分块大法吼2
莫对大法,O(nsqrt(n))解决无修改的区间询问问题;
这个模板差不多吧:
1 #include<stdio.h>
2 #include<algorithm>
3 #include<string.h>
4 #include<math.h>
5 #include<string>
6 #include<iostream>
7 using namespace std;
8 typedef long long ll;
9
10 #define N 1000002
11 int n,m,c,block;
12 int a[N],pos[N];
13 int tmp[N];
14 struct data
15 {
16 int l,r,ans,id;
17 }q[N];
18 int cmp(data a,data b)
19 {
20 if (pos[a.l]==pos[b.l]) return a.r<b.r;
21 return pos[a.l]<pos[b.l];
22 }
23 int cmpid(data a,data b)
24 {
25 return a.id<b.id;
26 }
27 void solve()
28 {
29 int l=0,r=0;
30 int ans=0;
31 for (int i=1;i<=m;i++)
32 {
33 while (r<q[i].r)
34 {
35 r++;
36 tmp[a[r]]++;
37 if (tmp[a[r]]%2==0) ans++;
38 if (tmp[a[r]]%2==1&&tmp[a[r]]!=1) ans--;
39 }
40
41 while (l>q[i].l)
42 {
43 l--;
44 tmp[a[l]]++;
45 if (tmp[a[l]]%2==0) ans++;
46 if (tmp[a[l]]%2==1&&tmp[a[l]]!=1) ans--;
47 }
48
49 while (l<q[i].l)
50 {
51
52 tmp[a[l]]--;
53 if (tmp[a[l]]%2==1) ans--;
54 if (tmp[a[l]]%2==0&&tmp[a[l]]!=0) ans++;
55 l++;
56 }
57
58 while (r>q[i].r)
59 {
60 tmp[a[r]]--;
61 if (tmp[a[r]]%2==2) ans--;
62 if (tmp[a[r]]%2==0&&tmp[a[r]]!=0) ans++;
63 r--;
64 }
65 q[i].ans=ans;
66 }
67 }
68
69 int main()
70 {
71 scanf("%d%d%d",&n,&c,&m);
72 block=sqrt(n);
73 for (int i=1;i<=n;i++) pos[i]=(i-1)/block+1;
74 for (int i=1;i<=n;i++) scanf("%d",&a[i]);
75 for (int i=1;i<=m;i++)
76 scanf("%d%d",&q[i].l,&q[i].r),q[i].id=i;
77
78 sort(q+1,q+m+1,cmp);
79 solve();
80 sort(q+1,q+m+1,cmpid);
81 for (int i=1;i<=m;i++)
82 printf("%d\n",q[i].ans);
83 return 0;
84 }
3 #include<string.h>
4 #include<math.h>
5 #include<string>
6 #include<iostream>
7 using namespace std;
8 typedef long long ll;
9
10 #define N 1000002
11 int n,m,c,block;
12 int a[N],pos[N];
13 int tmp[N];
14 struct data
15 {
16 int l,r,ans,id;
17 }q[N];
18 int cmp(data a,data b)
19 {
20 if (pos[a.l]==pos[b.l]) return a.r<b.r;
21 return pos[a.l]<pos[b.l];
22 }
23 int cmpid(data a,data b)
24 {
25 return a.id<b.id;
26 }
27 void solve()
28 {
29 int l=0,r=0;
30 int ans=0;
31 for (int i=1;i<=m;i++)
32 {
33 while (r<q[i].r)
34 {
35 r++;
36 tmp[a[r]]++;
37 if (tmp[a[r]]%2==0) ans++;
38 if (tmp[a[r]]%2==1&&tmp[a[r]]!=1) ans--;
39 }
40
41 while (l>q[i].l)
42 {
43 l--;
44 tmp[a[l]]++;
45 if (tmp[a[l]]%2==0) ans++;
46 if (tmp[a[l]]%2==1&&tmp[a[l]]!=1) ans--;
47 }
48
49 while (l<q[i].l)
50 {
51
52 tmp[a[l]]--;
53 if (tmp[a[l]]%2==1) ans--;
54 if (tmp[a[l]]%2==0&&tmp[a[l]]!=0) ans++;
55 l++;
56 }
57
58 while (r>q[i].r)
59 {
60 tmp[a[r]]--;
61 if (tmp[a[r]]%2==2) ans--;
62 if (tmp[a[r]]%2==0&&tmp[a[r]]!=0) ans++;
63 r--;
64 }
65 q[i].ans=ans;
66 }
67 }
68
69 int main()
70 {
71 scanf("%d%d%d",&n,&c,&m);
72 block=sqrt(n);
73 for (int i=1;i<=n;i++) pos[i]=(i-1)/block+1;
74 for (int i=1;i<=n;i++) scanf("%d",&a[i]);
75 for (int i=1;i<=m;i++)
76 scanf("%d%d",&q[i].l,&q[i].r),q[i].id=i;
77
78 sort(q+1,q+m+1,cmp);
79 solve();
80 sort(q+1,q+m+1,cmpid);
81 for (int i=1;i<=m;i++)
82 printf("%d\n",q[i].ans);
83 return 0;
84 }
随性Code