[poj1258 Agri-Net]最小生成树

来源:互联网 发布:有淘宝账号秒批七万 编辑:程序博客网 时间:2024/05/17 04:12

复习了一下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