#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <deque>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <numeric>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int k, n_1;
std::cin >> k >> n_1;
std::vector<std::vector<std::vector<int>>> tree(k + 2);
std::vector<std::vector<int>> dp(k + 2);
std::vector<int> days;
days.resize(k + 2, 0);
dp[1].resize(n_1 + 2, {});
tree[1].resize(n_1 + 2, {});
days[1] = n_1;
for (int i = 2; i <= k; i++) {
std::cin >> days[i];
tree[i].resize(days[i] + 2, {});
dp[i].resize(days[i] + 2, 0);
for (int j = 1; j <= days[i]; j++) {
int a;
std::cin >> a;
if (a > 0) {
tree[i - 1][a].push_back(j);
}
}
}
int result = 0; // max from all the layers
// traverse from the back to the beginning
for (int i = k; i >= 1; i--) {
int curr_result = 0;
// traverse one layer
for (int j = 1; j <= days[i]; j++) {
int sum_children = 0;
if (tree[i][j].empty()) {
sum_children = 1;
} else {
for (const int child : tree[i][j]) {
sum_children += dp[i + 1][child];
}
}
dp[i][j] = sum_children;
curr_result += sum_children;
}
result = std::max(result, curr_result);
}
std::cout << result << "\n";
return 0;
}
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 60 61 62 63 64 | #include <iostream> #include <vector> #include <algorithm> #include <queue> #include <stack> #include <deque> #include <set> #include <map> #include <string> #include <cmath> #include <numeric> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); int k, n_1; std::cin >> k >> n_1; std::vector<std::vector<std::vector<int>>> tree(k + 2); std::vector<std::vector<int>> dp(k + 2); std::vector<int> days; days.resize(k + 2, 0); dp[1].resize(n_1 + 2, {}); tree[1].resize(n_1 + 2, {}); days[1] = n_1; for (int i = 2; i <= k; i++) { std::cin >> days[i]; tree[i].resize(days[i] + 2, {}); dp[i].resize(days[i] + 2, 0); for (int j = 1; j <= days[i]; j++) { int a; std::cin >> a; if (a > 0) { tree[i - 1][a].push_back(j); } } } int result = 0; // max from all the layers // traverse from the back to the beginning for (int i = k; i >= 1; i--) { int curr_result = 0; // traverse one layer for (int j = 1; j <= days[i]; j++) { int sum_children = 0; if (tree[i][j].empty()) { sum_children = 1; } else { for (const int child : tree[i][j]) { sum_children += dp[i + 1][child]; } } dp[i][j] = sum_children; curr_result += sum_children; } result = std::max(result, curr_result); } std::cout << result << "\n"; return 0; } |
English