08-图7 公路村村通 (30分)
现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。
输入格式:
输入数据包括城镇数目正整数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<iostream>
using namespace std;
#define ERROR -1
#define INFINITY 65535
struct MNode{
int Nv;
int Ne;
int Vertex[1001][1001];
};
typedef struct MNode* MGraph;
MGraph Create(){
int v,w,weight;
MGraph Graph=(MGraph)malloc(sizeof(MNode));
cin>>Graph->Nv>>Graph->Ne;
for(int i=1;i<=Graph->Nv;i++)
for(int j=1;j<=Graph->Nv;j++){
Graph->Vertex[i][j]=INFINITY;
}
for(int i=1;i<=Graph->Ne;i++){
cin>>v>>w>>weight;
Graph->Vertex[v][w]=weight;
Graph->Vertex[w][v]=weight;
}
return Graph;
}
int FindMinV(MGraph Graph,int dist[]){
int MinV,min=INFINITY;
for(int i=1;i<=Graph->Nv;i++){
if(dist[i]!=0&&dist[i]<min){
min=dist[i];
MinV=i;
}
}
if(min==INFINITY)
return ERROR;
else
return MinV;
}
void Function(MGraph Graph){
int dist[Graph->Nv+1],V;
int VCount=1,TotalWeight=0;
for(int i=1;i<=Graph->Nv;i++)
dist[i]=INFINITY;
dist[1]=0;
for(int i=1;i<=Graph->Nv;i++){
if(Graph->Vertex[1][i]<INFINITY){
dist[i]=Graph->Vertex[1][i];
}
}
while(1){
V=FindMinV(Graph,dist);
if(V==ERROR)break;
VCount++;
TotalWeight+=dist[V];
dist[V]=0;
for(int i=1;i<=Graph->Nv;i++){
if(dist[i]!=0&&Graph->Vertex[V][i]<INFINITY){
if(dist[i]>Graph->Vertex[V][i]){
dist[i]=Graph->Vertex[V][i];
}
}
}
}
if(VCount!=Graph->Nv){
printf("-1");
}else{
printf("%d",TotalWeight);
}
}
int main(){
MGraph Graph=Create();
Function(Graph);
}
#include<bits/stdc++.h>
using namespace std;
#define INF 65536
int N, M , G[1005][1005], Dist[1005], counts = 0, cost = 0;
bool visit[1005] = {false};
int main() {
cin >> N >> M;
int v, u, c;
fill(G[0], G[0] + 1005 * 1005, INF);
fill(Dist, Dist + 1005, INF);
for (int i = 0; i < M; i++) {
cin >> v >> u >> c;
G[v][u] = G[u][v] = c;
}
for (int i = 2; i <= N; i++) {
Dist[i] = G[1][i];
}
Dist[1] = 0;
for (int i = 0; i < N; i++) {
int V = -1, Min = INF;
for (int j = 1; j <= N; j++) {
if (!visit[j] && Dist[j] < Min) {
Min = Dist[j];
V = j;
}
}
if (V == -1) break;
counts++;
cost += Min;
visit[V] = true;
Dist[V] = 0;
for (int j = 1; j <= N; j++) {
if (!visit[j] && G[V][j] != INF) {
if (G[V][j] < Dist[j]) {
Dist[j] = G[V][j];
}
}
}
}
if (counts != N) cout << "-1";
else cout << cost;
return 0;
}