562. 壁画 - AcWing题库
#include <bits/stdc++.h>
using namespace std;
const int N = 5e6 + 6;
//可以枚举每一种情况 因为都是相连的所以肯定是前缀和
int main() {int t;cin >> t;for (int i = 1; i <= t; i++) {char s[N];int n;cin >> n;int a[N]; // 修改这里,使用固定大小数组来保存前缀和cin>>s+1;for (int j = 1; j <= n; j++) {// cin >> s[j];a[j] = s[j] - '0';a[j] += a[j - 1];}int len = (n + 1) / 2;int res = 0;for (int h = len; h <= n; h++) {res = max(res, a[h] - a[h - len]); // 修改这里,计算前缀和数组的最大差值}cout << "Case #" << i << ": " << res << '\n';}return 0;
}
102. 最佳牛围栏 - AcWing题库
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int cows[N]; double sum[N];int n, m;bool check(double avg) {for (int i = 1; i <= n; i++) {sum[i] = sum[i - 1] + cows[i] - avg;}double minv = 0;for (int i = 0, j = m; j <= n; j++, i++) {//其实i是区间的左端点的左边,j是区间右端点minv = min(minv, sum[i]);//如果不是最小的话 下面哪一句就相当于直接加上了if(sum[j] - minv >= 0) return true;//存在的话//表示最小长度为m且以i结尾的子段} return false;
}int main() {scanf("%d %d", &n, &m);double l = 0, r = 2001;for (int i = 1; i <= n; i++) cin>>cows[i];while(r - l > 1e-5) {double mid = (l + r) / 2;if(check(mid)) l = mid;else r = mid;} printf("%d\n", (int)(r * 1000));return 0;
}