D. SubstringTime limit per test3 secondsmemory limit per testMegabytes
You is given a graph with n nodes and m directed edges. One lowercase letter are assigned to each node. We define a path ' s value as the number of the most frequently occurring. For example, if letters on a path was "abaca", then the value of this path is 3. Your task is find a path whose value is the largest.
Input
The first line contains positive integers n, m (1≤ n, m ≤300), Denot ing the graph has n nodes and m directed edges.
The second line contains a string s with only lowercase 中文版 letters. The i-th character is the letter assigned to the I-th node.
Then m lines follow. Each line contains integers x, y (1≤ x, y ≤ n), describing a dir Ected Edge from x to y. Note that x can is equal to y and there can is multiple edges between x an D y. Also the graph can be is not connected.
Output
Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1instead.
Examplesinput
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
Ten
XZYZYZYZQX
1 2
2 4
3 5
4 5
2 6
6 8
6 5
2 Ten
3 9
Ten 9
4 6
1 Ten
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.
Test instructions: N,m represents the number of vertices and the number of edges, enter a string of strings, input the information of the edge, the value of a path is the number of the most occurrences of that letter, so you seek maximum value! For example, Case 1: The maximum path is 1->3->4->5, the value is the number of occurrences of a, 3 times, so the output 3;
Analysis: topological sorting + thinking; record the number of occurrences of every letter to a vertex, 300000*300000 the array of vectors, if the number of traversed points is not equal to n words output-1, otherwise double loop query to the maximum value!
#include <bits/stdc++.h>#defineN 300010#defineMem (A, B) memset (A,b,sizeof (a))using namespacestd;intIndegree[n];//record the penetration of each nodeintdp[n][ -];//record the number of occurrences of 26 letters when you reach a nodequeue<int>W;vector<int>V[n];intn,m;CharS[n];intthe number of nodes traversed by the ans;//recordintMain () {CIN>>n>>m; CIN>>s; Mem (Indegree,0); intx, y; for(intI=1; i<=m;i++) {cin>>x>>y; V[x].push_back (y); Indegree[y]++; } for(intI=1; i<=n;i++) if(!Indegree[i]) W.push (i), Dp[i][s[i-1]-'a']++; intq,p; while(!W.empty ()) {Q=W.front (); W.pop (); for(intI=0; I<v[q].size (); i++) {p=V[q][i]; INDEGREE[P]--; for(intj=0;j< -; j + +) { if(j==s[p-1]-'a') Dp[p][j]=max (dp[p][j],dp[q][j]+1); Elsedp[p][j]=Max (dp[p][j],dp[q][j]); } if(!indegree[p]) W.push (p); } ans++; } if(ans!=N) cout<<"-1"<<Endl; Else { intmaxn=0; for(intI=1; i<=n;i++) for(intj=0;j< -; j + +) MAXN=Max (maxn,dp[i][j]); cout<< MAXN <<Endl; } return 0;}
Substring (codeforces-d-topology sort)