2 2 10 10 20 20 3 1 1 2 2 1000 1000
1414.2 oh!
这道题目的难点就是在于给出的是坐标,然后两个边之间的cost是长度,然而这个长度是需要自己计算的。
我的方法是用一个二重的for循环O(n*n)的复杂度为10000,也是比较小的。然后暴力枚举出所有的边的cost,然后把它放入struct point 中,剩下的就是单纯的kruskal算法了,只要熟悉就可以了。
给出AC代码:
#include<cstdio> #include<algorithm> #include<cstring> #include<queue> #include<cmath> using namespace std; typedef long long ll; const ll MAX_C = 100 + 50; const ll MAX_X = 1000 + 50; ll c, x[MAX_X], y[MAX_X]; struct point{ ll from, to; double cost; }; ll par[MAX_C], rank1[MAX_C], count1; point po[MAX_C * MAX_C]; void init(){ for(int i = 1; i <= c; i++){ par[i] = i; rank1[i] = 0; } } bool cmp(const point &po1, const point &po2){ return po1.cost < po2.cost; } int find(int x){ if(par[x] == x) return x; return par[x] = find(par[x]); } void unite(int x, int y){ x = find(x); y = find(y); if(x == y) return ; if(rank1[y] > rank1[x]){ par[x] = y; } else { par[y] = x; if(rank1[y] == rank1[x])rank1[x]++; } } bool same(int x, int y){ return find(x) == find(y); } void kruskal(){ init(); sort(po + 1, po + count1 +1, cmp); double res = 0; ll tally = 0; for(int i = 1; i <= count1; i++){ point e = po[i]; if(!same(e.from, e.to)){ unite(e.from, e.to); res += e.cost; tally++; } } if(tally == c-1)printf("%.1f\n", res * 100); else printf("oh!\n"); } int main(){ int t; scanf("%d", &t); while(t--){ scanf("%I64d", &c); for(int i = 1; i <= c; i++){ scanf("%I64d%I64d", &x[i], &y[i]); } count1 = 0; for(int i = 1; i <= c; i++){ for(int j = 1; j <= c; j++){ ll p1 = (x[i] - x[j]) * (x[i] - x[j]); ll p2 = (y[i] - y[j]) * (y[i] - y[j]); if(p1 + p2 <= 1000 * 1000 && p1 + p2 >= 100){ count1++; po[count1].from = i; po[count1].to = j; po[count1].cost = sqrt(p1 + p2); } } } kruskal(); } return 0; }