題目背景
農民約翰被選爲他們鎮的鎮長!他其中一個競選承諾就是在鎮上建立起互聯網,並連接到所有的農場。當然,他需要你的幫助。
題目描述
約翰已經給他的農場安排了一條高速的網絡線路,他想把這條線路共享給其他農場。爲了用最小的消費,他想鋪設最短的光纖去連接所有的農場。
你將得到一份各農場之間連接費用的列表,你必須找出能連接所有農場並所用光纖最短的方案。每兩個農場間的距離不會超過100000
輸入輸出格式
輸入格式:
第一行: 農場的個數,N(3<=N<=100)。
第二行..結尾: 後來的行包含了一個N*N的矩陣,表示每個農場之間的距離。理論上,他們是N行,每行由N個用空格分隔的數組成,實際上,他們限制在80個字符,因此,某些行會緊接着另一些行。當然,對角線將會是0,因爲不會有線路從第i個農場到它本身。
輸出格式:
只有一個輸出,其中包含連接到每個農場的光纖的最小長度。
輸入輸出樣例
輸入樣例
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
輸出樣例
28
sx模板題,最小生成樹搞一搞
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int size = 450;
int dist[size][size];
int f[size];
int find(int x)
{
if(f[x] == x)
return x;
return f[x] = find(f[x]);
}
int n;
struct dc
{
int f,t,d;
}l[size*12450];
bool cmp(dc a,dc b)
{
return a.d < b.d;
}
int tot = 0;
int main()
{
scanf("%d",&n);
for(int i = 1 ; i <= n ; f[i] = i , i ++);
for(int i = 1 ; i <= n ; i ++)
for(int j = 1 ; j <= n ; j ++)
scanf("%d",&dist[i][j]);
for(int i = 1 ; i <= n ; i ++)
{
for(int j = i + 1 ; j <= n ; j ++)
{
l[++tot].f = i;
l[tot].t = j;
l[tot].d = dist[i][j];
l[++tot].f = j;
l[tot].t = i;
l[tot].d = dist[i][j];
}
}
sort(l+1,l+tot+1,cmp);
int ans = 0;
for(int i = 1 ; i <= tot ; i ++)
{
int x = find(l[i].f);
int y = find(l[i].t);
if(x != y)
{
ans += l[i].d;
f[x] = y;
}
}
cout<<ans;
return 0;
}