【贪心】 TOJ 4121. Muxiaokui's Problem

来源:互联网 发布:如何评价火绒 知乎 编辑:程序博客网 时间:2024/05/17 01:40

对两个连通块做最小生成树,然后中间的边选一条代价最小的就行了。。。。

#include <iostream>#include <queue>#include <stack>#include <map>#include <set>#include <bitset>#include <cstdio>#include <algorithm>#include <cstring>#include <climits>#include <cstdlib>#include <cmath>#include <time.h>#define maxn 1005#define maxm 1000005#define eps 1e-7#define mod 1000000007#define INF 0x3f3f3f3f#define PI (acos(-1.0))#define lowbit(x) (x&(-x))#define mp make_pair#define ls o<<1#define rs o<<1 | 1#define lson o<<1, L, mid #define rson o<<1 | 1, mid+1, R#define pii pair<int, int>#pragma comment(linker, "/STACK:16777216")typedef long long LL;typedef unsigned long long ULL;//typedef int LL; using namespace std;LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}// headstruct node{int u, v;double c;node(int u = 0, int v = 0, double c = 0) : u(u), v(v), c(c) {}}e[maxm];int flag[maxn];int f[maxn];pair<double, double> p[maxn];double tt[maxm];int cnt, n;int find(int u){return f[u] = f[u] == u ? f[u] : find(f[u]);}int cmp(node aa, node bb){return aa.c < bb.c;}bool merge(int u, int v){int uu = find(u), vv = find(v);if(uu == vv) return false;f[uu] = vv;return true;}void work(){int kk, d;double u, v;scanf("%d%d", &d, &n);cnt = 0;for(int i = 0; i < n; i++) {scanf("%lf%lf%d", &u, &v, &kk);p[i] = mp(u, v);flag[i] = kk;}int tcnt = 0;double res = 1e15;for(int i = 0; i < n; i++)for(int j = i+1; j < n; j++) {double t1 = p[i].first - p[j].first;double t2 = p[i].second - p[j].second;double t = t1 * t1 + t2 * t2;t = sqrt(t);if(flag[i] ^ flag[j]) res = min(res, t);else e[cnt++] = node(i, j, t);}if(fabs(res - 1e15) > eps) tt[tcnt++] = res;sort(e, e+cnt, cmp);for(int i = 0; i < n; i++) f[i] = i;for(int i = 0; i < cnt; i++) {if(merge(e[i].u, e[i].v)) tt[tcnt++] = e[i].c;}double ans = 0;sort(tt, tt+tcnt);for(int i = 0; i < tcnt - d; i++) ans += tt[i];printf("%.2f\n", ans);}int main(){int _;scanf("%d", &_);while(_--) work();return 0;}


0 0
原创粉丝点击