-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1857-largest-color-value-in-a-directed-graph.cpp
More file actions
59 lines (55 loc) · 1.76 KB
/
1857-largest-color-value-in-a-directed-graph.cpp
File metadata and controls
59 lines (55 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:
int largestPathValue(string colors, vector<vector<int>>& edges) {
int n = colors.size();
vector<vector<int>> g(n);
vector<int> c(n, 0);
int dp[n][26]; //largest path starting from node x with char c
memset(dp, -1, sizeof(dp));
for (auto &e: edges) {
g[e[0]].push_back(e[1]);
}
//dfs1 to check for cycles
//c[u] = 0 means not seen yet
//c[u] = 1 means its on the dfs stack right now
//c[u] = 2 means we are done with u
function<bool(int)> dfs1 = [&](int u)-> bool {
c[u] = 1;
for (auto &v: g[u]) {
if ((c[v] == 1) || (c[v] == 0 && dfs1(v))) {
return true;
}
}
c[u] = 2;
return false;
};
//dfs2 to fill the dp
function<void(int)> dfs2 = [&](int u) -> void {
for (int i = 0; i < 26; i++) dp[u][i] = 0;
dp[u][colors[u] - 'a'] = 1;
for (auto &v: g[u]) {
for (int i = 0; i < 26; i++) {
if (dp[v][i] == -1) {
dfs2(v);
}
dp[u][i] = max(dp[u][i], (colors[u]-'a' == i) + dp[v][i]);
}
}
};
for (int node = 0; node < n; node++) {
if (c[node] == 2) continue;
if (dfs1(node)) return -1;
}
for (int node = 0; node < n; node++) {
if (dp[node][0] != -1) continue;
dfs2(node);
}
int ans = 0;
for (int node = 0; node < n; node++) {
for (int i = 0; i < 26; i++) {
ans = max(ans, dp[node][i]);
}
}
return ans;
}
};