POJ-1287-Networking
链接:https://vjudge.net/problem/POJ-1287#author=dream2017
题意:
存在许多点和点与点之间的路径,路径长度不一,点到点之间可能存在多条路径。挑选部分路径使得所有点连通且总路径长度最小。
思路:
Kruskal
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | #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\n" ,sum); } return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步