poj 3164(最小树形图)

题目链接

最小树形图的模板题, 原理和代码都是从这位神牛的博客http://blog.csdn.net/wsniyufang/article/details/6747392学到的。。


#include <vector>
#include <cstring>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

typedef double LL;
const LL INF = 1e11;
const int N = 105;
const int M = 10005;

struct DMST {
	struct Edge {
		int u, v;
		LL w;

		void init(int a, int b, LL c) {
			this->u = a, this->v = b, w = c;
		}
	};

	Edge E[M];
	LL in[N];
	int no[N], pre[N], vis[N];
	int n, m, rt;

	void init(int n, int r) {
		this->n = n;
		rt = r;
		m = 0;
	}

	void add(int u, int v, LL w) {
		E[m].init(u, v, w);
		m++;
	}

	LL gao() {
		LL res = 0;
		while (1) {
			fill(in, in + n, INF);
			for (int i = 0; i < m; i++) {
				int u = E[i].u, v = E[i].v;
				if (u != v && E[i].w < in[v]) {
					in[v] = E[i].w;
					pre[v] = u;		
				}
			}

			for (int i = 0; i < n; i++) {
				if (i == rt) continue;
				if (in[i] == INF) return -1;
			}
			
			int cnt = 0;
			fill(no, no + n, -1);
			fill(vis, vis + n, -1);
			
			in[rt] = 0;
			for (int i = 0; i < n; i++) {
				res += in[i];
				int v = i;
				while (vis[v] != i && no[v] == -1 && v != rt) {
					vis[v] = i;
					v = pre[v];
				}

				if (v != rt && no[v] == -1) {
					for (int u = pre[v]; u != v; u = pre[u]) {
						no[u] = cnt;
					}
					no[v] = cnt++;
				}	
			}

			if (cnt == 0) break;
			for (int i = 0; i < n; i++)
				if (no[i] == -1) {
					no[i] = cnt++;
				}

			for (int i = 0; i < m; i++) {
				int v = E[i].v;
				E[i].u = no[E[i].u];
				E[i].v = no[E[i].v];
				if (E[i].u != E[i].v)
					E[i].w -= in[v];
			}

			n = cnt;
			rt = no[rt];
					
		}

		return res;		
	}	
}G;

#define fi first
#define se second
typedef pair<double, double> Point;

Point pts[N];

inline double pow2(double x) {
	return x * x;
}

inline double dist(Point a, Point b) {
	return sqrt(pow2(a.fi - b.fi) + pow2(a.se - b.se));
}

int main() {
	int n, m, u, v;
	while (~scanf("%d%d", &n, &m)) {
		for (int i = 0; i < n; i++) {
			scanf("%lf%lf", &pts[i].fi, &pts[i].se);
		}	

		G.init(n, 0);

		for (int i = 0; i < m; i++) {
			scanf("%d%d", &u, &v);
			u--, v--;
			G.add(u, v, dist(pts[u], pts[v]));
		}
		
		LL res = G.gao();

		if (res == -1)
			puts("poor snoopy");
		else
			printf("%.2f\n", res);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值