201612-2 工资计算
- C++
- 枚举
- 二分
- 总结
本题链接:201612-2 工资计算
本博客给出本题截图:
C++
两种方法,枚举或二分
枚举
#include <iostream> #include <algorithm> using namespace std; int get(int x) { if (x <= 3500) return x; int a[] = {0, 1500, 4500, 9000, 35000, 55000, 80000, 1000000}; int b[] = {0, 3, 10, 20, 25, 30, 35, 45}; x -= 3500; int tax = 0; for (int i = 1; i < 8; i ++ ) if (x >= a[i - 1]) tax += (min(x, a[i]) - a[i - 1]) / 100 * b[i]; return x + 3500 - tax; } int main() { int T; cin >> T; for (int i = 0; ; i += 100) if (get(i) == T) { cout << i << endl; break; } return 0; }
二分
#include <iostream> using namespace std; int get(int n) { if (n <= 3500) return n; else { int a[8] = {0, 1500, 4500, 9000, 35000, 55000, 80000, 1000000000}; double b[8] = {0, 0.03, 0.1, 0.2, 0.25, 0.3, 0.35, 0.45}; double res = 0; n -= 3500; for (int i = 1; i <= 7; i ++ ) if (a[i] <= n) res += (a[i] - a[i - 1]) * b[i]; else { res += (n - a[i - 1]) * b[i]; break; } return n - res + 3500 + 1e-6; } } int main() { int n; cin >> n; int l = 0, r = 1e9; while (l < r) { int mid = l + r >> 1; if (get(mid) >= n) r = mid; else l = mid + 1; } cout << r << endl; return 0; }
总结
二分法
二分算法模板