2005年第3题
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1232
C语言源码:
#include<stdio.h>#include<stdlib.h>typedef struct linknode{int num;struct linknode *next;}linknode,*linklist;void dfs(linklist head[],int visited[],int n,int k){linklist p;p=head[k]->next;while(p){if(visited[p->num]==0){*(visited+p->num)=1;dfs(head,visited,n,p->num);}p=p->next;}}int main(){linklist head[1000],p;int n,m,count,visited[1000],x,y,i;scanf("%d",&n);while(n){scanf("%d",&m);for(i=0;i<n;i++){head[i]=(linklist)malloc(sizeof(linknode));head[i]->next=NULL;}for(i=0;i<m;i++){scanf("%d %d",&x,&y);x--;y--;p=(linklist)malloc(sizeof(linknode));p->num=y;p->next=head[x]->next;head[x]->next=p;p=(linklist)malloc(sizeof(linknode));p->num=x;p->next=head[y]->next;head[y]->next=p;}for(i=0;i<n;i++)visited[i]=0;count=0;for(i=0;i<n;i++){if(visited[i]==0){dfs(head,visited,n,i);count++;}}printf("%d\n",count-1);scanf("%d",&n);}}