【GOJ 3002】颜色

题目

正解

可以先假设每个区间中所有颜色都出现,然后减掉多算的答案。对每种颜色记录它出现的位置,则相邻两个位置间的所有区间都要减去,时间复杂度(O(n))

代码

#include<bits/stdc++.h>
using namespace std;
using LL=long long;
const LL N=1e5+5;
LL a[N],f[N];
int main() {
	LL n;
	scanf("%lld",&n);
	for(LL i=1; i<=n; i++) {
		scanf("%lld",a+i);
	}
	LL ans=0;
	for(LL i=1; i<=n; i++) {
		ans+=(n-i+1)*(i-f[a[i]]),f[a[i]]=i;
	}
	printf("%lld",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/Sam2007/p/13385256.html