D. Substring
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path’s value as the number of the most frequently occurring letter. For example, if letters on a path are “abaca”, then the value of that path is 3. Your task is find a path whose value is the largest.
Input
The first line contains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting that the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.
Then m lines follow. Each line contains two integers x, y (1 ≤ x, y ≤ n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.
Examples
inputCopy
5 4
abaca
1 2
1 3
3 4
4 5
output
3
inputCopy
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
output
-1
inputCopy
10 14
xzyzyzyzqx
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 10
3 9
10 9
4 6
1 10
2 8
3 7
output
4
Note
In the first sample, the path with largest value is 1 → 3 → 4 → 5. The value is 3 because the letter ‘a’ appears 3 times.
题目链接:http://codeforces.com/problemset/problem/919/D
题意:输入一个 n,m。分别代表有 n 个点,m 条有向边。接下来输入一个长度为 n 的字符串 S。Si 代表点 i 上的字符为 Si。最后输入 m 行 x ,y,代表有一条边从 x 指向 y。
问:输出一条路径上的最大权值(一条路径上的权值等于在这条路径出现最多次字母的次数),若有环则输出 -1。
数据范围:1 ≤ n, m ≤ 300 000 , 1 ≤ x, y ≤ n。
解题思路:可以用拓扑排序验证是否有环,若进队列的点的个数 等于 总点个数,则说明该图没有环,反之则有环。接着我们可以在拓扑排序的过程维护答案。
dp[i][j]
d
p
[
i
]
[
j
]
:代表到 点 i 时,字母 j 出现的最大次数。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 4e5 + 5;
vector<int> G[maxn];
int n,m,d[maxn],seq[maxn],dp[maxn][30];
char s[maxn];
int ma = 0;
void Init(){
cin >> n >> m >> s + 1;
for(int i = 1;i <= m;i++){
int x,y;
cin >> x >> y;
d[y]++;
G[x].push_back(y);
}
}
void Slove(){
int head = 1,tail = 0;
for(int i = 1;i <= n;i++){
if(d[i] == 0){
seq[++tail] = i;
dp[i][s[i] - 'a'] = 1;
}
}
while(head <= tail){
int u = seq[head];
for(int i = 0;i < G[u].size();i++){
int v = G[u][i];
d[v]--;
if(d[v] == 0){//不仅是在 d[v] = 0,才转移,而是每个状态都需要转移。
seq[++tail] = v;
}
for(int j = 0;j < 26;j++){
if(s[v] - 'a' == j){
dp[v][j] = max(dp[v][j],dp[u][j] + 1); //dp的精髓是 取 max 或 min,要不然就是递推了。
}
else dp[v][j] = max(dp[v][j],dp[u][j]);
ma = max(ma,dp[v][j]);
}
}
head++;
}
if(tail != n) cout << "-1" << endl;//判断是否有环。
else cout << ma << endl;
}
int main(){
Init();
Slove();
return 0;
}