BZOJ 1626: [Usaco2007 Dec]Building Roads 修建道路

最小生成树,原来有的几条路先预处理加上

#include
#include
#include
#include
#define g getchar()
#define ll long long
#define inf 0x3f3f3f3f
#define rep(i,n) for(int i=1;i<=n;++i)
#define f2(i,j,k) for(int i=j;i<=k;++i)
using namespace std;
inline ll read(){
    ll x=0,f=1;char ch=g;
    for(;ch<'0'||ch>'9';ch=g)if(ch=='-')f=-1;
    for(;ch>='0'&&ch<='9';ch=g)x=x*10+ch-'0';
    return x*f;
}
inline void out(ll x){
    int a[25],wei=0;
    if(x<0)putchar('-'),x=-x;
    for(;x;x/=10)a[++wei]=x%10;
    if(wei==0){puts("0");return;}
    for(int j=wei;j>=1;--j)putchar('0'+a[j]);
    putchar('\n');
}

struct re{long double v;int x,y;}ed[1005*1005];
int x[1005],y[1005],n,m,mm,f[1005],cnt,now;
long double ans=0;
inline bool cmp(re x,re y){return x.vint gtf(int x){return x==f[x]?x:f[x]=gtf(f[x]);}
inline long double sqr(long double x){return x*x;}
long double cal(int i,int j)
{return sqrt(sqr((long double)x[i]-(long double)x[j])+sqr((long double)y[i]-(long double)y[j]));}
int main(){
//  freopen("","r",stdin);
//  freopen("","w",stdout);
    n=read();mm=m=read();rep(i,n)f[i]=i;
    rep(i,n)x[i]=read(),y[i]=read();
    rep(i,m){int x=read(),y=read(),fx=gtf(x),fy=gtf(y);if(fx!=fy)f[fx]=fy;else --mm;}
    rep(i,n-1)f2(j,i+1,n)ed[++cnt]=(re){cal(i,j),i,j};
    sort(ed+1,ed+1+cnt,cmp);
    now=1;
    rep(i,n-1-mm){
        int fx=0,fy=0;
        for(;cnt>=now&&(fx=gtf(ed[now].x))==(fy=gtf(ed[now].y));++now);
        if(now>cnt)break;
        ans+=ed[now].v;
        f[fx]=fy;++now;
    }
    printf("%.2Lf",ans);
    return 0;
}

你可能感兴趣的:(usaco,bzoj,生成树,并查集)