隐藏
「Codeforces Round 460 div2」D. Substring - 拓扑排序+动态规划 | Bill Yang's Blog

路终会有尽头,但视野总能看到更远的地方。

0%

「Codeforces Round 460 div2」D. Substring - 拓扑排序+动态规划

题目大意

    给出一张有向图,每个结点上有一个a~z小写字母,询问图中的一条路径,使得这条路径上的出现次数最多的字母最多,输出最多的出现次数。


题目分析

就是求这张图上一条路径中最多的众数。
众数是没法$O(n)$求的,但因为本题中众数只可能是小写字母,因此不妨将众数压入状态。
$f[i,j]$表示$i$号结点,路径上众数字母为$j$的出现次数。
沿着DAG转移,有环则无解。
转移的时候对于每个字母从后继结点中选出一个最大的更新。

想到了状态没深入想转移就放弃了,还是在lxy的提醒下想出来的,真是太菜了。


代码

注意自环。

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
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;

inline const int Get_Int() {
int num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}

const int maxn=300005;

int n,m,bj=0,Dfn[maxn],Lowlink[maxn],Stack[maxn],Instack[maxn],step=0,top=0,f[maxn][26];
vector<int> edges[maxn],fedges[maxn],Top;
char a[maxn];

void AddEdge(int x,int y) {
edges[x].push_back(y);
fedges[y].push_back(x);
}

void Tarjan(int Now) {
Dfn[Now]=Lowlink[Now]=++step;
Stack[++top]=Now;
Instack[Now]=1;
for(int Next:edges[Now]) {
if(!Dfn[Next]) {
Tarjan(Next);
Lowlink[Now]=min(Lowlink[Now],Lowlink[Next]);
} else if(Instack[Next])Lowlink[Now]=min(Lowlink[Now],Dfn[Next]);
}
if(Dfn[Now]==Lowlink[Now]) {
int y,size=0;
do {
y=Stack[top--];
Instack[y]=0;
size++;
Top.push_back(y);
} while(y!=Now);
if(size>1)bj=1;
}
}

int main() {
n=Get_Int();
m=Get_Int();
for(int i=1; i<=n; i++)while(!isalpha(a[i]))a[i]=getchar();
for(int i=1; i<=m; i++) {
int x=Get_Int(),y=Get_Int();
AddEdge(x,y);
if(x==y)bj=1;
}
if(bj) {
puts("-1");
return 0;
}
for(int i=1; i<=n; i++)
if(!Dfn[i])Tarjan(i);
if(bj) {
puts("-1");
return 0;
}
for(int i=1; i<=n; i++)f[i][a[i]-'a']=1;
int ans=1;
for(int Now:Top)
for(int Next:fedges[Now])
for(int i=0; i<26; i++) {
f[Next][i]=max(f[Next][i],f[Now][i]+(a[Next]-'a'==i));
ans=max(ans,f[Next][i]);
}
printf("%d\n",ans);
return 0;
}

姥爷们赏瓶冰阔落吧~