分块——入门8

这里写图片描述

这个题目很考验分块的思想了,如果一个块里面都是相同的数,就给这一整个块标记,再进行处理即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//By Bibi
/// .-~~~~~~~~~-._ _.-~~~~~~~~~-.
/// __.' ~. .~ `.__
/// .'// \./ \\`.
/// .'// | \\`.
/// .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
/// .'//.-" `-. | .-' "-.\\`.
/// .'//______.============-.. \ | / ..-============.______\\`.
/// .'______________________________\|/______________________________`.
#include <bits/stdc++.h>
#define F(i, a, b) for (int i = (a); i < (b); ++i)
#define F2(i, a, b) for (int i = (a); i <= (b); ++i)
#define maxn 100010
#define maxm 1010
using namespace std;
int a[maxn],bl[maxn],n,blo,tag[maxm];
bool flag[maxm];
int read()
{
int sum=0,flag=1;
char c;
for(;c<'0'||c>'9';c=getchar())if(c=='-') flag=-1;
for(;c>='0'&&c<='9';c=getchar())sum=(sum<<1)+(sum<<3)+c-'0';
return sum*flag;
}
void reset(int p)
{
if (!flag[p]) return;
flag[p]=false;
F(i,p*blo,min(n,(p+1)*blo)) a[i]=tag[p];
}
int query(int l,int r,int c)
{
int ret=0;
if (flag[bl[l]]&&tag[bl[l]]==c) ret+=min(r+1,(bl[l]+1)*blo)-l;
else
{
reset(bl[l]);
F(i,l,min(r+1,(bl[l]+1)*blo))
{
ret+=a[i]==c;
a[i]=c;
}
}
if (bl[l]!=bl[r])
{
if (flag[bl[r]]&&tag[bl[r]]==c) ret+=r-bl[r]*blo+1;
else
{
reset(bl[r]);
F2(i,bl[r]*blo,r)
{
ret+=a[i]==c;
a[i]=c;
}
}
}
F(i,bl[l]+1,bl[r])
{
if (flag[i])
{
if (tag[i]==c) ret+=blo;
}
else
{
flag[i]=true;
F(j,i*blo,(i+1)*blo) ret+=a[j]==c;
}
tag[i]=c;
}
return ret;
}
int main()
{
n=read();
blo=sqrt(n);
F(i,0,n)
{
a[i]=read();
bl[i]=i/blo;
}
int num=(n+blo-1)/blo;
F(i,0,n)
{
int l,r,c;
l=read();r=read();c=read(); --l, --r;
printf("%d\n",query(l,r,c));
}
return 0;
}