全TLE求助,样例只能输入两行
  • 板块P1536 村村通
  • 楼主484A51
  • 当前回复14
  • 已保存回复14
  • 发布时间2021/8/15 09:06
  • 上次更新2023/11/4 10:38:06
查看原帖
全TLE求助,样例只能输入两行
180246
484A51楼主2021/8/15 09:06
#include <bits/stdc++.h>
using namespace std;
int n,m;
int pre[1001];
int read(){
    int x=0,f=1;char ch=getchar();
    while (!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
    while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
    return x*f;
}
int find(int x){
	int r = x;
	while(pre[r] = r)
		r = pre[r];
	while(x != r){
		int p = pre[x];
		pre[x] = r;
		x = p;
	}
	return r;
}
void join(int x,int y){
	int fx = find(x);
	int fy = find(y);
	if(fx != fy) pre[fx] = fy;
}
int main(){
	while(cin >> n){
		if(n==0) break;
		m = read();
		for(int i = 1; i <= n; i ++)
			pre[i] = i;
		for(int i = 1; i <= m; i ++){
			int x = read(), y = read();
			if(find(x)!=find(y)) join(x, y);
		}
		int ans = 0;
		for(int i = 1; i <= n; i ++){
			int x = find(i);
			if(x == i) ans ++;
		}
		cout << ans - 1 << endl;
	}
}
2021/8/15 09:06
加载中...