Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define DEBUG 0
- #define TIME clock() / 1.0 / CLOCKS_PER_SEC
- const int maxN = (int)3e5 + 17;
- int n, m;
- int a[maxN];
- int used[maxN];
- vector <int> dd;
- int dp[maxN][26];
- vector <int> g[maxN];
- void TopSort(int v) {
- used[v] = 1;
- //cout << "- >" << v + 1 << ' ';
- for(const auto to : g[v]) {
- if(used[to] == 1) {
- cout << -1 << '\n';
- exit(0);
- } else if(used[to] == 0) {
- TopSort(to);
- }
- }
- used[v] = 2;
- dd.push_back(v);
- }
- void dfs(int v, int colour) {
- used[v] = 1;
- if(g[v].size() == 0) {
- dp[v][colour] = (colour == a[v]);
- }
- for(const auto to : g[v]) {
- if(!used[to]) {
- dfs(to, colour);
- }
- dp[v][colour] = max(dp[v][colour], dp[to][colour] + (colour == a[to]));
- }
- }
- int solve(int v) {
- int ret = 0;
- for(int i = 0; i < dd.size(); ++i) {
- if(!used[dd[i]])
- dfs(dd[i], v);
- }
- fill(used, used + maxN, 0);
- for(int i = 0; i < n; ++i) {
- ret = max(ret, dp[i][v]);
- }
- return ret;
- }
- signed main()
- {
- #if DEBUG
- freopen("input.txt", "r", stdin);
- freopen("output.txt" , "w", stdout);
- #endif
- cin >> n >> m;
- for(int i = 0; i < n; ++i) {
- char x; cin >> x;
- a[i] = x - 'a';
- }
- for(int i = 0; i < m; ++i) {
- int x, y;
- cin >> x >> y;
- g[x - 1].push_back(y - 1);
- }
- for(int i = 0; i < n; ++i) {
- if(!used[i])
- TopSort(i);
- }
- //reverse(dd.begin(), dd.end());
- fill(used, used + maxN, 0);
- for(const auto i : dd){
- cout << i + 1 << ' ';
- }
- cout << endl;
- int ans = 0;
- for(int i = 'a'; i <= 'z'; ++i){
- ans = max(ans, solve(i - 'a'));
- }
- cout << ans << '\n';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement