P1972 【[SDOI2009]HH的项链】

树状数组裸题,与pingpong相似,不过需要离线查询

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 using namespace std;
 5 struct lie{
 6     int qi,jie;
 7     int wei;
 8 }e[555555];
 9 int cmp(lie p,lie q)
10 {
11     return p.jie<q.jie;
12 }
13 int n,m;
14 int a[555555],guo[5555555];
15 int b[1111111],c[1111111];
16 int tree[555555];
17 int lowbit(int x)
18 {
19     return x&(-x);
20 }
21 void add(int x,int y)
22 {
23     while(x<=n)
24     {
25         tree[x]+=y;
26         x+=lowbit(x);
27     }
28 }
29 int sum(int x)
30 {
31     int ans=0;
32     while(x!=0)
33     {
34         ans+=tree[x];
35         x-=lowbit(x);
36     }
37     return ans;
38 }
39 int main()
40 {
41     scanf("%d",&n);
42     for(int i=1;i<=n;++i) scanf("%d",&a[i]);
43     scanf("%d",&m);
44     for(int i=1;i<=m;++i)
45     {
46         scanf("%d%d",&e[i].qi,&e[i].jie);
47         e[i].wei=i;
48     }
49     sort(e+1,e+m+1,cmp);
50     int next=1;
51     for(int i=1;i<=m;++i)
52     {
53         for(int j=next;j<=e[i].jie;++j)
54         {
55             if(b[a[j]]) 
56             {
57                 add(c[a[j]],-1);
58             }
59             add(j,1);
60             b[a[j]]=1;
61             c[a[j]]=j;
62         }
63         next=e[i].jie+1;
64         guo[e[i].wei]=sum(e[i].jie)-sum(e[i].qi-1);
65     }
66     for(int i=1;i<=m;++i) printf("%d\n",guo[i]);
67     return 0;
68 }

猜你喜欢

转载自www.cnblogs.com/zytwan/p/9930736.html