forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
38 lines (38 loc) · 1.07 KB
/
Solution.cpp
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
class Solution {
public:
int largestPathValue(string colors, vector<vector<int>>& edges) {
int n = colors.size();
vector<vector<int>> g(n);
vector<int> indeg(n);
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
++indeg[b];
}
queue<int> q;
vector<vector<int>> dp(n, vector<int>(26));
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) {
q.push(i);
int c = colors[i] - 'a';
dp[i][c]++;
}
}
int cnt = 0;
int ans = 1;
while (!q.empty()) {
int i = q.front();
q.pop();
++cnt;
for (int j : g[i]) {
if (--indeg[j] == 0) q.push(j);
int c = colors[j] - 'a';
for (int k = 0; k < 26; ++k) {
dp[j][k] = max(dp[j][k], dp[i][k] + (c == k));
ans = max(ans, dp[j][k]);
}
}
}
return cnt == n ? ans : -1;
}
};