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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章