I have a directed graph (with possible self-loops and cycles). Each vertex has a certain value. Given the graph, I need to find the maximum value that is reachable from each vertex. I have tried applying dfs but I am stuck at the condition when a cycle occurs. I have also tried approaching it with white-grey-black visiting, but can’t get it right. I am stuck from a long time.
Please help.
ll dfs(ll s) {
if (vis[s]==2) return rch[s];
vis[s] = 1;
ll m = val[s];
for (ll x: adj[s]) {
if (vis[x]==1) continue;
m = max(m, dfs(x));
}
vis[s] = 2;
rch[s] = m;
return m;
}