题意:存在n个点,有m条边( input中读入的是 边的端点,要先转化为边的长度 ),做一个最小生成树,使得要去除的边的长度总和最小;
思路:利用并查集和求最小生成树的方法,注意这里的排序要从大到小排,这样最后建树的消耗最大,反过来去除的最小;
当然题意不是这么直白,感觉以后看到要做一个不成环的图时,要想到最小生成树;
下面是ac代码:
#include <cstdio> #include <iostream> #include <cstring> #include <string> #include <algorithm> #include <cmath> const int maxn =10007; const int mx =2e6+7; using namespace std; int n,m,fa[maxn]; struct node { int from; int to; double r; }a[mx]; struct nn{ int x,y; }p[maxn]; bool cmp(node a,node b) { return a.r>b.r; //这里的判断用大于,使得sort从大到小排列 } void init(){ for(int i=1;i<=n;i++) fa[i] = i; memset(a,0,sizeof(a)); memset(p,0,sizeof(p)); } int find(int x) { if(fa[x]==x)return x; else return fa[x] = find (fa[x]); } bool uni(int x,int y) { int px = find(x); int py = find (y); if(px==py)return false; fa[px] = py; return true; } int main(){ scanf("%d%d",&n,&m); init(); for(int i=1;i<=n;i++) { int x,y; scanf("%d%d",&x,&y); p[i].x=x; p[i].y=y; } double sum = 0,res=0; for(int i=1;i<=m;i++) { int u,v; scanf("%d%d",&u,&v); double tmp = sqrt((p[u].x-p[v].x)*(p[u].x-p[v].x)+(p[u].y-p[v].y)*(p[u].y-p[v].y)); a[i].from=u; a[i].to=v; a[i].r = tmp; sum+=tmp; } sort(a+1,a+1+m,cmp); for(int i=1;i<=m;i++) { int u = a[i].from; int v = a[i].to; if(uni(u,v))res+=a[i].r; } printf("%.3lf ",sum-res); return 0; }