poj1258-アグリのNet-最小スパニングツリー

それはまばらなグラフが、次のクラスカルを書くのが習慣...書き込みプリム(ではないので、プリム使用する必要がありますか?

快適に水問題の話を書く......ちょっと書くのを忘れたときに道路= n-1のとき、後ろにブレーク(彼

#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 10005
int fa[maxn];
typedef struct node
{
 int x;
 int y;
 int c;
}node;
node nod[maxn];
int comp(node a,node b){return a.c<b.c;}
void init(int n)
{
 for(int i=1;i<=n;i++)
  fa[i]=i;
}
int find(int x)
{
 if(fa[x]==x)
  return x;
 else return fa[x]=find(fa[x]);
}
void uni(int x,int y)
{
 int ffx=find(x);
 int ffy=find(y);
 fa[ffx]=ffy;
}
int main()
{
 int n;
 while(cin>>n)
 {
 int temp;
 int index=0;
 for(int i=1;i<=n;i++)
 {
  for(int j=1;j<=n;j++)
  {
   cin>>temp;
   if(i<j)
   {
   nod[index].c=temp;
   nod[index].x=i;
   nod[index].y=j;
   index++;
   }
  }
 }
 init(n);
 int ans=0;
 int cnt=0;
 sort(nod,nod+index,comp);
 for(int i=0;i<index;i++)
 {
  if(find(nod[i].x)!=find(nod[i].y))
  {
   uni(nod[i].x,nod[i].y);
   ans+=nod[i].c;
   cnt++;
   if(cnt==n-1) break;
  }
 }
 cout<<ans<<endl;
 }
}
公開された16元の記事 ウォンの賞賛1 ビュー260

おすすめ

転載: blog.csdn.net/weixin_44254608/article/details/104776307