NC53074 Forsaken喜欢独一无二的树 (最小生成树)

题目

代码

// Problem: Forsaken喜欢独一无二的树
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/problem/53074
// Memory Limit: 2 MB
// Time Limit: 53074000 ms
// Created Time: 2022-07-09 22:41:37
// 
// Powered by CP Editor (https://cpeditor.org)

//fw
#include<bits/stdc++.h>
#define zp ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
#define pii pair <int, int>
#define pll pair <ll, ll>
#define endl '\n'
#define il inline
#define pb push_back
#define fi first
#define se second
#define lc u<<1
#define rc u<<1|1
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int N=2e5+10;
struct edge{
	int a,b,w;
}e[N];
int n,m;
bool cmp(edge a,edge b)
{
	return a.w<b.w;
}
int p[N];
int find(int x)
{
	return p[x]==x?x:p[x]=find(p[x]);
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
    	cin>>e[i].a>>e[i].b>>e[i].w;
    }
    for(int i=1;i<=n;i++)p[i]=i;

    sort(e+1,e+1+m,cmp);
    ll ans=0;
	
    //类似双指针
    for(int i=1;i<=m;)
    {	int j;
    	for(j=i;j<=m;j++)//排序后按长度将边分成了一个个集合
    	{
    		if(e[i].w==e[j].w)//对于所有权值相同的边,将所有可能构成最小生成树的边全部计入总和
    		{
    			if(find(e[j].a)!=find(e[j].b))
    				ans+=e[i].w;
    		}
    		else  //如果出现了边长不相同的则直接退出,准备遍历下一段长度的边
    			break;
    	}
    	for(;i<j;i++)//在这一段长度里保留一条边
    	{
    		int x=find(e[i].a),y=find(e[i].b);
    		if(x!=y)
    		{
    			p[x]=y;
    			ans-=e[i].w;//减去构成最小生成树的边后即为删除的总边长
    		}
    	}

    }
    cout<<ans<<endl;

    return 0;
}
posted @ 2022-07-09 23:05  Avarice_Zhao  阅读(28)  评论(0编辑  收藏  举报