[poj1258 Agri-Net]最小生成树

复习了一下Kruskal和prim。

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const int MAX = 128;
struct edge {
	int from, to;
	int cost;
	bool operator<(const edge& B)const {
		return cost < B.cost;
	}
};
edge G[MAX*MAX];
int a[MAX][MAX];
int father[MAX];

int find(int x) {
	if (father[x] == x) return x;
	return father[x] = find(father[x]);
}

bool Union(int x, int y) {
	int fx = find(x), fy = find(y);
	if (fx != fy) {
		father[fx] = fy;
		return true;
	}
	return false;
}

//m:边数 
int kruskal(int m) {
	sort(G + 1, G + m + 1);
	int s = 0;
	for (int i = 1; i <= m; ++i) {
		edge e = G[i];
		if (Union(e.from, e.to)) {
			s += e.cost;
		}
	}
	return s;
}

int read() {
	char ch;
	while ((ch = getchar()) < '0' || ch > '9');
	int x = ch - '0';
	while ((ch = getchar()) >= '0' && ch <= '9') {
		x = (x << 3) + (x << 1) + ch - '0';
	}
	return x;
}

int main() {
	int n;
	while (~scanf(" %d", &n)) {
		for (int i = 1; i <= n; ++i) {
			for (int j = 1; j <= n; ++j) {
				a[i][j] = read();
			}
		}
		int es = 0;
		for (int i = 1; i <= n; ++i) {
			for (int j = i + 1; j <= n; ++j) {
				if (a[i][j] > 0) {
					G[++es] = (struct edge){i, j, a[i][j]};
				}
			}
		}
		for (int i = 1; i <= n; ++i) father[i] = i;
		printf("%d\n", kruskal(es));
	}
	return 0;
}

下面是Prim算法的

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const int MAX = 105;
int G[MAX][MAX];
int mincost[MAX];
bool vis[MAX];

int prim(int node) {
	memset(vis, false, sizeof(vis));
	fill(mincost, mincost + node + 1, 0xffffff);
	int sum = 0;
	mincost[1] = 0;
	for (int i = 1; i <= node; ++i) {
		int v = 0;
		for (int u = 1; u <= node; ++u) {
			if (!vis[u] && (v == 0 || mincost[v] > mincost[u])) {
				v = u;
			}
		}
		if (!v) break;
		sum += mincost[v];
		vis[v] = true;
		for (int i = 1; i <= node; ++i) {
			if (mincost[i] > G[v][i]) mincost[i] = G[v][i];
		}
	}
	return sum;
}
int read() {
	char ch;
	while ((ch = getchar()) < '0' || ch > '9');
	int x = ch - '0';
	while ((ch = getchar()) >= '0' && ch <= '9') {
		x = (x << 3) + (x << 1) + ch - '0';
	}
	return x;
}

int main() {
	int n;
	while (~scanf(" %d", &n)) {
		for (int i = 1; i <= n; ++i) {
			for (int j = 1; j <= n; ++j) {
				G[i][j] = read(); //scanf(" %d", &G[i][j]);
			}
		}
		printf("%d\n", prim(n));
	}
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值