码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 11183 - Teen Girl Squad(最小树形图)

时间:2014-09-12 12:01:45      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   ar   for   sp   代码   

UVA 11183 - Teen Girl Squad

题目链接

题意:本质就是给一个有向图,有一些能连接的边,连接有一个代价,问从0能遍历到所有点的,并且代价最小的最小代价

思路:最小树形图的裸题,用朱刘算法求解,验证一下模板

代码:

#include <cstdio>
#include <cstring>

const int MAXNODE = 1005;
const int MAXEDGE = 40005;

typedef int Type;
const Type INF = 0x3f3f3f3f;

struct Edge {
	int u, v;
	Type dist;
	Edge() {}
	Edge(int u, int v, Type dist) {
		this->u = u;
		this->v = v;
		this->dist = dist;
	}
};

struct Directed_MST {
	int n, m;
	Edge edges[MAXEDGE];
	int vis[MAXNODE];
	int pre[MAXNODE];
	int id[MAXNODE];
	Type in[MAXNODE];

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

	void add_Edge(int u, int v, Type dist) {
		edges[m++] = Edge(u, v, dist);
	}

	void add_Edge(Edge e) {
		edges[m++] = e;
	}

	Type dir_mst(int root) {
		Type ans = 0;
		while (true) {
			for (int i = 0; i < n; i++) in[i] = INF;
			for (int i = 0; i < m; i++) {
				int u = edges[i].u;
				int v = edges[i].v;
				if (edges[i].dist < in[v] && u != v) {
					in[v] = edges[i].dist;
					pre[v] = u;
				}
			}

			for (int i = 0; i < n; i++) {
				if (i == root) continue;
				if (in[i] == INF) return -1;
			}

			int cnt = 0;
			memset(id, -1, sizeof(id));
			memset(vis, -1, sizeof(vis));
			in[root] = 0;
			for (int i = 0; i < n; i++) {
				ans += in[i];
				int v = i;
				while (vis[v] != i && id[v] == -1 && v != root) {
					vis[v] = i;
					v = pre[v];
				}
				if (v != root && id[v] == -1) {
					for (int u = pre[v]; u != v; u = pre[u])
						id[u] = cnt;
					id[v] = cnt++;
				}
			}
			if (cnt == 0) break;
			for (int i = 0; i < n; i++)
				if (id[i] == -1) id[i] = cnt++;
			for (int i = 0; i < m; i++) {
				int v = edges[i].v;
				edges[i].u = id[edges[i].u];
				edges[i].v = id[edges[i].v];
				if (edges[i].u != edges[i].v)
					edges[i].dist -= in[v];
			}
			n = cnt;
			root = id[root];
		}
		return ans;
	}
} gao;

int t, n, m;

int main() {
	int cas = 0;
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d", &n, &m);
		gao.init(n);
		int u, v, d;
		while (m--) {
			scanf("%d%d%d", &u, &v, &d);
			gao.add_Edge(u, v, d);
		}
		int tmp = gao.dir_mst(0);
		printf("Case #%d: ", ++cas);
		if (tmp == -1) printf("Possums!\n");
		else printf("%d\n", tmp);
	}
	return 0;
}


UVA 11183 - Teen Girl Squad(最小树形图)

标签:style   http   color   io   os   ar   for   sp   代码   

原文地址:http://blog.csdn.net/accelerator_/article/details/39226921

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!