标签:
Description
求出给定无向带权图的最小生成树。图的定点为字符型,权值为不超过100的整形。在提示中已经给出了部分代码,你只需要完善Prim算法即可。
Input
第一行为图的顶点个数n
第二行为图的边的条数e
接着e行为依附于一条边的两个顶点和边上的权值
Output
最小生成树中的边。
Sample Input
#include<iostream> #include<cstring> #include<cstdlib> using namespace std; typedef struct { int n; int e; char data[500]; int edge[500][500]; }Graph; typedef struct { int index; int cost; }mincost; typedef struct { int x; int y; int weight; }EDGE; typedef struct { int index; int flag; }F; void create(Graph &G, int n, int e) { int i, j, k, w; char a, b; for (i = 0; i< n; i++) cin >> G.data[i]; for (i = 0; i< n; i++) for (j = 0; j< n; j++) { if (i == j) G.edge[i][j] = 0; else G.edge[i][j] = 100; } for (k = 0; k< e; k++) { cin >> a; cin >> b; cin >> w; for (i = 0; i< n; i++) if (G.data[i] == a) break; for (j = 0; j< n; j++) if (G.data[j] == b) break; G.edge[i][j] = w; G.edge[j][i] = w; } G.n = n; G.e = e; } #define inf 32767 void Prim(Graph &G, int v) { int lowcost[100]; int min, closest[100], i, j, k; for (i = 0; i < G.n; i++) { lowcost[i] = G.edge[v][i]; closest[i] = v; } for (i = 1; i < G.n; i++) { min = inf; for (j = 0; j < G.n; j++) { if (lowcost[j] && lowcost[j] < min) { min = lowcost[j]; k = j; } } cout << ‘(‘ << G.data[closest[k]] << ‘,‘ << G.data[k] << ‘)‘; lowcost[k] = 0; for (j = 0; j < G.n; j++) if (G.edge[k][j] && G.edge[k][j] < lowcost[j]) { lowcost[j] = G.edge[k][j]; closest[j] = k; } } } int main() { Graph my; int n, e; cin >> n >> e; create(my, n, e); Prim(my, 0); return 0; }
标签:
原文地址:http://www.cnblogs.com/traini13/p/4579877.html