跳到正文

个人记录

走廊泼水节

zzr8178541919约 3 分钟
原文
文章信息与版本

文章信息

发布
2020年11月6日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 3 分钟

版本

  1. v1当前

题目描述:

给定一棵N个节点的树,要求增加若干条边,把这棵树扩充为完全图,并满足图的唯一最小生成树仍然是这棵树。

求增加的边的权值总和最小是多少。

注意: 树中的所有边权均为整数,且新加的所有边权也必须为整数。

题解:

这是一道很清新的题目,考察的是最小生成树的原理。我们知道,求最小生成树的过程,就是在不断找图中的最小的边,若边两端的点x,y不在同一个并查集内,就加入这条边。

于是这道题我们想:在求最小生成树的时候,同时把其他的不选的边的值统计出来,假设此时要加(x,y,z)这条边,x集合中的个数为tot[x],y集合中的个数为tot[y],其他的不选的边要保证不选,那么所有的能够连通这两个并查集的点对应该加入(z+1)的边,一共有(tot[x]*tot[y]-1)个点对,而且能保证每次这样处理完后,每个并查集连起来都是一张完全图。

最终得到的一个并查集也是一张完全图!

我们在这过程中,不重不漏地弄掉了所有的贡献!此题得到解决!

C++
#include<cmath>
#include<cstring>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#define int long long
using namespace std;
const int maxn=6e3+5;
const int mod=100003;
inline int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch=='-')
		f=-1;
		ch=getchar();
	}
	while(ch>='0' && ch<='9')
	{
		x=x*10+ch-'0';
		ch=getchar();
	}
	return x*f;
}
int father[maxn];
int Find(int x)
{
	if(x!=father[x])
	{
		father[x]=Find(father[x]);
	}
	return father[x];
}
int tot[maxn];
int T,n;
struct node
{
	int x,y;
	int val;
}p[maxn];
bool cmp(node a,node b)
{
	return a.val<b.val;
}
signed main()
{
	T=read();
	while(T--)
	{
		int ans=0;
		n=read();
		for(int i=1;i<=n-1;i++)
		{
			p[i].x=read(),p[i].y=read(),p[i].val=read();
		}
		for(int i=1;i<=n;i++)
		father[i]=i,tot[i]=1;
		sort(p+1,p+n,cmp);
		for(int i=1;i<=n-1;i++)
		{
			int x=p[i].x,y=p[i].y;
			x=Find(x),y=Find(y);
			if(x==y)
			continue;
			ans=ans+(p[i].val+1)*(tot[x]*tot[y]-1);
			father[x]=y;	
			tot[y]+=tot[x];
		}
		printf("%lld\n",ans);
	}
	return 0;
}
/*

6 5 3
1 5 
4 5
1 4
2 3 
3 2
1 2
2 3
2 5
*/
原文