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 |
#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 nodeType{ double x; double y; } node[755]; struct requestType{ int a; int b; double 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(){ init_bcj(); req.clear(); memset(node, 0, sizeof(node)); int n = 0; scanf(" %d",&n); for (int i = 1; i <= n; i++) { nodeType &now = node[i]; scanf(" %lf %lf",&now.x,&now.y); } for (int i = 1;i <= n; i++) { for (int j = i+1; j <= n; j++) { requestType tmp; tmp.a = i,tmp.b = j,tmp.cost = sqrt(abs(node[i].x-node[j].x)*abs(node[i].x-node[j].x)+abs(node[i].y-node[j].y)*abs(node[i].y-node[j].y)); req.push_back(tmp); } } int m; scanf(" %d",&m); for (int i = 1;i <= m; i++) { requestType tmp; int a,b; scanf(" %d %d",&a,&b); tmp.a = a,tmp.b = b,tmp.cost = 0; req.push_back(tmp); } sort(req.begin(), req.end(), cmp); for (int i =0; i < req.size(); i++) { if (check_bcj(req[i].a, req[i].b)) { continue; }{ unify_bcj(req[i].a, req[i].b); if (req[i].cost) { printf("%d %dn",req[i].a,req[i].b); } } } return 0; } |
要是在POJ上做的话不要交C++会T,交G++就好了。
kruskal,没啥好说的。