解法:
记录一下tle的代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define endl '\n'
bool check(vector<int>& a, int l,int k) {int sum = 0;for (int i = 0; i < a.size() && l <= a[i]; i++) {sum += a[i] / l;if (sum >= k) return true;}return false;
}
int main() {ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);int n, k;cin >> n >> k;long long sum = 0, l;vector<int> vec(n, 0);for (int i = 0; i < n; i++) {cin >> vec[i];sum += vec[i];}l = sum / k;sort(vec.begin(), vec.end(),greater<int>());while (l>0&&!check(vec,l,k)){l--;}if (l == 0) {cout << sum -k << endl;}else {cout << sum - l * k << endl;}return 0;
}
解法:
可能-1太慢了,二分答案
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define endl '\n'
bool check(vector<int>& a, int mid, int k) {long long sum = 0;for (int i = 0; i < a.size(); i++) {sum += a[i] / mid;if (sum >= k) return true;}return false;
}
signed main() {ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);int n, k;long long sum = 0;cin >> n >> k;vector<int> vec(n, 0);for (int i = 0; i < n; i++){cin >> vec[i];sum += vec[i];}int l = 1, r = *max_element(vec.begin(), vec.end());long long mid, result=0;while (l <= r) {mid = l + (r - l) / 2;if (check(vec, mid, k)) {result = mid;l = mid + 1;}else {r = mid - 1;}}cout << sum - result * k << endl;return 0;
}