生活随笔
收集整理的這篇文章主要介紹了
HDU1863
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://acm.hdu.edu.cn/showproblem.php?pid=1863
題目很簡單 就是使用kruskal算法 求最小生成樹 的總權值
當然也可以使用prim算法來做 但是稍微復雜了一點 還要對輸入的邊和權值
用一個鄰接矩陣或者鄰接表來存儲圖
用kruskal的話 直接對邊排序 然后判決邊的兩個頂點是否屬于同一個集合
再來判斷是否要加入這條邊
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
#define MMAX 150
int s[MMAX], e[MMAX], w[MMAX], r[MMAX], p[MMAX];
bool compare(
int i,
int j)
{
return w[i] < w[j];
}
int find(
int x)
{
return p[x] == x ? x : p[x]=find(p[x]);
}
int main()
{
int n, m;
int totalcost;
int totaledge;
while (
cin >> n >> m, n){totalcost =
0;totaledge =
0;
for (
int i =
0; i < n; i++){
cin >> s[i] >> e[i] >> w[i];}
for (
int i =
1; i <= m; i++){p[i] = i;}
for (
int i =
0; i < n; i++){r[i] = i;}sort(r, r + n, compare);
for (
int i =
0; i < n; i++){
int start, end;start = s[r[i]];end = e[r[i]];
int x, y;x = find(start);y = find(end);
if (x != y){p[x] = y;totalcost += w[r[i]];totaledge++;}}
if (totaledge < m -
1)
cout <<
"?"<<endl;
elsecout << totalcost << endl;}
return 0;
}
總結
以上是生活随笔為你收集整理的HDU1863的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。