# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
742215 | rainboy | Special graph (IZhO13_specialg) | C11 | 67 ms | 15580 KiB |
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 100000
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 rr[N], dd[N], ta[N], tb[N]; char visited[N];
void dfs(int i, int r, int d) {
static int time;
int o;
if (visited[i] == 1)
return;
visited[i] = 1;
ta[i] = time++;
rr[i] = r, dd[i] = d;
for (o = eo[i]; o--; ) {
int j = ej[i][o];
dfs(j, r, d + 1);
}
tb[i] = time;
}
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() {
static int pp[N];
int n, m, i, j;
scanf("%d", &n);
for (i = 0; i < n; i++)
ej[i] = (int *) malloc(2 * sizeof *ej[i]);
for (i = 0; i < n; i++) {
scanf("%d", &pp[i]), pp[i]--;
if (pp[i] != -1)
append(pp[i], i);
}
for (i = 0; i < n; i++) {
if (visited[i])
continue;
j = i;
while (pp[j] != -1 && !visited[j])
visited[j] = -1, j = pp[j];
dfs(j, j, 0);
}
scanf("%d", &m);
while (m--) {
int t, ans;
scanf("%d", &t);
if (t == 1) {
scanf("%d", &i), i--;
pp[i] = -1;
update(ta[i], n, 1), update(tb[i], n, -1);
} else {
scanf("%d%d", &i, &j), i--, j--;
if (ta[j] <= ta[i] && tb[i] <= tb[j])
ans = query(ta[i]) - query(ta[j]) == 0 ? dd[i] - dd[j] : -1;
else {
if (query(ta[i]) > 0)
ans = -1;
else {
ans = dd[i] + 1;
if ((i = pp[rr[i]]) == -1 || ta[i] < ta[j] || ta[i] >= tb[j])
ans = -1;
else
ans = query(ta[i]) - query(ta[j]) == 0 ? ans + dd[i] - dd[j] : -1;
}
}
printf("%d\n", ans);
}
}
return 0;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |