问题 1435: [蓝桥杯][历届试题]国王的烦恼(并查集)
转自:link.
题目链接: link.
解题思路:本题使用并查集的思想;
先按道路损坏的时间排个序,题目上说如果两个岛前一天能到达后一天就不能到达,居民就会抗议,我们可以反着来想,最后所有的路都会损坏,所有的岛之间都不能到达。假如从后往前来,根据排序好的数据将小岛合并在一个集合,如果发现两个小岛能够到达了,他们就会抗议一天。使用并查集算法能够轻松解决。
居民会在两个小岛不能到达之后抗议一天,而同一天中可能会有多个小岛不能到达,所以在判断两个小岛是否能到达时还应该判断两个小岛不能到达的时间是不是同一天。
#include<iostream>
#include<algorithm>
using namespace std;
int n,m;
struct point {
int l;
int r;
int t;
};
int fa[100005];
struct point a[100005];
bool cmp(point x,point y)
{
return x.t>y.t;
}
int find(int root)
{
int son = root;
while(root!=fa[root])
{
root = fa[root];
}
while(son != root)
{
int temp = fa[son];
fa[son] = root;
son = temp;
}
}
void unit(int x,int y)
{
int root1 = find(x);
int root2 = find(y);
if(root1 != root2)
{
fa[root1] = root2;
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
cin>>a[i].l>>a[i].r>>a[i].t;
}
sort(a+1,a+m+1,cmp);
for(int i=1;i<=n;i++)
{
fa[i]=i;
}
int ans=0;
int last=0;
for(int i=1;i<=m;i++)
{
int root1 = find(a[i].l);
int root2 = find(a[i].r);
if(root1!=root2 && a[i].t!=last)
{
ans++;
last = a[i].t;
//cout<<a[i].l<<" "<<a[i].r<<endl;
}
unit(a[i].l,a[i].r);
}
cout<<ans<<endl;
return 0;
}