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 |
#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[1005]; void init_bcj(){ for (int i = 0; i < 1005; 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 main(){ int n= 0,m = 0; while (cin >> n && n) { cin >> m; init_bcj(); req.clear(); for (int i = 1; i <= m; i++) { int a,b; scanf(" %d %d",&a,&b); requestType tmp; tmp.a = a,tmp.b = b,tmp.cost = 1; req.push_back(tmp); } sort(req.begin(), req.end(), cmp); int res = n-1; for (int i = 0; i < req.size(); i++) { requestType &now = req[i]; if (check_bcj(now.a, now.b)) { continue; }else{ res -= now.cost; unify_bcj(now.a, now.b); } } cout << res << endl; } return 0; } |
Kruskal算法,并查集老写挫,正确的写法是合并操作是把parentA和parentB合并(链接根节点),查询的时候压缩,就是
return parent_bcj[currNode] = query_bcj(parent_bcj[currNode]);
这句。