链接:https://vjudge.net/problem/POJ-1287#author=dream2017
题意:
存在许多点和点与点之间的路径,路径长度不一,点到点之间可能存在多条路径。挑选部分路径使得所有点连通且总路径长度最小。
思路:
Kruskal
代码:
#include <iostream> #include <memory.h> #include <string> #include <istream> #include <sstream> #include <vector> #include <stack> #include <algorithm> #include <map> #include <queue> #include <math.h> using namespace std; typedef long long LL; const int MAXM = 10000; const int MAXN = 100; struct Path { int _l; int _r; int _value; bool operator < (const Path & that)const { return this->_value < that._value; } }path[MAXM]; int Father[MAXN]; int Get_F(int x) { return Father[x] = (Father[x] == x) ? x : Get_F(Father[x]); } int main() { int p,r; while (~scanf("%d%d",&p,&r) && p) { for (int i = 1;i<=p;i++) Father[i] = i; for (int i = 1;i<=r;i++) scanf("%d%d%d",&path[i]._l,&path[i]._r,&path[i]._value); sort(path+1,path+1+r); int sum = 0; for (int i = 1;i<=r;i++) { int tl = Get_F(path[i]._l); int tr = Get_F(path[i]._r); if (tl != tr) { Father[tl] = tr; sum += path[i]._value; } } printf("%d ",sum); } return 0; }