tarjan求lca, wa on #13, 求调
查看原帖
tarjan求lca, wa on #13, 求调
297270
sqcnzlgvhy楼主2024/8/9 20:50
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 5e6 + 10;
int n, m, s, h[N], cnt, f[N], id[N];
struct inform
{
	int n, t;
}lb[N];
void jb(int u, int v)
{
	lb[++cnt].n = h[u]; lb[cnt].t = v; h[u] = cnt;
}
int read()
{
	int sum = 0, f = 1; char c = getchar();
	while(c < '0' || c > '9')
	{
		if(c == '-') f = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') sum = (sum << 1) + (sum << 3) + (c ^ 48), c = getchar();
	return sum * f;
}
ll find(int now)
{
	if(f[now] == now) return now;
	else return f[now] = find(f[now]); 
}
struct Inform
{
	int ans, a, w;
};
vector<Inform>Ask[N];
void dfs(int u, int fa)
{
	id[u] = 1;
	
//	cout<<u<<" "<<len<<"\n";
	for(int i = h[u]; i; i = lb[i].n)
	{
		int t = lb[i].t;
		if(t == fa) continue;
		dfs(t, u);
	}
	int len = Ask[u].size();
	
	for(int i = 0; i < len; i++)
	{
		int now = Ask[u][i].a;
		if(id[now] == 2)
		{
			Ask[u][i].ans = find(now);
//			cout<<u<<" "<<now<<" "<<Ask[u][i].ans<<"\n";
		}
//		cout<<"-------------"<<"\n";
	}
	id[u] = 2;
	f[u] = fa;
}
int Ans[N];
int main()
{
//	freopen("a.in", "r", stdin);
	n = read(); m = read(); s = read(); // 根节点序号
//	cout<<n<<" "<<m<<" "<<s<<"-------"<<"\n";
	for(int i = 1; i <= n; i++) f[i] = i;
	for(int i = 1; i < n; i++)
	{
		int x, y; x = read(), y = read();
		jb(x, y), jb(y, x);
	} 
	for(int i = 1; i <= m; i++)
	{
		int x, y; x = read(); y = read();
		Inform A = {0, y, i}, B = {0, x, i};
		Ask[x].push_back(A); Ask[y].push_back(B); 
	}
//	cout<<"*-----------------"<<"\n";
//	cout<<"*-----------------"<<"\n";
//	cout<<"-----------------";
	dfs(s, 0);
	for(int i = 1; i <= n; i++)
	{
//		ll len = Ask[i].size();
		for(Inform x : Ask[i])
		{
			Ans[x.w] = max(Ans[x.w], x.ans);
		}
//		for(int j = 0; j < len; j++)
//		{
//			cout<<Ask[i][j].ans<<" ";
//		}
//		cout<<"\n";
	}
	for(int i = 1; i <= m; i++) cout<<Ans[i]<<"\n";
	return 0;
}
2024/8/9 20:50
加载中...