为什么会超时
  • 板块灌水区
  • 楼主Leo11
  • 当前回复5
  • 已保存回复5
  • 发布时间2024/3/22 17:59
  • 上次更新2024/3/22 20:08:40
查看原帖
为什么会超时
990387
Leo11楼主2024/3/22 17:59

亲戚这道题,当n>=20000,m>=106n>=20000,m>= 10^6的时候,我的代码该怎么优化?

#include<bits/stdc++.h>
using namespace std;
int n, m ,q, u, v, f[200001];
int fd(int x)
{
	while(f[x] != x)
	{
		x = f[x];
	}
	return x;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie();
	cout.tie();
	cin >> n >> m;
	for(int i = 1; i <= n; i++)
	{
		f[i] = i;
	}
	for(int i = 1; i <= m; i++)
	{
	    cin >> u >> v;
	    int x = fd(u);
	    int y = fd(v);
	    if(x != y)
	    {
	    	f[y] = x;
		}
	}
	cin >> q;
	while(q--)
	{
		cin >> u >> v;
		if(fd(u) == fd(v))
		{
			cout << "Yes" << "\n";
		}
		else
		{
			cout << "No" << "\n";
		}
	}
}
2024/3/22 17:59
加载中...