您的位置:首页 > 其它

【kruscal】【最小生成树】【并查集扩展】bzoj3714 [PA2014]Kuglarz

2014-10-31 10:53 357 查看
ORZ:http://www.cnblogs.com/zrts/p/bzoj3714.html

#include<cstdio>
#include<algorithm>
using namespace std;
#define N 2010
int fa
,rank
,n,m,tot;
long long ans;
struct Edge{int u,v,w;}edges[(N*N)>>1];
bool operator < (const Edge &a,const Edge &b){return a.w<b.w;}
void init(){for(int i=1;i<=n;i++)fa[i]=i;}
int Res;char C;
inline int R()
{
Res=0;C='*';
while(C<'0'||C>'9')C=getchar();
while(C>='0'&&C<='9'){Res=Res*10+(C-'0');C=getchar();}
return Res;
}
int findroot(int x)
{
if(x==fa[x]) return x;
int rt=findroot(fa[x]);
fa[x]=rt;
return rt;
}
inline void Union(const int &U,const int &V)
{
if(rank[U]<rank[V]) fa[U]=V;
else
{
fa[V]=U;
if(rank[U]==rank[V]) rank[U]++;
}
}
int main()
{
n=R(); init();
for(int i=1;i<=n;i++)
for(int j=i;j<=n;j++)
edges[++m]=(Edge){i-1,j,R()};
sort(edges+1,edges+m+1);
for(int i=1;i<=m;i++)
{
int f1=findroot(edges[i].u),f2=findroot(edges[i].v);
if(f1!=f2)
{
Union(f1,f2);
ans+=(long long)edges[i].w;
tot++;
if(tot==n) break;
}
}
printf("%lld\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: