Guest User

Untitled

a guest
Jan 31st, 2018
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. // problem D
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. const int N = 3e5 + 1;
  6.  
  7. int n , m;
  8.  
  9. char arr[N];
  10. bool vis[N];
  11. bool loop[N];
  12. bool inrecur[N];
  13.  
  14. vector < int > adj[N];
  15.  
  16. bool dfs(int u) {
  17. int to = (int) adj[u].size();
  18. for(int i = 0; i < to; ++i) {
  19. int nxt = adj[u][i];
  20. if(!vis[nxt]) {
  21. vis[nxt] = true;
  22. inrecur[nxt] = true;
  23. if(dfs(nxt)) {
  24. loop[u] = true;
  25. return true;
  26. }
  27. } else {
  28. if(inrecur[nxt]) {
  29. loop[u] = true;
  30. return true;
  31. }
  32. }
  33. }
  34. inrecur[u] = false;
  35. return false;
  36. }
  37. int dp[N][26];
  38.  
  39. void go(int u) {
  40. int to = (int) adj[u].size();
  41. if(!to) {
  42. dp[u][arr[u] - 'a'] = 1;
  43. return;
  44. }
  45. for(int i = 0; i < to; ++i) {
  46. go(adj[u][i]);
  47. for(int j = 0; j < 26; ++j) {
  48. dp[u][j] = max(dp[u][j] , (j == (arr[u] - 'a')) + dp[adj[u][i]][j]);
  49. }
  50. }
  51. }
  52.  
  53. int solve() {
  54. int ans = 0;
  55. memset(dp , -1 , sizeof dp);
  56. for(int i = 1; i <= n; ++i) {
  57. go(i);
  58. for(int j = 0; j < 26; ++j) {
  59. ans = max(ans , dp[i][j]);
  60. }
  61. }
  62. return ans;
  63. }
  64.  
  65. int main() {
  66. scanf("%d %d" , &n , &m);
  67. scanf("%s" , arr + 1);
  68. while(m--) {
  69. int u , v;
  70. scanf("%d %d" , &u , &v);
  71. adj[u].push_back(v);
  72. }
  73. bool has_loop = false;
  74. for(int i = 1; i <= n; ++i) {
  75. if(!vis[i]) {
  76. vis[i] = true;
  77. inrecur[i] = true;
  78. if(dfs(i)) {
  79. has_loop = true;
  80. break;
  81. }
  82. }
  83. }
  84. if(has_loop) {
  85. printf("-1\n");
  86. return 0;
  87. }
  88. printf("%d\n" , solve());
  89. return 0;
  90. }
Add Comment
Please, Sign In to add comment