標籤:acm poj 最小產生樹
Agri-Net
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 39499 |
|
Accepted: 16017 |
Description
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
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
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
40 4 9 214 0 8 179 8 0 1621 17 16 0
Sample Output
28
Source
USACO 102
最小產生樹的入門題;水題一道;協助理解一下prim演算法;prim演算法剛開始看的時候,沒有怎麼搞懂,最近又回過頭來看最小產生樹這一塊,感覺對prim演算法的理解就更深刻了;最小產生樹是包含n個點的n-1條邊的權值最小的一個子圖;prim演算法是從一個點開始,尋找與它相連的權值最小的一個點,然後把這個點也加入進來,比較這與這兩個點相連的權值最小的點,更新之間的權值,後面的點以此類推;用點來尋找邊;直到包含有n個點。下面是代碼;用一個二維數組map儲存圖結構,用low數組記錄兩點之間的權值,用visit數組標誌這個店是否訪問;
#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;}