树剖RE求助,疑似死循环,悬关!!!
查看原帖
树剖RE求助,疑似死循环,悬关!!!
868063
_Coffice_楼主2023/6/25 18:27

code:

#include<iostream> 
#include<string>
using namespace std;
const int N = 500005;
struct Edge
{
	int v, next;
};
Edge e[3*N];
int head[N];
int tot = 0;
void insert(int u, int v)
{
	tot++;
	e[tot] = {v, head[u]};
	head[u] = tot;
}
int n, m, s;
int fa[N], dep[N], top[N], son[N], sz[N];
void dfs_1(int p, int father)
{
	fa[p] = father;
	dep[p] = dep[father]+1;
	sz[p] = 1;
	int heavy = -1000000000;
	for(int i=head[p];i;i=e[i].next)
	{
		if(e[i].v != father)
		{
			dfs_1(e[i].v, p);
			sz[p] += sz[e[i].v];
			if(!son[p] || sz[e[i].v] >= heavy) 
				{ son[p] = e[i].v; heavy = sz[e[i].v]; }
		}
	}
}
void dfs_2(int p, int t)
{
	top[p] = t;
	if(son[p] != 0) dfs_2(son[p], t);
	else if(son[p] == 0) return ;
	else
	{
		for(int i=head[p];i;i=e[i].next)
			if(e[i].v != fa[p] && e[i].v != son[p])
				dfs_2(e[i].v, e[i].v);
	}
}
int main()
{
	ios::sync_with_stdio(false); 
	cin.tie(0), cout.tie(0);
	cin >> n >> m >> s;
	for(int i=1;i<=n-1;i++)
	{
		int x, y;
		cin >> x >> y;
		insert(x, y);
		insert(y, x);
	}
	dfs_1(s, 0);
	dfs_2(s, s);
	for(int i=1;i<=m;i++)
	{
		int a, b;
		cin >> a >> b;
		while(top[a] != top[b])
		{
			if(dep[top[a]] >= dep[top[b]]) a = top[a];
			else b = top[b];
		}
		if(dep[a] <= dep[b]) cout << a << endl;
		else cout << b << endl;
	}
	return 0;
}

样例都过不了!!!

疯了!!

2023/6/25 18:27
加载中...