數據結構實驗之圖論六:村村通公路
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
當前農村公路建設正如火如荼的展開,某鄉鎮政府決定實現村村通公路,工程師現有各個村落之間的原始道路統計數據表,表中列出了各村之間可以建設公路的若干條道路的成本,你的任務是根據給出的數據表,求使得每個村都有公路連通所需要的最低成本。
Input
連續多組數據輸入,每組數據包括村落數目N(N <= 1000)和可供選擇的道路數目M(M <= 3000),隨後M行對應M條道路,每行給出3個正整數,分別是該條道路直接連通的兩個村莊的編號和修建該道路的預算成本,村莊從1~N編號。
Output
輸出使每個村莊都有公路連通所需要的最低成本,如果輸入數據不能使所有村莊暢通,則輸出-1,表示有些村莊之間沒有路連通。
Sample Input
5 8 1 2 12 1 3 9 1 4 11 1 5 3 2 3 6 2 4 9 3 4 4 4 5 6
Sample Output
19
典型最小生成樹問題,模板題;
#include <iostream>
#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
#define ERROR -1
using namespace std;
int n, m;
int G[1100][1100];
int dist[1100];
int i, j, Min;
int money, num;
int V, W;
int FindMinDist ( )
{
Min = INF;
for( i=1; i<=n; i++ )
{
if( dist[i] !=0 && dist[i] < Min )
{
V = i;
Min = dist[i];
}
}
if( Min == INF )
{
V = ERROR;
}
return V;
}
void Prim ( )
{
money = -1;
num = 0;
while( 1 )
{
V = FindMinDist ( );
if( V == ERROR )
break;
money += dist[V];
dist[V] = 0; num++; // 將V收進樹裏
for( W=1; W<=n; W++ )
{
if( dist[W] != 0 )
{
if( G[V][W] < dist[W] )
{
dist[W] = G[V][W];
}
}
}
}
}
int main()
{
while( cin >> n >> m )
{
int s = 1;
for( i=1; i<=n; i++ )
{
for( j=1; j<=n; j++ )
{
if(i == j) G[i][j] = 0;
else G[i][j] = INF;
}
dist[i] = G[s][i];
}
dist[s] = 1;
while( m-- )
{
int a, b, c;
cin >> a >> b >> c;
if( G[a][b] > c )
{
G[a][b] = c;
G[b][a] = c;
}
}
Prim( );
if(num < n)
cout << -1 << endl;
else
cout << money << endl;
}
return 0;
}