求助TLE
查看原帖
求助TLE
527206
wjh2022楼主2024/1/25 09:37

rt,第6个点T了,是代码有问题还是需要卡常?

(帮同学问的)

#include<bits/stdc++.h>
using namespace std;
int n,m,a[200005],ans[200005],x,l=1,r=0,cnt[1000005],s,pos[200005];
struct kkk{
	int l,r,th;
}q[100005];
int read(){
	int k=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){k=k*10+ch-'0';ch=getchar();}
	return k*f;
}
bool cmp(kkk a,kkk b){
	if(pos[a.l]==pos[b.l]){
		return (pos[a.l]&1)?a.r<b.r:a.r>b.r;
	}
	return a.l<b.l;
}
void add(int k){
	x+=(2*cnt[a[k]]+1)*a[k];
	cnt[a[k]]++;
}
void del(int k){
	x-=(2*cnt[a[k]]-1)*a[k];
	cnt[a[k]]--;
}
int main(){
	std::ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	s=sqrt(n);
	for(int i=1;i<=m;i++){
		pos[i]=(i-1)/s+1;
	}
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	for(int i=1;i<=m;i++){
		cin>>q[i].l>>q[i].r;
		q[i].th=i;
	}
	sort(q+1,q+m+1,cmp);	
	for(int i=1;i<=m;i++){
		while(q[i].l<l)add(--l);
		while(q[i].r>r)add(++r);
		while(q[i].l>l)del(l++);
		while(q[i].r<r)del(r--);
		ans[q[i].th]=x;
	}
	for(int i=1;i<=m;i++){
		cout<<ans[i]<<"\n";
	}
	return 0;
}
2024/1/25 09:37
加载中...