#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10000
typedef int elemtype;
typedef int setname;
typedef elemtype settype[MAXSIZE];
setname find(settype s,elemtype x){
// for(;s[x]>=0;x=s[x]) ;
// return x;
if(s[x]<0) return x;
else return s[x]=find(s,s[x]); //路径压缩 把路上的节点都压到根节点
}
/***
void Union(settype s,setname r1,setname r2){ //比树高,同理还可以比规模
if(s[r1]>s[r2]) s[r1]=r2;
else {
if(s[r1]==s[r2]) s[r1]--;
s[r2]=r1;
}
}
***/
void Union(settype s,setname r1,setname r2){ //比规模
if(s[r2]<s[r1]){
s[r2]+=s[r1];
s[r1]=r2;
}
else{
s[r1]+=s[r2];
s[r2]=r1;
}
}
void initia(settype s,int n){
for(int i=0;i<n;i++) s[i]=-1; //一开始高度为1
}
void input(settype s){
elemtype u,v;
setname r1,r2;
scanf("%d %d\n",&u,&v);
r1=find(s,u-1);
r2=find(s,v-1);
if(r1!=r2)
Union(s,r1,r2);
}
void checkconnect(settype s){
elemtype u,v;
setname r1,r2;
scanf("%d %d\n",&u,&v);
r1=find(s,u-1);
r2=find(s,v-1);
if(r1==r2)
printf("yes\n");
else printf("no\n");
}
void checknet(settype s,int n){
int i,count=0;
for(i=0;i<n;i++)
if(s[i]<0) count++;
if(count==1) printf("The network is connected.\n");
else printf("There are %d components.\n",count);
}
int main(){
settype s;
int n;
char in;
scanf("%d\n",&n);
initia(s,n);
do{
scanf("%c",&in);
switch(in){
case 'I':input(s);break;
case 'C':checkconnect(s);break;
case 'S':checknet(s,n);break;
}
}while(in!='S');
return 0;
}
05-树8 File Transfer
最新推荐文章于 2022-08-07 10:03:47 发布