HH的项链 BZOJ1878

树状数组

 1 #include<bits/stdc++.h>
 2 const int N=2000001;
 3 const int M=2000001;
 4 using namespace std;
 5 int a[N],m,n,tr[N];
 6 int last[2000001];
 7 struct question{
 8     int l,r,id;
 9     bool operator < (const question b)const
10     {
11     if(r==b.r)return l<b.l;
12     else return r<b.r;
13     }
14 }q[M];
15 
16 #define lowbit(x) (x&(-x))
17 
18 inline void add(int pos,int x){
19     for(;pos<=n;pos+=lowbit(pos)){
20     tr[pos]+=x;
21     }
22 }
23 
24 inline int query(int pos){
25     int ans=0;
26     for(;pos;pos-=lowbit(pos)){
27     ans+=tr[pos];
28     }
29     return ans;
30 }
31 int ans[M];
32 
33 int main()
34 {
35     scanf("%d",&n);
36     for(int i=1;i<=n;i++)
37     scanf("%d",&a[i]);
38     scanf("%d",&m);
39     for(int i=1;i<=m;i++){
40     scanf("%d%d",&q[i].l,&q[i].r);
41     q[i].id=i;
42     }
43     sort(q+1,q+m+1);
44     int nowques=1;
45     for (int i=1;i<=n;i++){
46         add(i,1);
47         if (last[a[i]]) add(last[a[i]],-1);
48         last[a[i]]=i;
49         int tmp=query(i);
50         while (q[nowques].r==i&&nowques<=m){
51             ans[q[nowques].id]=tmp-query(q[nowques].l-1);
52             nowques++;
53         }
54     }
55     for(int i=1;i<=m;i++)printf("%d\n",ans[i]);
56     return 0;
57 }
View Code

莫队

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <set>
 5 using namespace std;
 6 typedef long long ll;
 7 #define space putchar(' ')
 8 #define enter putchar('\n')
 9 template <class T>
10 void read(T &x){
11     char c;
12     bool op = 0;
13     while(c = getchar(), c < '0' || c > '9')
14     if(c == '-') op = 1;
15     x = c - '0';
16     while(c = getchar(), c >= '0' && c <= '9')
17     x = x * 10 + c - '0';
18     if(op) x = -x;
19 }
20 template <class T>
21 void write(T x){
22     if(x < 0) x = -x, putchar('-');
23     if(x >= 10) write(x / 10);
24     putchar('0' + x % 10);
25 }
26 const int N = 50005, M = 200005, B = 233;
27 int n, m, a[N], sum, ans[M], cnt[1000005];
28 #define bel(x) ((x - 1) / B + 1)
29 struct query {
30     int id, l, r;
31     bool operator < (const query &b) const{
32     return bel(l) == bel(b.l) ? r < b.r : l < b.l;
33     }
34 } q[M];
35 void add(int x){
36     if(!cnt[x]) sum++;
37     cnt[x]++;
38 }
39 void del(int x){
40     cnt[x]--;
41     if(!cnt[x]) sum--;
42 }
43 int main(){
44     read(n);
45     for(int i = 1; i <= n; i++) read(a[i]);
46     read(m);
47     for(int i = 1; i <= m; i++)
48     q[i].id = i, read(q[i].l), read(q[i].r);
49     sort(q + 1, q + m + 1);
50     int pl = 1, pr = 0;
51     for(int i = 1; i <= m; i++){
52     while(pl < q[i].l) del(a[pl++]);
53     while(pl > q[i].l) add(a[--pl]);
54     while(pr < q[i].r) add(a[++pr]);
55     while(pr > q[i].r) del(a[pr--]);
56     ans[q[i].id] = sum;
57     }
58     for(int i = 1; i <= m; i++)
59     write(ans[i]), enter;
60     return 0;
61 }
View Code

猜你喜欢

转载自www.cnblogs.com/weiyanpeng/p/9393558.html