HDU 5723 Abandoned country(最小生成树+DFS)

给定一个图求其最小生成树,并且算出最小生成树上任意两个点的期望距离

因为题目中说到每条边的边权都是唯一的,所以可以知道最小生成树唯一

然后求期望距离。点的数目非常大所以求出任意两点间距离在算期望距离是不现实的。

但是根据期望的累加性质可以想到,对于每条边,他对期望的贡献是经过他的路径数量*边权。

而经过这条边的数目为这条边左边的点和右边点的积。最后问题转化成统计一棵树上每个点他的子树的点数目


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <string.h>
#include <string>
#include <iomanip>
#include <cstring>
#include <vector>
#include <functional>
#include <cmath>
#include <sstream>
#include <set>

using namespace std;
#define PI acos(-1.0)
#define sp system("pause")
typedef long long ll;
typedef unsigned long long ull;
const ll mod = 1000000007;
#define PI acos(-1.0)

struct Edge
{
	ll p,n, c;
	Edge(){ p = n = c = 0; }
	Edge(ll x, ll y, ll z) :p(x), n(y), c(z){}
	friend bool operator<(const Edge& x, const Edge &y)
	{
		return x.c < y.c;
	}
};
bool vis[100000 + 20];
int fa[100000 + 20];

int getfa(int x)
{
	return fa[x] == x ? x : fa[x] = getfa(fa[x]);
}
ll cot[100000 + 20];
vector<Edge>g[100000 + 20];
vector<Edge>edge;
ll n, m;
double ans = 0;
void init()
{
	memset(cot, 0, sizeof cot);
	memset(vis, false, sizeof vis);
	for (int i = 0; i <= 100000; i++)
	{
		g[i].clear();
	}
	edge.clear();
	ans = 0;
}

void dfs(int x)
{
	vis[x] = true;
	for (int i = 0; i < g[x].size(); i++)
	{
		if (!vis[g[x][i].n])
		{
			dfs(g[x][i].n);
			ans += (cot[g[x][i].n] * 1.0*(n - cot[g[x][i].n])*g[x][i].c / (n*(n - 1)*1.0 / 2.0));
			cot[x] += cot[g[x][i].n];
		}
	}
	cot[x]++;
}

int main()
{
	int T;
	cin >> T;
	while (T--)
	{
		cin >> n >> m;
		init();
		ll ans1 = 0;
		for (int i = 0; i <= n; i++)fa[i] = i;
		for (int i = 0; i < m; i++)
		{
			Edge x;
			scanf("%lld%lld%lld", &x.p, &x.n, &x.c);
			edge.push_back(x);
		}
		sort(edge.begin(), edge.end());
		ll cot = 0;
		for (int i = 0; i < m; i++)
		{
			int x = getfa(edge[i].n), y = getfa(edge[i].p);
			if (x != y)
			{
				cot++;
				fa[x] = y;
				ans1 += edge[i].c;
				g[edge[i].n].push_back(Edge(edge[i].n, edge[i].p, edge[i].c));
				g[edge[i].p].push_back(Edge(edge[i].p, edge[i].n, edge[i].c));
			}
			if (cot == n - 1)break;
		}
		dfs(1);
		printf("%lld %.2f\n", ans1, ans);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值