bzoj 1601: [Usaco2008 Oct]灌水【最小生成树】

挺有意思的思路
如果不能自己打井,那么就是MST裸题了,考虑转换一下,自己打井就相当于连接一口虚拟的井(地下水?),所有井i到这口井的距离是w[i],这样把所有边排个序跑MST即可

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=305;
int n,a[N][N],cnt,f[N],con,ans;
struct qwe
{
    int u,v,w;
}e[N*N];
bool cmp(const qwe &x,const qwe &y)
{
    return x.w<y.w;
}
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
int zhao(int x)
{
    return f[x]==x?x:f[x]=zhao(f[x]);
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
        a[i][n+1]=a[n+1][i]=read(),f[i]=i;
    a[n+1][n+1]=1e9;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            a[i][j]=read();
    for(int i=1;i<=n+1;i++)
        for(int j=1;j<i;j++)
            e[++cnt]=(qwe){i,j,a[i][j]};
    sort(e+1,e+1+cnt,cmp);
    for(int i=1;i<=cnt&&con<n;i++)
    {
        int fx=zhao(e[i].u),fy=zhao(e[i].v);
        if(fx!=fy)
        {
            f[fx]=fy;
            con++;
            ans+=e[i].w;
        }
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/8933792.html
今日推荐