#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
using ll = long long;
#define all(a) begin(a), end(a)
void solve() {
int n, k;
cin >> n >> k;
vector<vector<int>> adj(k);
vector<int> offs{0};
vector<int> is_root(k, 1);
for (int h = 1; h < n; h++) {
int c;
cin >> c;
vector<int> a(c);
for (auto &i : a) {
cin >> i;
--i;
}
int off = adj.size();
for (int i = 0; i < c; i++) {
if (a[i] != -1) {
adj[offs.back() + a[i]].push_back(adj.size());
}
adj.push_back({});
is_root.push_back(a[i] == -1);
}
offs.push_back(off);
}
int sz = adj.size();
offs.push_back(sz);
vector<int> need(sz);
for (int i = sz - 1; i >= 0; i--) {
if (adj[i].size() == 0) {
need[i] = 1;
} else {
for (auto v : adj[i]) {
need[i] += need[v];
}
}
}
int res = 0, fr = 0;
for (int i = 0; i + 1 < offs.size(); i++) {
// cerr << "L " << i << ": ";
for (int j = offs[i]; j < offs[i + 1]; j++) {
if (is_root[j]) {
// cerr << need[j] << " ";
int t = min(fr, need[j]);
fr -= t;
res += need[j] - t;
}
}
for (int j = offs[i]; j < offs[i + 1]; j++) {
fr += adj[j].size() == 0;
if (adj[j].empty()) {
// cerr << "-1 ";
}
}
// cerr << "\n";
}
cout << res << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int q = 1;
// cin >> q;
while (q--) {
solve();
}
}
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | #include <cassert> #include <iostream> #include <vector> using namespace std; using ll = long long; #define all(a) begin(a), end(a) void solve() { int n, k; cin >> n >> k; vector<vector<int>> adj(k); vector<int> offs{0}; vector<int> is_root(k, 1); for (int h = 1; h < n; h++) { int c; cin >> c; vector<int> a(c); for (auto &i : a) { cin >> i; --i; } int off = adj.size(); for (int i = 0; i < c; i++) { if (a[i] != -1) { adj[offs.back() + a[i]].push_back(adj.size()); } adj.push_back({}); is_root.push_back(a[i] == -1); } offs.push_back(off); } int sz = adj.size(); offs.push_back(sz); vector<int> need(sz); for (int i = sz - 1; i >= 0; i--) { if (adj[i].size() == 0) { need[i] = 1; } else { for (auto v : adj[i]) { need[i] += need[v]; } } } int res = 0, fr = 0; for (int i = 0; i + 1 < offs.size(); i++) { // cerr << "L " << i << ": "; for (int j = offs[i]; j < offs[i + 1]; j++) { if (is_root[j]) { // cerr << need[j] << " "; int t = min(fr, need[j]); fr -= t; res += need[j] - t; } } for (int j = offs[i]; j < offs[i + 1]; j++) { fr += adj[j].size() == 0; if (adj[j].empty()) { // cerr << "-1 "; } } // cerr << "\n"; } cout << res << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int q = 1; // cin >> q; while (q--) { solve(); } } |
English