Codeforce 750E1
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
91
92
93
94
95
96
97
98
99
100
101
102
103
using namespace std;
const int maxn = 1000050;
typedef pair<int, int> P;
typedef long long ll;
const int inf = 0x3f3f3f3f;
char S[maxn];
int g[maxn][5][5];
char str[6] = "2019";
int ans[5];
int pa(int i, int j, char c) //
{
if (i == 4)
return c == '8';
if (j > i + 1)
return inf;
if (i < j)
{
if (c != str[i])
return inf;
return 0;
}
if (i == 3 && c == '8')
return 1;
return c == str[i];
}
void init(int k, int l, int r) // 初始化线段树,线段树节点维护的内容是
{
if (l == r)
{
for (int i = 0; i <= 4; ++i)
for (int j = i; j <= 4; ++j)
g[k][i][j] = pa(i, j, S[l - 1]);
return;
}
int mid = (l + r) / 2, ls = k * 2, rs = k * 2 + 1;
init(ls, l, mid);
init(rs, mid + 1, r);
for (int i = 0; i <= 4; i++)
for (int j = i; j <= 4; j++)
{
g[k][i][j] = inf;
for (int k1 = i; k1 <= j; k1++)
{
int l1 = g[ls][i][k1];
int r1 = g[rs][k1][j];
g[k][i][j] = min(g[k][i][j], l1 + r1);
}
}
}
void query(int k, int s, int e, int l, int r)
{
if (l <= s && e <= r)
{
int aa[5];
for (int i = 0; i <= 4; i++)
{
aa[i] = inf;
for (int j = 0; j <= i; j++)
aa[i] = min(aa[i], ans[j] + g[k][j][i]);
}
for (int i = 0; i <= 4; i++)
ans[i] = aa[i];
return;
}
int mid = (s + e) / 2, ls = k * 2, rs = k * 2 + 1;
if (l <= mid)
query(ls, s, mid, l, r);
if (r > mid)
query(rs, mid + 1, e, l, r);
}
char s[maxn];
int main()
{
int n,m,i,l,r;
scanf("%d %d %s", &n, &m, s);
for(int i=0; i<n; i++)
S[i]=s[n-i-1];
init(1, 1, n);
while (m--)
{
scanf("%d%d", &l, &r);
l=n-l+1;
r=n-r+1;
swap(l,r);
for (i = 0; i <= 4; i++)
ans[i] = inf;
ans[0] = 0;
query(1, 1, n, l, r);
if(ans[4]>n)
printf("-1\n");
else
printf("%d\n",ans[4]);
//printf("%d\n", ans[4] > n ? -1 : ans[4]);
}
return 0;
}
1 | //codeforce 750E(https://codeforces.com/contest/750/problem/E) |