Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // problem D
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 3e5 + 1;
- int n , m;
- char arr[N];
- bool vis[N];
- bool loop[N];
- bool inrecur[N];
- vector < int > adj[N];
- bool dfs(int u) {
- int to = (int) adj[u].size();
- for(int i = 0; i < to; ++i) {
- int nxt = adj[u][i];
- if(!vis[nxt]) {
- vis[nxt] = true;
- inrecur[nxt] = true;
- if(dfs(nxt)) {
- loop[u] = true;
- return true;
- }
- } else {
- if(inrecur[nxt]) {
- loop[u] = true;
- return true;
- }
- }
- }
- inrecur[u] = false;
- return false;
- }
- int dp[N][26];
- void go(int u) {
- int to = (int) adj[u].size();
- if(!to) {
- dp[u][arr[u] - 'a'] = 1;
- return;
- }
- for(int i = 0; i < to; ++i) {
- go(adj[u][i]);
- for(int j = 0; j < 26; ++j) {
- dp[u][j] = max(dp[u][j] , (j == (arr[u] - 'a')) + dp[adj[u][i]][j]);
- }
- }
- }
- int solve() {
- int ans = 0;
- memset(dp , -1 , sizeof dp);
- for(int i = 1; i <= n; ++i) {
- go(i);
- for(int j = 0; j < 26; ++j) {
- ans = max(ans , dp[i][j]);
- }
- }
- return ans;
- }
- int main() {
- scanf("%d %d" , &n , &m);
- scanf("%s" , arr + 1);
- while(m--) {
- int u , v;
- scanf("%d %d" , &u , &v);
- adj[u].push_back(v);
- }
- bool has_loop = false;
- for(int i = 1; i <= n; ++i) {
- if(!vis[i]) {
- vis[i] = true;
- inrecur[i] = true;
- if(dfs(i)) {
- has_loop = true;
- break;
- }
- }
- }
- if(has_loop) {
- printf("-1\n");
- return 0;
- }
- printf("%d\n" , solve());
- return 0;
- }
Add Comment
Please, Sign In to add comment