#include <bits/stdc++.h>
#define F first
#define S second
#define pii pair<int, int>
using namespace std;
using ll = long long;
using ld = long double;
constexpr int SIZE = 5e5+5;
vector<int> children[SIZE];
int parent[SIZE];
int fre[SIZE];
int siz[SIZE];
int dth[SIZE];
int DFS(int v, int g){
vector<pii> ST;
ST.push_back({v, g});
int cnt = 0;
while (!ST.empty()){
v = ST.back().F;
g = ST.back().S;
ST.pop_back();
if (children[v].empty()){
fre[g+1] ++;
cnt ++;
continue;
}
for (int u:children[v]) ST.push_back({u, g+1});
}
return cnt;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k;
cin >> k >> n;
siz[0] = n;
int act = n;
int a;
for (int i=1; i<k; i++){
cin >> n;
siz[i] = n;
for (int j=1; j<=n; j++){
cin >> a;
dth[act+j] = i;
if (!a) continue;
parent[act+j] = act-siz[i-1] + a;
children[act-siz[i-1] + a].push_back(act+j);
}
act += n;
}
int sum = 0;
act = 0;
for (int i=0; i<k; i++){
for (int j=1; j<=siz[i]; j++){
if (parent[act+j]) continue;
int res = DFS(act+j, i);
if (fre[i] >= res) fre[i] -= res;
else if (!fre[i]) sum += res;
else {
sum += res-fre[i];
fre[i] = 0;
}
}
act += siz[i];
fre[i+1] += fre[i];
}
cout << sum;
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | #include <bits/stdc++.h> #define F first #define S second #define pii pair<int, int> using namespace std; using ll = long long; using ld = long double; constexpr int SIZE = 5e5+5; vector<int> children[SIZE]; int parent[SIZE]; int fre[SIZE]; int siz[SIZE]; int dth[SIZE]; int DFS(int v, int g){ vector<pii> ST; ST.push_back({v, g}); int cnt = 0; while (!ST.empty()){ v = ST.back().F; g = ST.back().S; ST.pop_back(); if (children[v].empty()){ fre[g+1] ++; cnt ++; continue; } for (int u:children[v]) ST.push_back({u, g+1}); } return cnt; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin >> k >> n; siz[0] = n; int act = n; int a; for (int i=1; i<k; i++){ cin >> n; siz[i] = n; for (int j=1; j<=n; j++){ cin >> a; dth[act+j] = i; if (!a) continue; parent[act+j] = act-siz[i-1] + a; children[act-siz[i-1] + a].push_back(act+j); } act += n; } int sum = 0; act = 0; for (int i=0; i<k; i++){ for (int j=1; j<=siz[i]; j++){ if (parent[act+j]) continue; int res = DFS(act+j, i); if (fre[i] >= res) fre[i] -= res; else if (!fre[i]) sum += res; else { sum += res-fre[i]; fre[i] = 0; } } act += siz[i]; fre[i+1] += fre[i]; } cout << sum; return 0;} |
English