bzoj 1232: [Usaco2008Nov] comfort cow cheer [minimum spanning tree]

Interesting
Each edge is doubled the edge weight plus the weight of the two endpoints when calculating the answer, and then the sleep point is added once,
so you can use this weight as MST, and then add the point with the smallest point weight.

#include<iostream>
#include<cstdio> 
#include<algorithm>
using namespace std;
const int N=100005;
int n,m,a[N],f[N],ans=1e9,con;
struct qwe
{
    int u,v,w;
}e[N];
bool cmp(const qwe &a,const qwe &b)
{
    return a.w<b.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 x==f[x]?x:f[x]=zhao(f[x]);
}
int main()
{
    n=read(),m=read();
    for(int i=1;i<=n;i++)
    {
       a[i]=read();
       ans=min(ans,a[i]);
       f[i]=i;
   }
    for(int i=1;i<=m;i++)
    {
        int x=read(),y=read(),z=read()*2+a[x]+a[y];
        e[i]=(qwe){x,y,z};
    }
    sort(e+1,e+m+1,cmp);
    for(int i=1;i<=m&&con<n-1;i++)
    {
        int fu=zhao(e[i].u),fv=zhao(e[i].v);
        if(fu!=fv)
        {
            f[fu]=fv;
            con++;
            ans+=e[i].w;
        }
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324949394&siteId=291194637