遇到一个 START,一定能够和前面的 k 个 KICK 都构成 KICK*START,因此答案累加上 k
时间复杂度
线性扫描:O(n)
C++ 代码
#include<iostream> usingnamespacestd;
int t; string s;
intsolve(){ int n = s.length(); int k = 0, ans = 0; for (int i = 0; i < n; i++) { if (s.substr(i, 4) == "KICK") k++; if (s.substr(i, 5) == "START") ans += k; } return ans; }
intmain(){ cin >> t; for (int i = 1; i <= t; i++) { cin >> s; printf("Case #%d: %d\n", i, solve()); } return0; }
#include<iostream> usingnamespacestd; constint N = 1e3 + 10; typedeflonglong LL;
int t, c[N][N], n;
LL solve(){ LL ans = 0; for (int d = -(n - 1); d <= n - 1; d++) { LL sum = 0; for (int i = 0; i < n; i++) { int j = i + d; if (j < 0 || j >= n) continue; sum += c[i][j]; } ans = max(sum, ans); } return ans; }
intmain(){ cin >> t; for (int i = 1; i <= t; i++) { cin >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> c[i][j]; } } printf("Case #%d: %lld\n", i, solve()); } return0; }
LL solve(){ LL ans = 1e18, pre, cur; for (int l = 0; l < w; l++) { int r = l + w; int mid = (l + r - 1) >> 1; if (l == 0) { cur = 0; for (int i = l; i < r; i++) { cur += abs(x[i] - x[mid]); } ans = min(ans, cur); pre = cur; } else { LL a = abs(x[l - 1] - x[mid - 1]); LL b = w / 2 * abs(x[mid - 1] - x[mid]); LL c = abs(x[r - 1] - x[mid]); LL d = (w - 1) / 2 * abs(x[mid - 1] - x[mid]);
cur = pre - a - b + c + d; ans = min(ans, cur); pre = cur; } } return ans; }
intmain(){ cin >> t; for (int i = 1; i <= t; i++) { cin >> w >> n; for (int i = 0; i < w; i++) { cin >> x[i]; x[i + w] = x[i] + n; } sort(x, x + 2 * w);
printf("Case #%d: %lld\n", i, solve()); } return0; }