题目链接:https://ac.nowcoder.com/acm/contest/1084/B

题意

5e5的区间,5e5个询求[l,r]区间内出现过的数的和

思路

1s时限,莫队显然会T

我们可以将询问按r排序,维护每个数最后出现的位置,并用树状数组维护前缀和即可

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<vector>
#include<map>
#include<functional>
#include<unordered_map> #define fst first
#define sc second
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lc root<<1
#define rc root<<1|1 using namespace std; typedef double db;
typedef long double ldb;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PI;
typedef pair<ll,ll> PLL; const db eps = 1e-6;
const int mod = 998244353;
const int maxn = 5e5+100;
const int maxm = 2e6+100;
const int inf = 0x3f3f3f3f;
const db pi = acos(-1.0); int n,m;
int a[maxn];
ll tree[maxn];
int lowbit(int x){return x&(-x);}
void add(int x, ll c){
for(int i = x; i <= n; i+=lowbit(i)){
tree[i]+=c;
}
}
ll sum(int x){
ll ans = 0;
for(int i = x; i; i-=lowbit(i)){
ans+=tree[i];
}
return ans;
}
struct node{
int l, r;
int id;
node(){}
node(int l, int r, int id):l(l),r(r),id(id){}
}q[maxn];
int cnt[maxn];
int id[maxn];
ll ans[maxn];
bool cmp(node a, node b){return a.r<b.r;}
int main(){
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
for(int i = 1; i <= m; i++){
int l,r;
scanf("%d %d", &l, &r);
q[i]=node(l,r,i);
}
sort(q+1,q+1+m,cmp);
int lst = 1;
for(int i = 1; i <= m; i++){
for(int j = lst; j <= q[i].r; j++){
if(id[a[j]]){
add(id[a[j]],-a[j]);
}
id[a[j]]=j;
add(j,a[j]);
}lst=q[i].r+1;
ans[q[i].id]=sum(q[i].r)-sum(q[i].l-1);
}
for(int i = 1; i <= m; i++){
printf("%lld\n",ans[i]);
}
return 0;
}
/*
3 3
1 1 1
1 3
2 3
2 2
*/
05-11 19:55