pat-top 1016. Uniqueness of MST (35)

5 篇文章 0 订阅

https://www.patest.cn/contests/pat-t-practise/1016

照抄了 http://blog.csdn.net/jtjy568805874/article/details/60338730


确定是否唯一是难点,在每新加一个边时,先看同等权值的边可否加入,并对所有可加入的边进行计数,最后如果边数小于n,不小于则最小生成树不唯一。


#include <cstdio>
#include <algorithm>
#include <vector>
#define rep(i,j,k) for(int i=j;i<=k;i++)
#define intwo(i,j) scanf("%d%d",&i,&j)
#define inthree(i,j,k) scanf("%d%d%d",&i,&j,&k)
using namespace std;

const int maxn = 3e5 + 10;
int n, m;
int fa[maxn];


int find(int x) {
	return x == fa[x] ? x : fa[x] = find(fa[x]);
}
typedef struct e {
	int x, y, w;
	bool friend operator < (struct e a, struct e b) {
		return a.w < b.w;
	}
}E;
E es[maxn];

int main()
{
	intwo(n, m);
	int mCost = 0, tot = 0, nCompt = n; //tot 可出现在最小生成树中的边的个数
	rep(i, 1, n) fa[i] = i;
	rep(i, 1, m) inthree(es[i].x, es[i].y, es[i].w);
	sort(es + 1, es + m + 1);
	for (int i = 1, j; i <= m; i = j)
	{
		for (j = i; j <= m&&es[i].w == es[j].w; j++)
		{
			int fx = find(es[j].x), fy = find(es[j].y);
			if (fx == fy) continue; else tot++;
		}
		for (j = i; j <= m&&es[i].w == es[j].w; j++)
		{
			int fx = find(es[j].x), fy = find(es[j].y);
			if (fx == fy) continue; 
			fa[fx] = fy; mCost += es[j].w; nCompt--;
		}
	}
	if (nCompt == 1) printf("%d\n%s\n", mCost, tot < n ? "Yes" : "No");
	else printf("No MST\n%d\n", nCompt);
    return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值