Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 29613 | Accepted: 11750 |
Description
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
題意:
給你N*N矩陣,表示N個村莊之間的距離。FJ要把N個村莊全都連接起來,求連接的最短距離。(即傳說中的最小生成樹)
樣例分析:
連接方式:1-----------2-----------3----------4
距離: 4 + 8 + 16 = 24
算法:
圖論之最小生成樹問題。。。下面的是Prime算法複雜度O(n*n)
最小生成樹算法思想:
假設N=(V,E) 是連通網,TE是N上最小生成樹中邊的集合,算法從U={vk},TE={ }開始(即從vk出發求最小生成樹,vk∈V)。
重複執行下述操作:
在所有的邊(vi,vj)∈E (vi∈U,vj∈V-U)中尋找一條權值最小的邊(vi,vj)將其添加到TE中(或打印之),同時把vj添 加到集合U 中 。
反覆執行上述操作n-1次(或所有頂點全部加入U時爲止)。
通俗的說:1、有一個圖N=(V,E),設置一個空集合U,設置路長ans=0。
2、就是先找一個點v1,將v1添加到集合U,再找出和它距離最近的點v2,再把v2添加到集合U,ans加上兩點間的距離。
3、再到點集合V-U (屬於V,但是不屬於U的點)中找出一個離集合U最近的點。將找到的點添加到集合U,ans加上這個最短的距離。
4、如此循環第三步,直到所有的點全到U中。
#include <cstdio>
#include <cstring>
const int Max=0x3f3f3f3f;
const int maxn=100+10;
int map[maxn][maxn],low[maxn],visit[maxn];
int n;
int prim()
{
int pos,i,j,min,sum=0;
memset(visit,0,sizeof(visit));//初始化visit數組
visit[1]=1; //從第一個點開始
pos=1; //標記和記錄這個點
for(i=1;i<=n;i++)
low[i]=map[pos][i]; //用low數組記錄權值
for(i=1;i<n;i++) //第一個點已經進行了,還需要進行n-1次;
{
min=Max; //把min賦初值
for(j=1;j<=n;j++)
{
if(visit[j]==0 && low[j]!=0 && low[j]<min) //比較權值的大小
{
min=low[j];
pos=j; //記錄權值最小的點,下一次從這個點開始
}
}
sum+=min; //記錄權值的和
visit[pos]=1; //標記訪問
for(j=1;j<=n;j++) //訪問下一個點
{
if(visit[j]==0 && low[j]>map[pos][j])
low[j]=map[pos][j];
}
}
return sum;
}
int main()
{
int sum,i,j;
while(scanf("%d",&n)!=EOF)
{
sum=0;
memset(map,Max,sizeof(map));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&map[i][j]);
sum=prim();
printf("%d\n",sum);
}
return 0;
}