Codeforces Round #134 (Div. 2)C. Ice Skating

並查集。

這麼久沒做題了,竟然快速的敲了個並查集出來還是蠻爽的。

這個題目我是把能夠彼此到達(中間可以通過其他點)的那些點歸納到一個集合中,最後統計集合的數目,需要新加的點就是集合的數目減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;
}


發佈了32 篇原創文章 · 獲贊 10 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章