题意是有n桶水,有一个容量为s升的桶,然后输入每桶水的容量,刚开始每桶水都是满的,现在要从n桶水中抽水把s升的桶倒满,问倒满后n桶水所剩的水最少是多少。
题解 : 二分答案,枚举是否满足条件。
#include <bits/stdc++.h> using namespace std; #define ll long long #define N 1010 int n; ll s, v[N]; bool check(ll x) { ll tot = 0; for (int i = 1; i <= n; ++i) { if (v[i] < x) return false; tot += v[i] - x; } return tot >= s; } int main() { while (scanf("%d%lld", &n, &s) != EOF) { for (int i = 1; i <= n; ++i) scanf("%lld", v + i); ll l = 0, r = 1e9, res = -1; while (l <= r) { ll mid = (l + r) >> 1; if (check(mid)) { res = mid; l = mid + 1; } else r = mid - 1; } printf("%lld\n", res); } return 0; }