在昨晚 CF Round 640 div4 E 题的官方题解中,它是这么说的:
The intended solution for this problem uses O(n2) time and O(n) memory. Firstly, let's calculate cnti for each i from 1 to n, where cnti is the number of occurrences of i in a. This part can be done in O(n).
Then let's iterate over all segments of a of length at least 2 maintaining the sum of the current segment sum. We can notice that we don't need sums greater than n because all elements do not exceed n. So if the current sum does not exceed n then add cntsum to the answer and set cntsum:=0 to prevent counting the same elements several times. This part can be done in O(n2).
官方代码也是按这个写的:
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
vector<int> cnt(n + 1);
int ans = 0;
for (auto &it : a) {
cin >> it;
++cnt[it];
}
for (int l = 0; l < n; ++l) {
int sum = 0;
for (int r = l; r < n; ++r) {
sum += a[r];
if (l == r) continue;
if (sum <= n) {
ans += cnt[sum];
cnt[sum] = 0;
}
}
}
cout << ans << endl;
}
}
但是我当时没敢这么写,因为这道题有多组数据,我认为时间复杂度是 O(n2t)。
(t≤1000,n≤8000)
那么请问为什么能过呢/kk