any point union

Link: https://www.nowcoder.com/acm/contest/84/C
Source: Niuke.com

Topic description

There are several points on the plane. From each point, you can walk in any direction, until you hit another point, and then you can change the direction.
How many points need to be added at least so that the point pairs can reach each other.

Enter description:

The first line contains an integer n representing the number of points ( 1 <= n <= 100). 
The second line is n lines, each line contains two integers xi, and yi represents the coordinates (1<=xi,yi<=1000).
The positive direction of the y-axis is north, and the square of the x-axis is east.

Output description:

Output an integer indicating the minimum number of points to add.
Example 1

enter

2
2 1
1 2

output

1
Example 2

enter

2
2 1
4 1

output

0 

problem-solving ideas: 100 points, the scale is small, you can mess around. For any two points, if the abscissa or ordinate is the same, then the two points are mutually reachable, and a set is added, and the final answer is equal to the number of sets - 1 (the idea of ​​spanning tree)
#include<bits/stdc++.h>
using namespace std;

int x[110],y[110];
int f[1100];
int n;
void init()
{
    for(int i=0; i<=1000; i++)
        f[i] = i;
}

int Find(int a)
{
    if(f[a] == a)
        return a;
    else
        return f[a] = Find(f[a]);
}

void unite(int a, int b)
{
    int fa = Find(a);
    int fb = Find(b);
    if(fa != fb)
        f[fa] = fb;
}

intmain ()
{
    while(~scanf("%d",&n))
    {
        init();
        for(int i=1; i<=n; i++)
            scanf("%d %d",&x[i],&y[i]);

        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
                if(x[i] == x[j] || y[i] == y[j])
                    unite(i,j);
        int ans = 0;
        for(int i=1; i<=n; i++)
        {
            if(f[i] == i)
                years ++ ;
        }
        printf("%d\n",ans-1);
    }
    return 0;
}

 



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325169787&siteId=291194637