【codevs】2627 村村通 kruskal

鏈接

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

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

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

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

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

樣例輸入 Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

樣例輸出 Sample Output
28

數據範圍及提示 Data Size & Hint
暫時無範圍。

最小生成樹裸題,我居然用鄰接表存的圖…
同樣存個模板

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX_V=15000+50,MAX_E=30000+50;
struct edge{
    int from,to,cost;
}es[MAX_E<<1];
int first[MAX_V],next[MAX_E<<1],tot,fa[MAX_V],ans=0,m,n;
void init()
{
    memset(first,-1,sizeof(first));
    tot=0;
}
void build(int ff,int tt,int dd)
{
    es[++tot]=(edge){ff,tt,dd};
    next[tot]=first[ff];
    first[ff]=tot;
}
bool cmp(edge a,edge b)
{
    return a.cost<b.cost;
}
int find(int x)
{
    if(fa[x]==x)
        return x;
    else return fa[x]=find(fa[x]);
}
void kruskal()
{
    for(int i=1;i<=n;i++)
        fa[i]=i,
    sort(es+1,es+tot+1,cmp);
    for(int i=1;i<=tot;i++)
    {
        int fx=find(es[i].from);
        int fy=find(es[i].to);
        int value=es[i].cost;
        if(fx!=fy)
        {
            fa[fx]=fy;
            ans+=value;
        }
    }
}
int main()
{
    int dd;
    scanf("%d",&n);
    init();
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            scanf("%d",&dd);
            build(i,j,dd);
        }
    }
    kruskal();
    cout<<ans<<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章