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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值