Pagini recente » Cod sursa (job #2219425) | Cod sursa (job #2718278) | Cod sursa (job #752184) | Cod sursa (job #843750) | Cod sursa (job #2022821)
#include <cstdio>
#include <vector>
#include <cctype>
#define BUF_SIZE 1 << 17
#define MAXN 100000
#define MAXM 2000000
std::vector <int> g[MAXN + 1], q[MAXN + 1];
int a[MAXM], b[MAXM], ans[MAXM];
int t[MAXN + 1];
int pos = BUF_SIZE, poz = 0;
char buf[BUF_SIZE], fub[BUF_SIZE], c[11];
FILE *fin = fopen("lca.in", "r"), *fout = fopen("lca.out", "w");
inline char nextch() {
if (pos == BUF_SIZE) fread(buf, BUF_SIZE, 1, fin), pos = 0;
return buf[pos++];
}
inline int read() {
char ch;
while (!isdigit(ch = nextch())) ch = nextch();
int x = ch - '0';
while (isdigit(ch = nextch())) x = 10 * x + ch - '0';
return x;
}
inline void putch(char ch) {
fub[poz++] = ch;
if (poz == BUF_SIZE) fwrite(fub, BUF_SIZE, 1, fout), poz = 0;
}
inline void write(int x) {
int s = 0;
do { c[++s] = x % 10 + '0'; } while ((x /= 10) > 0);
for (; s; s--) putch(c[s]);
}
int sef(int x) {
if (t[x] == x) return x;
else return t[x] = sef(t[x]);
}
void dfs(int x) {
t[x] = x;
for (auto &y : q[x])
if (a[y] != x && t[a[y]])
ans[y] = sef(a[y]);
else if (b[y] != x && t[b[y]])
ans[y] = sef(b[y]);
for (auto &y : g[x]) if (t[y] == 0) {
dfs(y);
t[sef(y)] = sef(x);
}
}
int main() {
int n = read();
int m = read();
for (int i = 2; i <= n; i++)
g[read()].push_back(i);
for (int i = 0; i < m; i++) {
a[i] = read();
b[i] = read();
if (a[i] == b[i])
ans[i] = a[i];
else q[a[i]].push_back(i), q[b[i]].push_back(i);
}
dfs(1);
for (int i = 0; i < m; i++) {
//write(ans[i]);
//putch('\n');
fprintf(fout, "%d\n", ans[i]);
}
fwrite(fub, poz, 1, fout);
fclose(fin);
fclose(fout);
return 0;
}