This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define F first
#define S second
#define pb push_back
#define endl "\n"
#define all(x) x.begin(), x.end()
const int M = 200007;
const ll inf = 1e9;
const ll mod = 998244353;
const double pi = acos(-1);
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
vector < pair <int,int> > v;
vector <int> adj[M];
int n, d, p[M], mn[M], sz[M], add[M], dep[M], dist, ans, anc[M][20];
bool vist[M];
void calc(int node, int par)
{
sz[node] = 1;
for(auto i : adj[node]) if(i != par && !vist[i]){
calc(i, node);
sz[node] += sz[i];
}
return;
}
int get(int node, int par, int half)
{
++dist;
for(auto i : adj[node]) if(!vist[i] && i != par && sz[i] > half) return get(i, node, half);
return node;
}
void decompose(int node, int par)
{
dist = 0;
calc(node, 0);
int cen = get(node, 0, sz[node] / 2);
vist[cen] = 1;
p[cen] = par;
add[cen] = dist;
for(auto i : adj[cen]) if(!vist[i]) decompose(i, cen);
return;
}
void dfs(int node, int par)
{
v.pb({dep[node], node});
for(auto i : adj[node]) if(i != par){
dep[i] = dep[node] + 1;
anc[i][0] = node;
dfs(i, node);
}
return;
}
int lca(int x, int y)
{
if(x == y) return 0;
int ret = 0;
if(dep[x] < dep[y]) swap(x, y);
for(int i = 19; i >= 0; --i) if(dep[anc[x][i]] >= dep[y]){
ret += (1 << i);
x = anc[x][i];
}
if(x == y) return ret;
for(int i = 19; i >= 0; --i) if(anc[x][i] != anc[y][i]){
ret += 2 * (1 << i);
x = anc[x][i];
y = anc[y][i];
}
return ret + 2;
}
int main()
{
scanf("%d%d", &n, &d);
for(int i = 2; i <= n; ++i){
int a;
scanf("%d", &a);
adj[a + 1].pb(i);
adj[i].pb(a + 1);
}
decompose(1, 0);
dep[1] = 1;
dfs(1, 0);
for(int j = 1; j < 20; ++j) for(int i = 1; i <= n; ++i) anc[i][j] = anc[anc[i][j - 1]][j - 1];
sort(all(v), greater < pair <int,int> > ());
for(int i = 1; i <= n; ++i) mn[i] = inf;
for(auto i : v){
bool ok = 1;
int cur = i.S;
while(cur){
if(mn[cur] + lca(i.S, cur) < d) ok = 0;
cur = p[cur];
}
if(ok){
++ans;
cur = i.S;
while(cur){
mn[cur] = min(mn[cur], lca(i.S, cur));
dist += add[cur];
cur = p[cur];
}
}
}
printf("%d\n", ans);
return 0;
}
Compilation message (stderr)
catinatree.cpp: In function 'int main()':
catinatree.cpp:80:7: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
80 | scanf("%d%d", &n, &d);
| ~~~~~^~~~~~~~~~~~~~~~
catinatree.cpp:83:8: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
83 | scanf("%d", &a);
| ~~~~~^~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |