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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <ctime> #include <iomanip> #include <cmath> #include <set> #include <stack> using namespace std; struct requestType{ int a; int b; int cost; }; vector<requestType> req; int parent_bcj[105]; void init_bcj(){ for (int i = 0; i < 105; i++) { parent_bcj[i] = i; } } int query_bcj(int currNode){ if (parent_bcj[currNode] == currNode) { return currNode; }else return parent_bcj[currNode] = query_bcj(parent_bcj[currNode]); } void unify_bcj(int a,int b){ int pa = query_bcj(a); int pb = query_bcj(b); if (pa == a) { parent_bcj[pa] = pb; }else { parent_bcj[pb] = pa; } } bool check_bcj(int a,int b){ int pa = query_bcj(a); int pb = query_bcj(b); if (pa == pb) { return true; }else{ return false; } } bool cmp(requestType a,requestType b){ return a.cost > b.cost; } int kruskal(int startReqPos,int n){ init_bcj(); int maxw = -1,minw = 10001,cnt = 0; for (int i = startReqPos; i < (int)req.size(); i++) { if (check_bcj(req[i].a, req[i].b)) { continue; }else{ unify_bcj(req[i].a, req[i].b); maxw = max(req[i].cost,maxw); minw = min(req[i].cost,minw); cnt++; } } //cout << "+" << maxw-minw << "=" << cnt << endl; if (cnt == n-1) { return maxw - minw; }else{ return -1; } } int main(){ int n = 0,m = 0; while (cin >> n >> m) { req.clear(); if (n == 0 && m == 0) { break; } for (int i = 0; i < m; i++) { requestType tmp; scanf(" %d %d %d",&tmp.a,&tmp.b,&tmp.cost); req.push_back(tmp); } sort(req.begin(), req.end(), cmp); int ans = 10001; for (int i = 0;i < (int)req.size(); i++) { int res = kruskal(i, n); if (res >= 0) { ans = min(ans, res); } } if (ans == 10001) { ans = -1; } cout << ans << endl; } return 0; } |
在kruskal的基础上,每一次干掉一条边,再kruskal一次,如果得到了生成树,就看看他的最大边权-最小边权是不是可以更新当前最优解,然后反复这么搞把所有边都搞掉就完成遍历了,因为事先已经对边权排序了,这么做并不会丢解。