并查集。
这么久没做题了,竟然快速的敲了个并查集出来还是蛮爽的。
这个题目我是把能够彼此到达(中间可以通过其他点)的那些点归纳到一个集合中,最后统计集合的数目,需要新加的点就是集合的数目减1。
有个地方需要证明,就是不存在添加一个点可以同时连通多个集合的情况。没举出反例,也没证明出来,怀疑是数学上的某个定理之类的。
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <queue>
using namespace std;
const int N = 105;
int father[N];
int n;
void init()
{
for(int i=0;i<n;i++)
{
father[i] = i;
}
}
int find(int x)
{
if(x!=father[x])
{
father[x] = find(father[x]);
}
return father[x];
}
void merge(int x, int y)
{
x = find(x);
y = find(y);
if(x == y)
{
return;
}
father[x] = y;
}
int count()
{
int ans = 0;
for(int i=0; i<n; i++ )
{
if(find(i) == i)
{
ans++;
}
}
return ans;
}
struct Point
{
int x,y;
bool can_reach(Point b)
{
if(x == b.x || y == b.y)
{
return true;
}
return false;
}
}p[N];
int main()
{
cin>>n;
init();
for(int i=0;i<n;i++)
{
cin>>p[i].x>>p[i].y;
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(p[i].can_reach(p[j]))
{
merge(i,j);
}
}
}
cout<<count()-1<<endl;
return 0;
}