社区讨论

为啥我的代码答案减一就过了

P2709【模板】莫队 / 小B的询问参与者 4已保存回复 3

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
3 条
当前快照
1 份
快照标识符
@lo987f2c
此快照首次捕获于
2023/10/28 07:10
2 年前
此快照最后确认于
2023/10/28 07:10
2 年前
查看原帖
CPP
#include<bits/stdc++.h>
using namespace std;

int n, m, k;
int a[50005], id[50005];
int cnt[50005], res[50005];
int len;

struct Ask{
	int l, r, id, pos;
}ask[50005];

template<typename T>
inline void read(T&x){
    x = 0; char q; bool f = 1;
    while(!isdigit(q = getchar()))  if(q == '-')    f = 0;
    while(isdigit(q)){
        x = (x<<3) + (x<<1) + (q^48);
        q = getchar();
    }
    x=f?x:-x;
}

template<typename T>
inline void write(T x){
    if(x < 0){
        putchar('-');
        x = -x;
    }
    if(x > 9)   write(x/10);
    putchar(x%10+'0');
}

inline bool cmp(Ask a, Ask b){
	if(a.pos != b.pos)	return a.pos < b.pos;
	return a.r > b.r;
}

int main(){
	read(n), read(m), read(k);
	len = sqrt(n);
	for(register int i = 1; i <= n; ++i)	read(a[i]);
	for(register int i = 1; i <= m; ++i){
		read(ask[i].l), read(ask[i].r);
		ask[i].id = i, ask[i].pos = (ask[i].l-1)/len+1;
	}
	sort(ask+1, ask+m+1, cmp);
	int l = 0, r = 0;
	long long ans = 0;
	for(register int i = 1; i <= m; ++i){
		while(l > ask[i].l)	--l, ++cnt[a[l]], ans += 2*cnt[a[l]]-1;
		while(r < ask[i].r)	++r, ++cnt[a[r]], ans += 2*cnt[a[r]]-1;
		while(l < ask[i].l)	--cnt[a[l]], ans -= 2*cnt[a[l]]+1, ++l;
		while(r > ask[i].r)	--cnt[a[r]], ans -= 2*cnt[a[r]]+1, --r;
		res[ask[i].id] = ans;
	}
	for(register int i = 1; i <= m; ++i)	write(res[i]-1), puts("");
	return 0;
}

回复

3 条回复,欢迎继续交流。

正在加载回复...