目录
- 1 介绍
- 2 训练
1 介绍
本博客用来记录前缀和、差分、二分相关的题目。
2 训练
题目1:99激光炸弹
C++代码如下,
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>using namespace std;const int N = 5010;int s[N][N];int main() {int n, R;scanf("%d%d", &n, &R);R = min(R, 5001);for (int i = 0; i < n; ++i) {int x, y, w;scanf("%d%d%d", &x, &y, &w);x++, y++;s[x][y] += w;}for (int i = 1; i <= 5001; ++i) {for (int j = 1; j <= 5001; ++j) {s[i][j] += s[i-1][j] + s[i][j-1] - s[i-1][j-1];}}int res = 0;for (int i = R; i <= 5001; ++i) {for (int j = R; j <= 5001; ++j) {res = max(res, s[i][j] - s[i-R][j] - s[i][j-R] + s[i-R][j-R]);}}printf("%d\n", res);return 0;
}
题目2:100增减序列
C++代码如下,
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>using namespace std;const int N = 100010;typedef long long LL;int n;
int a[N], b[N];int main() {scanf("%d", &n);for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);for (int i = 1; i <= n; ++i) b[i] = a[i] - a[i-1];LL p = 0, q = 0;for (int i = 2; i <= n; ++i) {if (b[i] > 0) p += b[i];else q -= b[i];}cout << max(p, q) << endl;cout << abs(p - q) + 1 << endl;return 0;
}
题目3:102最佳牛围栏
C++代码如下,
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>using namespace std;const int N = 100010;int n, F;
double a[N], s[N];bool check(double avg) {for (int i = 1; i <= n; ++i) s[i] = s[i-1] + a[i] - avg;double mins = 0;for (int k = F; k <= n; ++k) {mins = min(mins, s[k-F]);if (s[k] >= mins) return true;}return false;
}int main() {scanf("%d%d", &n, &F);double l = 0, r = 0;for (int i = 1; i <= n; ++i) {scanf("%lf", &a[i]);r = max(r, a[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;
}
题目4:113特殊排序
C++代码如下,
// Forward declaration of compare API.
// bool compare(int a, int b);
// return bool means whether a is less than b.class Solution {
public:vector<int> specialSort(int N) {vector<int> res(1, 1);for (int i = 2; i <= N; ++i) {int l = 0, r = res.size() - 1;while (l < r) {int mid = l + r + 1 >> 1;if (compare(res[mid], i)) l = mid;else r = mid - 1;}res.push_back(i);for (int j = res.size() - 2; j > r; j--) swap(res[j], res[j+1]);if (compare(i, res[r])) swap(res[r], res[r+1]);}return res;}
};