浙大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;
总结:老老实实合并。
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;
}