D. Substring
time limit per test 3 seconds
memory limit per test 256 megabytes
You are given agraph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path'svalue as the number of the most frequently occurring letter. For example, ifletters on a path are "abaca", then thevalue of that path is 3. Your task isfind a path whose value is the largest.
Input
The first linecontains two positive integers n, m (1 ≤ n, m ≤ 300 000), denoting thatthe graph has n nodes and m directed edges.
The second linecontains a string s with onlylowercase 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 adirected edge from x to y. Note that x can be equal toy and there can be multiple edges betweenx and y. Also the graph can be not connected.
Output
Output a single line with a singleinteger denoting the largest value. If the value can be arbitrarily large,output -1 instead.
Examples
Input
5 4
abaca
1 2
1 3
3 4
4 5
Output
3
Input
6 6
xzyabc
1 2
3 1
2 3
5 4
4 3
6 4
Output
-1
Input
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 withlargest value is 1 → 3 → 4 → 5. The value is 3 because the letter 'a' appears 3 times.
【题意】
有一个具有n个节点,m条边的有向图,每个点对应一个小写字母,现在给出每个顶点对应的字母以及有向边的连接情况,求经过的某一条路上相同字母出现的最多次数。如果次数无限大,则输出-1.
第一步就是建图,之后判断这个图是否有环。有则输出-1,否则dp
dp就是单个判断每一个字母出现的最大次数。也就是for26个字母,对于每一个字母,我们dp/dfs来求按照路径走,这个字母出现的次数。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include <fstream>
#include<vector>
using namespace std;
int rudu[510000];
queue<int>q;
vector<int>g[510000];
int n,m;
char s[510000];
int dp[510000];
int vis[510000];
int rudu2[510000];
int val[510000];
int ans=-1;
bool tuopu()
{
int cnt=0;
for(int i=1;i<=n;i++)
{
if(rudu[i]==0)
{
q.push(i);
cnt++;
}
}
while(!q.empty())
{
int v=q.front();
q.pop();
for(int i=0;i<g[v].size();i++)
{
int vv=g[v][i];
rudu[vv]--;
if(!rudu[vv])
{
q.push(vv);
cnt++;
}
}
}
return n==cnt;
}
void dfs(int u)
{
dp[u]=val[u];
vis[u]=1;
for(int i=0;i<g[u].size();i++)
{
int v=g[u][i];
if(!vis[v])
{
dfs(v);
}
dp[u]=max(dp[u],dp[v]+val[u]);
}
ans=max(dp[u],ans);
}
int main()
{
cin>>n>>m;
scanf("%s",s+1);
for(int i=0;i<m;i++)
{
int x,y;
cin>>x>>y;
g[x].push_back(y);
rudu[y]++;
rudu2[y]++;
}
if(!tuopu())
{
cout<<"-1"<<endl;
return 0;
}
for(int i=0;i<26;i++)
{
memset(vis,0,sizeof(vis));
memset(dp,0,sizeof(dp));
for(int j=1;j<=n;j++)
{
if(s[j]=='a'+i)
val[j]=1;
else
val[j]=0;
}
for(int j=1;j<=n;j++)
{
if(rudu2[j]==0)
{
dfs(j);
}
}
}
cout<<ans<<endl;
}