九度:1012<并查集>

浙大2005年研究生机试


类别:图类。方案:并查集。


首先AC:

#include <stdio.h>
#include <iostream>
 
using namespace std;
 
int fa[1010];
 
int getfa(int x){
    if(fa[x] == x)
        return x;
    fa[x] = getfa(fa[x]);
    return fa[x];
}
 
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("E:\\in.txt", "r", stdin);
#endif
 
    int n, m;
    while(scanf("%d %d", &n, &m) && n){
 
        int i;
        for(i=1;i<=n;i++){
            fa[i]=i;
        }
 
        int t1, t2;
        while(m-->0){
            scanf("%d %d", &t1, &t2);
            fa[getfa(t1)]=getfa(t2);
        }
 
        int j, road=0;
        for(i=1;i<=n;i++){ //“查”与后面的是否连通,未连则并
            for(j=i+1;j<=n;j++){ 
                if(getfa(i) != getfa(j)){
                    road++;
                    fa[getfa(i)] = getfa(j);
                }
            }
        }
 
        cout << road << endl;
    }//while
    return 0;
}



另外WA:

原因:此程序没有执行合并。自己规定总是由大指向小的节点。
测试2:
输入:
1 2
2 1
2 3
结果:
fa[1]=1;
fa[2]=1;
fa[3]=2;
统计fa[i] != i;的节点数,此处1个。所需最少边为1-1=0个。


测试2:
输入:
1 3
2 3
结果:
fa[1]=1;
fa[2]=2;
fa[3]=2; // 错误原因
统计fa[i] != i;的节点数,此处2个。所需最少边为2-1=1个。但实际上,此已连同。
错误在于自定的规则。总是让大的指向小的。先有fa[3]=1; 后又成为fa[3]=2;




总结:老老实实合并。

#include <stdio.h>
#include <iostream>
#include <vector>


using  namespace std;

int min(int x, int y){
	return x<y ? x:y;
}

int max(int x, int y){

	return x>y ? x:y;
}

int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("E:\\in.txt", "r", stdin);
#endif
 
	int n, m;
	while(scanf("%d %d", &n , &m)!= EOF && n != 0){
		if(m == 0){
			cout << n-1 << endl;
			continue;
		}

		int i;
		vector <int> father;
		father.resize(n+10); //when use vector, it's better to resize it

		for(i=1;i<=n;i++){
			father[i]=i;
		}
		
		int t1, t2;
		for(i=0;i<m;i++){
			
			scanf("%d %d", &t1, &t2);
			int mi=min(t1, t2);
			int ma=max(t1, t2);

			father[ma]=mi; //little always the father
		}

		int cntree=0;

		for(i=1; i<=n; i++){
			if(father[i] == i)

				cntree++;
		}

		cout << cntree-1 << endl;
	}//while


	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值