1. 程式人生 > >最小生成樹基礎模板題(USACO Training Section 3.1 最短網絡 Agri-Net)

最小生成樹基礎模板題(USACO Training Section 3.1 最短網絡 Agri-Net)

格式 聯網 std fin sync 輸出格式 class cti ons

農民約翰被選為他們鎮的鎮長!他其中一個競選承諾就是在鎮上建立起互聯網,並連接到所有的農場。當然,他需要你的幫助。

約翰已經給他的農場安排了一條高速的網絡線路,他想把這條線路共享給其他農場。為了用最小的消費,他想鋪設最短的光纖去連接所有的農場。

你將得到一份各農場之間連接費用的列表,你必須找出能連接所有農場並所用光纖最短的方案。每兩個農場間的距離不會超過100000

輸入格式:

第一行: 農場的個數,N(3<=N<=100)。

第二行..結尾: 後來的行包含了一個N*N的矩陣,表示每個農場之間的距離。理論上,他們是N行,每行由N個用空格分隔的數組成,實際上,他們限制在80個字符,因此,某些行會緊接著另一些行。當然,對角線將會是0,因為不會有線路從第i個農場到它本身。

輸出格式:

只有一個輸出,其中包含連接到每個農場的光纖的最小長度。

輸入樣例#1:
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
輸出樣例#1:
28
與繁忙的都市類似,模板題。
#include<bits/stdc++.h>
#define LL long long
const int inf=20000000;
using namespace std;
LL n,m;
struct Edge{LL from,to,w;};
struct Edge e[300000];
LL f[300000];
 
LL ans=0;
 
bool cmp(const Edge &a,const Edge &b)
{
   return a.w<b.w;
}
 
LL Find(LL  x) {return f[x]==x?x:f[x]=Find(f[x]);}
 
LL merge(LL x,LL y)
{
  LL fx=Find(x),fy=Find(y);
  if(f[fx]!=fy)
  {
     f[fx]=fy;
    return 1;
  }
    return 0;
}
 
 
int main()
 
{   ios::sync_with_stdio(false);
    LL Count=0;
 
    cin>>n;
    LL x;
    for(LL i=1;i<=n*n;i++)
    {
      cin>>x;
      if(x!=0)
        {e[i].from=(i-1)/n+1;e[i].to=(i-1)%n+1;e[i].w=x;}
      else
        e[i].w=inf;
    }

    for(LL i=1;i<=n;i++)
      f[i]=i;
      sort(e+1,e+n*n+1,cmp);

    for(LL i=1;i<=n*n;i++)
    {
       if(merge(e[i].from,e[i].to))
       {
            ans+=e[i].w;
            Count++;

       }
       if(Count==n-1)
         break;
    }
    cout<<ans<<endl;
    return 0;
}

  

最小生成樹基礎模板題(USACO Training Section 3.1 最短網絡 Agri-Net)