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>
#include <string.h>
#define N 500000
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 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 dd[N], ta[N], tb[N], qu[N], n, head, cnt; char visited[N];
void dfs_(int i) {
int o;
if (visited[i] == 1)
return;
if (dd[i] == 0 && visited[i] == 0)
update(ta[i], n, -1);
visited[i] = 1;
for (o = eo[i]; o--; ) {
int j = ej[i][o];
if (dd[j] == dd[i] - 1)
dfs_(j);
}
}
void dfs(int p, int i) {
static int time;
int o;
ta[i] = time++;
for (o = eo[i]; o--; ) {
int j = ej[i][o];
if (j != p)
dfs(i, j);
}
tb[i] = time;
if (dd[i] == 0 && visited[i] == -1)
visited[i] = 0, update(ta[i], n, 1);
if ((p == -1 || dd[i] != dd[p] - 1) && query(tb[i] - 1) - query(ta[i] - 1) > 0)
qu[cnt++] = i, dfs_(i);
}
int main() {
int k, h, i, j;
scanf("%d%d", &n, &k);
for (i = 0; i < n; i++)
ej[i] = (int *) malloc(2 * sizeof *ej[i]);
for (h = 0; h < n - 1; h++) {
scanf("%d%d", &i, &j), i--, j--;
append(i, j), append(j, i);
}
for (i = 0; i < n; i++)
dd[i] = n;
head = cnt = 0;
while (k--) {
scanf("%d", &i), i--;
dd[i] = 0, qu[head + cnt++] = i;
}
while (cnt) {
int d, o;
i = qu[cnt--, head++], d = dd[i] + 1;
for (o = eo[i]; o--; ) {
j = ej[i][o];
if (dd[j] > d)
dd[j] = d, qu[head + cnt++] = j;
}
}
memset(visited, -1, n * sizeof *visited);
dfs(-1, 0);
printf("%d\n", cnt);
for (h = 0; h < cnt; h++)
printf("%d ", qu[h] + 1);
printf("\n");
return 0;
}
Compilation message (stderr)
pastiri.c: In function 'append':
pastiri.c:12:23: warning: suggest parentheses around '-' in operand of '&' [-Wparentheses]
12 | if (o >= 2 && (o & o - 1) == 0)
| ~~^~~
pastiri.c: In function 'main':
pastiri.c:75:2: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
75 | scanf("%d%d", &n, &k);
| ^~~~~~~~~~~~~~~~~~~~~
pastiri.c:79:3: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
79 | scanf("%d%d", &i, &j), i--, j--;
| ^~~~~~~~~~~~~~~~~~~~~
pastiri.c:86:3: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
86 | scanf("%d", &i), i--;
| ^~~~~~~~~~~~~~~
# | 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... |