求助:关于时间复杂度
  • 板块学术版
  • 楼主ez_lcw
  • 当前回复17
  • 已保存回复17
  • 发布时间2020/5/10 16:20
  • 上次更新2023/11/7 02:42:58
查看原帖
求助:关于时间复杂度
118318
ez_lcw楼主2020/5/10 16:20

在昨晚 CF Round 640 div4 E 题的官方题解中,它是这么说的:

The intended solution for this problem uses O(n2)O(n^2) time and O(n)O(n) memory. Firstly, let's calculate cnticnt_i for each ii from 11 to nn, where cnticnt_i is the number of occurrences of ii in aa. This part can be done in O(n)O(n).

Then let's iterate over all segments of a of length at least 22 maintaining the sum of the current segment sumsum. We can notice that we don't need sums greater than nn because all elements do not exceed nn. So if the current sum does not exceed nn then add cntsumcnt_{sum} to the answer and set cntsum:=0cnt_{sum}:=0 to prevent counting the same elements several times. This part can be done in O(n2)O(n^2).

官方代码也是按这个写的:

#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)O(n^2t)

t1000,n8000t\leq1000,n\leq8000

那么请问为什么能过呢/kk

2020/5/10 16:20
加载中...