历届试题 国王的烦恼

//N值不够大,会出现运行超时的现象

//路径未压缩,也会出现超时

//主要的思想是按天数从大到小排序,然后开始并查集运算,建立起连通性


#include<bits/stdc++.h>

using namespace std;

const int N = 100000;
struct Node{
	int u, v, day;
    bool operator <(const Node &b)const {//第一个是为了保护我们传的引用不被非法修改(传引用为了节约开销,一般的类可能比较复杂) //第二个const 是为了修饰 this 指针     
	//从大到小             
		return day > b.day;
	}
}Island[N];

int pre[N];
/*
bool cmp(Node a, Node b){
		return a.day > b.day;
}*/

void Init()
{
	for(int i=1; i<=N; i++){
		pre[i] = i;
	}
}
int Find(int a)
{
    return pre[a] == a ? a : pre[a] = Find(pre[a]);//顺带压缩路径 
}

bool Union(int a, int b)
{
    a = Find(a), b = Find(b);

    if(a == b){
        return true;
    }
    else{
        pre[a] = b;
        return false;
    }
}


int main()
{
	int n, m;
	
//	cin >> n >> m;
	scanf("%d%d", &n, &m);	
	for(int i=0; i<m; i++){
		//cin >> Island[i].u >> Island[i].v >> Island[i].day;
		scanf("%d%d%d", &Island[i].u, &Island[i].v, &Island[i].day);
	}
	
//	sort(Island, Island+m, cmp);//从day大到小排列,相当于逐渐建立起连通性 若从小到大排序,则相当于建好连通性后来破坏连通性 
	sort(Island, Island+m); 
	Init();
	
	int pretmp = -1, ans = 0;
	for (int i=0; i <m; ++i)	{
		if (!Union(Island[i].u, Island[i].v) && pretmp != Island[i].day) //两个小岛不连通,联通两个岛(因为day是从大到小的),且与上一个大桥的天数不同		
		{			
			++ans;
			pretmp = Island[i].day;		
		} 	
		
	}

	printf("%d\n", ans);
	
	return 0;
 } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值