1、求众数
#include <iostream> #include <unordered_map> using namespace std; int main(){ int n, num; cin >> n; int cnt = 0, ans = 0; unordered_map<int, int> m; for (int i = 0; i < n; i++) { cin >> num; m[num] ++; if (m[num] > cnt || m[num] == cnt && num < ans) ans = num; } cout << ans << endl; return 0; }
2、解方程
#include <iostream> using namespace std; int main(){ string str; cin >> str; int a = 0, b = 0, sym = 1, i = 0, flag = 1;//sym表示符号,flag=1表示等式左边,flag=-1表示等式右边 while (i < str.size()) { if (str[i] == '=') {//遇到等号时,sym置1规避之前的影响 flag = -1; sym = 1; } else if (str[i] == '+') sym = 1; else if (str[i] == '-') sym = -1; else { int t = 0; while (i < str.size() && str[i] >= '0' && str[i] <= '9') { t = 10 * t + (str[i] - '0'); i++; } if (i >= str.size()) {//当表达式最后是数字时单独判断,如4x-1=2x+3,否则会越界 b -= t * sym; break; } if (str[i] == 'x' && t == 0) a += sym * flag;//x前系数为正负1时单独判断处理 else if (str[i] == 'x') a += t * sym * flag;//处理系数 else {//处理常数 b += t * sym * flag; continue; } } i++; } if (a == 0 && b == 0) printf("infinite solutions\n"); else if (a != 0 && b % a == 0) printf("x=%d\n", -b / a); else printf("no solution\n"); return 0; }
3、骨牌
dp[i] = dp[i - 1] + dp[i - 2]
#include <iostream> using namespace std; const int MAXN = 10010; int dp[MAXN]; int main() { int n; cin >> n; dp[1] = 1; dp[2] = 2; for (int i = 3; i <= n; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } cout << dp[n]; return 0; }