公路村村通 (30分)
現有村落間道路的統計資料表中,列出了有可能建設成標準公路的若干條道路的成本,求使每個村落都有公路連通所需要的最低成本。
輸入資料報括城鎮數目正整數nn
n(≤1000\le 1000≤1
000)和候選道路數目mm
m(≤3n\le 3n≤3
n);隨後的mm
m行對應mm
m條道路,每行給出3個正整數,分別是該條道路直接連通的兩個城鎮的編號以及該道路改建的預算成本。為簡單起見,城鎮從1到nn
n編號。
輸出村村通需要的最低成本。如果輸入資料不足以保證暢通,則輸出−1-1−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
本題就是求圖的最小生成樹
使用vector做鄰接表儲存圖
我用的是krusal演算法,我們先把給出的邊按照權值排序,然後每次選擇權值最小的邊,這裡要判斷是不是邊選重了(即連線邊的點被選了2次),用並查集判斷,知道選擇出n-1條邊
#include #include #include #include #include #include using namespace std;
typedef struct bianbian;
int n,m;
int f[1001]; ///並查集使用的陣列
bool cmp(const bian a,const bian b)
void init()
}int getf(int a)
int merge(int a,int b)
int main(int argc, char *argv)
sort(v.begin(),v.end(),cmp); ///根據權值對邊排序
for(int i = 0; i < v.size(); ++i)
if(count == n-1) break;
} if(count != n-1) printf("-1\n"); ///如果最後沒有選出n-1條邊,那麼只能是條件不夠
else
printf("%d\n",ans);
return 0;
}
PTA 公路村村通 最小生成樹
現有村落間道路的統計資料表中,列出了有可能建設成標準公路的若干條道路的成本,求使每個村落都有公路連通所需要的最低成本。輸入資料報括城鎮數目正整數n n le 1000 1 000 和候選道路數目m m le 3n 3 n 隨後的m m行對應m m條道路,每行給出3個正整數,分別是該條道路直接連通的兩...
公路村村通 30分 最小生成樹
公路村村通 30分 現有村落間道路的統計資料表中,列出了有可能建設成標準公路的若干條道路的成本,求使每個村落都有公路連通所需要的最低成本。輸入資料報括城鎮數目正整數n n le 1000 1 000 和候選道路數目m m le 3n 3 n 隨後的m m行對應m m條道路,每行給出3個正整數,分別是...
公路村村通
公路村村通 kruscal 演算法 include include include using namespace std int per 1010 n,m struct node 結構體來儲存邊 x 5005 bool cmp node a,node b int find int x 並查集的查詢...