现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。
输入格式:
输入数据包括城镇数目正整数N(≤1000)和候选道路数目M(≤3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。
输出格式:
输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出−1,表示需要建设更多公路。
输入样例:
6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3
输出样例:
12
代码:
//最小生成树
#include<stdio.h>
#include<stdlib.h>
typedef struct GNode* MGraph;
struct GNode {
int Nv;
int Ne;
int** G;
};
typedef struct ENode* Edge;
struct ENode {
int V1, V2;
int Weight; //权重
};
MGraph CreateGraph(int VertexNum) {
int X, Y;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct ENode));
Graph->G = (int**)malloc(sizeof(int*) * 1001);
for (int i = 0; i < 1001; i++) {
Graph->G[i] = (int*)malloc(sizeof(int) * 1001);
}
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (X = 1; X <= Graph->Nv; X++) {
for (Y = 1; Y <= Graph->Nv; Y++) {
Graph->G[X][Y] = 100000; //假设若X到Y没有直接的边,则Graph->G[X][Y]定义为100000
}
}
return Graph;
}
void InsertEdge(MGraph Graph, Edge E) {
Graph->G[E->V1][E->V2] = E->Weight;
Graph->G[E->V2][E->V1] = E->Weight;
}
MGraph BuildGraph() {
MGraph Graph;
Edge E;
int Nv, i;
scanf("%d", &Nv);
Graph = CreateGraph(Nv);
scanf("%d", &(Graph->Ne));
if (Graph->Ne != 0) {
E = (Edge)malloc(sizeof(struct ENode));
for (i = 0; i < Graph->Ne; i++) {
scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
InsertEdge(Graph, E);
}
}
return Graph;
}
int FindMinDist(MGraph Graph, int dist[]) {
int MinV, V;
int MinDist = 100000;
for (V = 1; V <= Graph->Nv; V++) {
if (dist[V] != 0 && dist[V] < MinDist) {
MinDist = dist[V];
MinV = V;
}
}
if (MinDist < 100000)
return MinV;
else
return -1;
}
int Prim(MGraph Graph) {
int dist[10001];
int totalWeight; //权重和
int V, W;
int VCount=0; //收录的顶点数
for (V = 1; V <= Graph->Nv; V++) {
dist[V] = Graph->G[1][V];
}
totalWeight = 0;
VCount++;
dist[1] = 0;
while (1) {
V = FindMinDist(Graph, dist);
if (V == -1)
break;
totalWeight += dist[V];
dist[V] = 0;
VCount++;
for (W = 1; W <= Graph->Nv; W++) {
if (dist[W] != 0 && Graph->G[V][W] < 100000) {
if (Graph->G[V][W] < dist[W]) {
dist[W] = Graph->G[V][W];
}
}
}
}
if (VCount < Graph->Nv)
totalWeight = -1;
return totalWeight;
}
int main() {
MGraph Graph = BuildGraph();
int result = Prim(Graph);
printf("%d", result);
}
文章描述了使用Prim算法解决村落间道路建设问题,给定成本数据,目标是找到最低成本使得所有村落都能通过公路相连。代码实现了一个最小生成树算法来计算所需的最低成本。
1998






