Advertisement
nikunjsoni

1857

May 9th, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int largestPathValue(string colors, vector<vector<int>>& edges) {
  4.         int n = colors.length();
  5.         vector<int> in(n, 0);
  6.         vector<vector<int>> g(n);
  7.         int cnt[n][26];
  8.         memset(cnt, 0, sizeof cnt);
  9.         int ans = 0;
  10.        
  11.         // Make adj list graph.
  12.         for(auto &edge: edges){
  13.             g[edge[0]].push_back(edge[1]);
  14.             in[edge[1]]++;
  15.         }
  16.        
  17.         // Push the vertices with 0 indegree to queue.
  18.         queue<int> q;
  19.         for(int i=0; i<n; i++){
  20.             if(!in[i])
  21.                 q.push(i);
  22.         }
  23.        
  24.         // BFS.
  25.         while(!q.empty()){
  26.             int node = q.front(); q.pop();
  27.             int col = colors[node]-'a';
  28.             cnt[node][col]++;
  29.             ans = max(ans, cnt[node][col]);
  30.             for(auto &child: g[node]){
  31.                 for(int i=0; i<26; i++){
  32.                     cnt[child][i] = max(cnt[child][i], cnt[node][i]);
  33.                 }
  34.                 in[child]--;
  35.                 if(!in[child])
  36.                     q.push(child);
  37.             }
  38.         }
  39.        
  40.         // Check for cycle in graph.
  41.         for(int i=0; i<n; i++)
  42.             if(in[i])
  43.                 return -1;
  44.        
  45.         return ans;
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement