CH 6201 走廊潑水節 最小生成樹

~hsm~發表於2019-03-11

title

CH 6201

analysis

以後填坑。。。。qwq

code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=6e3+10;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1,ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
struct mst
{
	int x,y,z;
}e[maxn];
int fa[maxn];
inline int get(int x)
{
	if (fa[x]==x) return x;
	return fa[x]=get(fa[x]);
}
inline bool operator < (mst a,mst b)
{
	return a.z<b.z;
}
int s[maxn];
ll ans;
int main()
{
	int t;read(t);
	while (t--)
	{
		int n;
		read(n);
		for (int i=0;i<=n;++i)
			fa[i]=i,s[i]=1;
		for (int i=1;i<n;++i)
			read(e[i].x),read(e[i].y),read(e[i].z);
		sort(e+1,e+n);
		ans=0;
		for (int i=1;i<n;++i)
		{
			int x=get(e[i].x),y=get(e[i].y);
			if (x==y) continue;
			ans+=(ll)(e[i].z+1)*(s[x]*s[y]-1);
			fa[x]=y;
			s[y]+=s[x];
		}
		printf("%lld\n",ans);
	}
	return 0;
}

相關文章