蓝桥杯真题 问题 1435: [蓝桥杯][历届试题]国王的烦恼

问题 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;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值