关于杭电上并查集,最短路的题目代码(学习ing)

(1)

hdu 1213 

How Many Tables

Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
Input
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.
 

Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
Sample Input
2
5 3
1 2
2 3
4 5
 
5 1
2 5
 

Sample Output
2
4

这题的意思是主人请客吃饭 要把互相认识的(间接认识的)安排在一个桌子,问一共需要摆几个桌子,属于最简单的并查集

 1 #include<stdio.h>

 2  #include<string.h>

 3  int bin[200001];

 4  int find(int x)

 5  {

 6      int r=x;

 7      while(bin[r]!=r)

 8      r=bin[r];

 9      return r;

10  }

11  void merge(int x,int y)

12  {

13      int fx=find(x);

14      int fy=find(y);

15      if(fx!=fy)

16      bin[fx]=fy;

17  }

18  int main()

19  {

20      int n,i,m,h,k,count,j,a,b;

21      scanf("%d",&h);

22      for(k=1;k<=h;k++)

23      {

24          scanf("%d",&n);

25          for(i=1;i<=n;i++)

26          {

27              bin[i]=i;

28          }

29          for(scanf("%d",&m);m>0;m--)

30          {

31              scanf("%d %d",&a,&b);

32              merge(a,b);

33          }

34          for(count=0,i=1;i<=n;i++)

35          {

36              if(bin[i]==i)

37              count++;

38          }

39          printf("%d\n",count);

40      }

41      return 0;

42  }

43  

你可能感兴趣的:(最短路)