錯誤的連接情況有很多種,缺少邊,邊多了,有子環結構(整體是個環,內部又有小環;整體不是環,而是兩個或更多個環);
我覺得最方便的還是用鏈表吧,記錄前一個和後一個,找一個結點作爲起始點,檢查最後是否構成一個環;
#include<stdio.h>
struct node
{
int num;
int left;
int right;
}nd[11];
int find(int x,int *father)
{
if(father[x]==x)
return x;
else
return find(father[x],father);
}
int main()
{
int n,m,i,father[11],x,y,t,head;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
{
father[i]=i;
nd[i].num=i;
nd[i].left=0;
nd[i].right=0;
}
for(i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
t=0;
if(i==0)head=x;
if(nd[x].left==0&&nd[y].right==0)
{
nd[x].left=y;
nd[y].right=x;
if(x!=head) //head是選定的起始點,father指向自己
father[x]=find(y ,father);
}
else
{
if(nd[x].right==0&&nd[y].left==0)
{
nd[x].right=y;
nd[y].left=x;
father[y]=find(x,father);
}
else
t=1; //一個結點上只能連兩個點,多了就出錯了
}
}
if(t==1)
printf("NO\n");
else //判斷是否構成一個環
{
x=find(1,father);
for(i=2;i<=n;i++)
{
y=find(i,father);
if(x!=y)
t=1;
}
if(t==1)
printf("NO\n");
else
printf("YES\n");
}
}
return 0;
}
//思路對了,這題很容易就過了