codeforces1101B. Accordion 贪心 状态机解题法 算法日常[34/100]

题目链接

codeforces1101B. Accordion

题意

删除一些字符,从而找出[::]这种结构,::的两点中可以有|,而且要最多的这样的|,以便构成最长的满足条件的串

题解

通法,状态机解题法

  • 设计状态机(详见下面的代码和解释)
  • 找到了[:之后开始记录|状态
  • 让每次成功匹配第二个冒号的时候更新|的个数值precnt = cnt
  • 让每次成功匹配整个串的时候维护答案ans = precnt + 4;

tutorial

tutorial比较巧妙,一般不易想到

AC代码

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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, a, b) for(int i = int(a); i <= int(b); ++i)
#define per(i, b, a) for(int i = int(b); i >= int(a); --i)
#define mem(x, y) memset(x, y, sizeof(x))
#define SZ(x) x.size()
#define mk make_pair
#define pb push_back
#define fi first
#define se second
const ll mod=1000000007;
const int inf = 0x3f3f3f3f;
inline int rd(){char c=getchar();int x=0,f=1;while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}return x*f;}
inline ll qpow(ll a,ll b){ll ans=1%mod;for(;b;b>>=1){if(b&1)ans=ans*a%mod;a=a*a%mod;}return ans;}
const int M = 5e5+10;
char s[M];
int ans = -1;

int main(){
scanf("%s",s);
int state = 0,precnt = 0,cnt = 0;
rep(i,0,strlen(s)-1){
switch(state){
case 0 : if(s[i]==char(91)) state = 1;
break;
case 1 : if(s[i]==char(58)) state = 2;
break;
case 2 :
if(s[i] == char(124)) cnt++;
else if(s[i] == char(58)){
precnt = cnt;
state = 3;
}
break;
case 3 :
if(s[i] == char(124)) cnt++;
else if(s[i] == char(58)){
precnt = cnt;
state = 3;
} else if(s[i] == char(93)){
ans = precnt + 4;
}
break;
}
}
printf("%d\n",ans);

return 0;
}