Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions 1857. Largest Color Value in a Directed Graph
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
class Solution {
public:
int maxi = -1;
int dp[100001][26];
bool dfs(int node, vector<int> adj[], vector<int>& vis, string& colors) {
vis[node] = 1;
dp[node][colors[node] - 'a']++;
for (auto it : adj[node]) {
if (!vis[it]) {
if (dfs(it, adj, vis, colors))
return true;
}

for (int i = 0; i < 26; i++)
if (colors[node] - 'a' == i)
dp[node][i] = max(dp[node][i], dp[it][i] + 1);
else
dp[node][i] = max(dp[node][i], dp[it][i]);
}
for(int i=0;i<26;i++)maxi=max(maxi,dp[node][i]);
return false;
}
int largestPathValue(string colors, vector<vector<int>>& edges) {
int n = colors.size();
memset(dp, 0, sizeof(dp));
vector<int> adj[n];
queue<int> q, p;
vector<int> indegree(n, 0);
// creating adjacency matrix
for (auto it : edges) {
adj[it[0]].push_back(it[1]);
indegree[it[1]]++;
}
// topological sort using kahn's algo
for (int i = 0; i < n; i++)
if (indegree[i] == 0) {
q.push(i);
p.push(i);
}
vector<int> z;
while (!p.empty()) {
int node = p.front();
p.pop();
z.push_back(node);
for (auto it : adj[node]) {
indegree[it]--;
if (indegree[it] == 0)
p.push(it);
}
}
//if cycle is present return -1
if (z.size() != n)
return -1;
vector<int> vis(n, false), pathvis(n, false);
// making dfs calls only for nodes which have zero indegree
// other nodes will be included automatically in
// the dp table by dfc calls of these nodes
while (!q.empty()) {
int node = q.front();
q.pop();
if (dfs(node, adj, vis, colors))
return -1;
}
return maxi;
}
};
Loading