随笔(并查集)

今天的比赛真的好郁闷啊!一个博弈题弄了两小时结果还WA啦,放下博弈接着写并查集,这是一道比较简单的题目。由于输入数据有多组,而我只用一组处理导致很悲剧的无数次WA。。。。伤心ING ...

题目:

Statistics

Ice Skating

Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 8 Accepted Submission(s) : 3

Font: Times New Roman | Verdana | Georgia

Font Size:

Problem Description

LZ is learning to skate on ice. he's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created. We assume that LZ can only heap up snow drifts at integer coordinates.

Input

The first line of input contains a single integer n (1<=n<=100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1<=xi,yi<=1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output

Output the minimal number of snow drifts that need to be created in order for LZ to be able to reach any snow drift from any other one.

Sample Input

2
2 1
1 2

Sample Output

1
 
 
代码:
 
    
 #include 
 #include
 #include
 using namespace std;
 struct node
 {
     int x,y;
 }q[110];
 int father[110];
 int find(int x)
 {
     if(x!=father[x])
     father[x]=find(father[x]);
     return father[x];
 }
 int main()
 {
     int n,i,j,k,num = 0;
     //freopen("Din.txt","r",stdin);
     //freopen("ou.txt","w",stdout);
     while(scanf("%d",&n)!=EOF)
     {
       num=0;
     for(i = 1; i <= n ;i++)
     {
         scanf("%d%d",&q[i].x,&q[i].y);
     }
     for(i = 1; i <= n ;i++)
     father[i] = i;
     for(i = 1; i < n ; i++)
     {
         for(j = i+1; j <= n ;j++)
         {
             if(q[j].x==q[i].x||q[j].y==q[i].y)
             {
                 int px = find(i);
                 int py = find(j);
                 if(px!=py);
                 father[px]=py;
             }
         }
     }
     for(i=1;i<=n;i++)
      if(father[i]==i)
        num++;
     printf("%d\n",num-1);
  }
     return 0;
 }

你可能感兴趣的:(随笔)