B 猜数
题目地址:
基本思路:
这题可以直接贪心从小到大改为9就行了,比较简单。
这里我们考虑怎样进一步优化时间复杂度,由于只有0 ~ 9几个数,我们考虑用个桶维护一下每种增加量的出现次数,然后对于每个增加量从9到0数学方法计算最大贪心就好了。
参考代码
#pragma GCC optimize(2) #pragma GCC optimize(3) #include <bits/stdc++.h> using namespace std; #define IO std::ios::sync_with_stdio(false) #define ll long long #define rep(i, l, r) for (int i = l; i <= r; i++) #define per(i, l, r) for (int i = l; i >= r; i--) #define mset(s, _) memset(s, _, sizeof(s)) #define pb push_back #define pii pair <int, int> #define mp(a, b) make_pair(a, b) #define INF 0x3f3f3f3f inline int read() { int x = 0, neg = 1; char op = getchar(); while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); } while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); } return neg * x; } inline void print(int x) { if (x < 0) { putchar('-'); x = -x; } if (x >= 10) print(x / 10); putchar(x % 10 + '0'); } const int maxn = 1e6 + 10; int n,m,a[maxn]; int memo[10]; signed main() { IO; n = read(); m = read(); int sum = 0; rep(i,1,n){ a[i] = read(); memo[9 - a[i]]++; sum += a[i]; } int cnt = 0; per(i,9,0){ if(sum >= m) break; int all = memo[i] * i; if(sum + all < m) sum += all,cnt += memo[i]; else{ int num = ceil((double)(m - sum)/(double)i); cnt += num; sum += num * i; } } cout << cnt << '\n'; return 0; }