7-10 公路村村通 (30 分)
這個題就是簡單的最小生成樹的算法,可以用Prim,也可以用Kruskal。
這裏我用的Prim因爲kruskal我換不是很熟練(haha)。
這個題我主要的錯誤就是對權值矩陣初始化,放在了讀取N,M的數據之前。
這就導致了我之前的初始化完全沒有效果,我換Debug了半天。
代碼:
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 1010;
const int INF = 1000000;
int N,M,dist[MAX],Edge[MAX][MAX];
bool book[MAX];
void Prim(){
int k,count = 0,weight = 0;
book[1] = true;
count++;
for(int i = 1;i <= N;i++) //初始化距離
dist[i] = Edge[1][i];
while(count < N){
int MIN = INF;
for(int i = 1;i <= N;i++){
if(!book[i] && MIN > dist[i]){
k = i;
MIN = dist[i];
}
}
if(MIN == INF) break;
book[k] = true;
count++;
weight += dist[k];
for(int i = 1;i <= N;i++){
if(!book[i] && dist[i] > Edge[k][i])
dist[i] = Edge[k][i];
}
}
if(count >= N) printf("%d\n",weight);
else printf("-1\n");
}
int main(){
int V1,V2,W;
fill(dist+1,dist+N+1,INF);
fill(book+1,book+N+1,false);
scanf("%d%d",&N,&M);
for(int i = 1;i <= N;i++){ //失誤,在沒有輸入N的時候就初始化
for(int j = 1;j <= N;j++){
if(i == j)
Edge[i][j] = 0;
else
Edge[i][j] = INF;
}
}
for(int i=0;i<M;i++){
scanf("%d%d%d",&V1,&V2,&W);
Edge[V1][V2] = W; //頂點從1開始編號
Edge[V2][V1] = W;
}
Prim();
system("pause");
return 0;
}