NewCoder 多校1 J Different Integers (樹狀陣列+貢獻思維)
阿新 • • 發佈:2018-12-12
#include<bits/stdc++.h> using namespace std; #define debug puts("YES"); #define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++) #define read(x,y) scanf("%d%d",&x,&y) #define ll long long #define lrt int l,int r,int rt #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 #define root l,r,rt const int maxn =2e5+5; const int mod=1e9+7; const ll INF =1e18+7; ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;} ll gcd(ll x,ll y){return y?gcd(y,x%y):x;} /* 題目大意:給定一個序列, 和m個查詢,每次查詢對l,r分別代表, 1~l,和r~n之間不同數字的個數。 首先將陣列倍增下,查詢也處理下,然後離線。 考慮如果左端固定只查詢右端,或者說左端固定為1, 則對於所有查詢值怎麼計算?只要在數字第一次出現的地方累加貢獻1就可以了。 但當左端點移動呢?貢獻消去,在下一個數字出現的地方累加貢獻, 不斷的迭代下去就行了,複雜度: O(nlogn+m*logn*logn) */ int n,m,a[maxn]; int show[maxn],rep[maxn]; ///bit int bit[maxn]; int lowbit(int x){return x&(-x);} void add(int x,int d){for(;x<maxn;bit[x]+=d,x+=lowbit(x));} int sum(int x){int ret=0;for(;x>0;ret+=bit[x],x-=lowbit(x));return ret;} ///查詢結構 struct qy { int l,r,id; bool operator<(const qy& y) const { if(l==y.l) return r<y.r; return l<y.l; } }q[maxn]; int ret[maxn]; int main() { while(scanf("%d%d",&n,&m)!=EOF) { memset(show,0,sizeof(show)); for(int i=1;i<=n;i++) scanf("%d",&a[i]),a[i+n]=a[i]; for(int i=2*n;i>=1;i--) rep[i]=show[a[i]],show[a[i]]=i; for(int i=0;i<m;i++) { scanf("%d%d",&q[i].r,&q[i].l); q[i].id=i;q[i].r+=n; } sort(q,q+m); memset(show,0,sizeof(show)); memset(bit,0,sizeof(bit)); for(int i=1;i<=2*n;i++) if(show[a[i]]==0) {add(i,1);show[a[i]]=1;} int cur=1; for(int i=0;i<m;i++) { while(cur<q[i].l) { add(cur,-1),add(rep[cur],1); cur++; } ret[q[i].id]=sum(q[i].r); } for(int i=0;i<m;i++) printf("%d\n",ret[i]); } return 0; }