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 <stdio.h>
#include <stdlib.h>
#define N 200000
int *ej[N], eo[N];
void append(int i, int j) {
int o = eo[i]++;
if (o >= 2 && (o & o - 1) == 0)
ej[i] = (int *) realloc(ej[i], o * 2 * sizeof *ej[i]);
ej[i][o] = j;
}
int dd[N], pp[N], qq[N], ta[N], tb[N];
int dfs1(int i, int d) {
int o, s, k_, j_;
dd[i] = d;
s = 1, k_ = 0, j_ = -1;
for (o = eo[i]; o--; ) {
int j = ej[i][o], k = dfs1(j, d + 1);
s += k;
if (k_ < k)
k_ = k, j_ = j;
}
qq[i] = j_;
return s;
}
void dfs2(int i, int q) {
static int time;
int o, j_;
ta[i] = time++;
j_ = qq[i], qq[i] = q;
if (j_ != -1)
dfs2(j_, q);
for (o = eo[i]; o--; ) {
int j = ej[i][o];
if (j != j_)
dfs2(j, j);
}
tb[i] = time;
}
int lca(int i, int j) {
while (qq[i] != qq[j]) {
if (dd[qq[i]] > dd[qq[j]])
i = pp[qq[i]];
else
j = pp[qq[j]];
}
return dd[i] < dd[j] ? i : j;
}
int ft[N];
void update(int i, int n, int x) {
while (i < n) {
ft[i] += x;
i |= i + 1;
}
}
int query(int i) {
int x = 0;
while (i >= 0) {
x += ft[i];
i &= i + 1, i--;
}
return x;
}
int main() {
int n, q, i;
scanf("%d%d", &n, &q);
for (i = 0; i < n; i++)
ej[i] = (int *) malloc(2 * sizeof *ej[i]);
for (i = 1; i < n; i++) {
scanf("%d", &pp[i]), pp[i]--;
append(pp[i], i);
}
dfs1(0, 0);
dfs2(0, 0);
while (q--) {
int i, j, upd, yes;
scanf("%d%d%d", &i, &j, &upd), i--, j--;
yes = query(ta[i]) + query(ta[j]) - query(ta[lca(i, j)]) * 2 == 0;
printf(yes ? "YES\n" : "NO\n");
if (upd) {
if (!yes)
i = j;
update(ta[i], n, 1), update(tb[i], n, -1);
}
}
return 0;
}
Compilation message (stderr)
tree.c: In function 'append':
tree.c:11:23: warning: suggest parentheses around '-' in operand of '&' [-Wparentheses]
11 | if (o >= 2 && (o & o - 1) == 0)
| ~~^~~
tree.c: In function 'main':
tree.c:83:2: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
83 | scanf("%d%d", &n, &q);
| ^~~~~~~~~~~~~~~~~~~~~
tree.c:87:3: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
87 | scanf("%d", &pp[i]), pp[i]--;
| ^~~~~~~~~~~~~~~~~~~
tree.c:95:3: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
95 | scanf("%d%d%d", &i, &j, &upd), i--, j--;
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |