Codeforces - Substring

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≤300000), 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
outputCopy
3
inputCopy
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
outputCopy
-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
outputCopy
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.


就是要我们找到一条路径,里面出现最多的字母,出现的次数最多。

很明显,如果有环,直接输出-1

如果没有环,直接拓扑排序递推即可。就相当于在DAG图上DP。


AC代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=3e5+10;
int n,m,dag[N],val[N][30],cnt,res;
char str[N];
int head[N],nex[N],w[N],to[N],tot;
inline void add(int a,int b){to[++tot]=b; nex[tot]=head[a]; head[a]=tot;}
void top_sort(){
	queue<int> q;	for(int i=1;i<=n;i++)	if(!dag[i]) q.push(i),cnt++;
	while(q.size()){
		int u=q.front();	q.pop();
		for(int i=head[u];i;i=nex[i]){
			if(--dag[to[i]]==0)	q.push(to[i]),cnt++;
			for(int j=0;j<26;j++)
				val[to[i]][j]=max((str[to[i]]-'a'==j)+val[u][j],val[to[i]][j]);
		}
	}
	if(cnt!=n){puts("-1"); exit(0);}
}
signed main(){
	cin>>n>>m;	scanf("%s",str+1);
	for(int i=1;i<=n;i++)	val[i][str[i]-'a']++;
	for(int i=1,a,b;i<=m;i++)	cin>>a>>b,add(a,b),dag[b]++;
	top_sort();
	for(int i=1;i<=n;i++)	for(int j=0;j<26;j++)	res=max(res,val[i][j]);
	cout<<res<<endl;
	return 0;
}
发布了416 篇原创文章 · 获赞 228 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/103766234
今日推荐