[poj1258 Agri-Net]最小生成树
2014-11-29 10:20
211 查看
复习了一下Kruskal和prim。
下面是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; }
相关文章推荐
- 超详细最小生成树 prim 普里姆算法 poj1258 Agri-Net 最小生成树基础题 MST
- POJ1258 Agri-Net 【最小生成树Prim】
- poj1258 Agri-Net 最小生成树 prim kruskal 模板
- poj1258 Agri-Net最小生成树问题
- Agri-Net_usaco3.1.1_poj1258_最小生成树
- POJ1258 Agri-Net(最小生成树)
- poj1258 Agri-Net +hdu 1233 还是畅通工程 (最小生成树Prime算法)
- POJ1258 Agri-Net【最小生成树】
- POJ1258 Agri-Net(最小生成树)
- poj1258 Agri-Net 最小生成树,kruskal算法
- poj1258 Agri-Net (最小生成树prime)
- Agri-Net ——最小生成树
- 初级->图算法->最小生成树 poj 1258 Agri-Net
- POJ 1258 Agri-Net 最小生成树(Kruskal算法入门)
- [usaco]Agri-Net(使用最小生成树算法)
- ACM POJ 1258 Agri-Net (简单最小生成树)
- [U]3.1.1 Agri-Net 简单的最小生成树问题Ford
- poj 1258 Agri-Net 最小生成树
- Poj1258_Agri-Net(最小生成树)
- POJ1258,Agri-Net,明显的最小生成树