Description
The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.
Input
題意很簡單,求一個最小生成樹,求出樹的最短距離和,最小生成樹有兩種算法,一種是prim算法,一種是kruskal算法,先來看prim,基本過程爲:1.將圖中n個點分爲兩個集合。2.U集合爲已經在生成樹上的頂點集。3.V集合爲尚未落在生成樹上的頂點集。4.不斷選取U中頂點與V中頂點權值最小的邊。結束。
再來看這次用到的Kruskal算法,將每條邊的權值排序,每次選擇最小的邊加入生成樹中,如果它的添加不使樹產生迴路那麼這條邊就加入生成樹中,我們將邊排序,然後根據最小的邊來不斷的構造樹,其中判斷迴路比較難,這裏使用了一種數據結構需要學習一下,並查集。能夠快速的判斷樹中是否有環,並且合併不相交的集合,代碼雖短,很實用效率也很高,這裏需要注意一下並查集的應用。
#include<algorithm>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<vector>
using namespace std;
#define INF 0x3f3f3f3f
struct node
{
int l;
int r;
int len;
bool operator <(const node &x)const
{
if(len<x.len)
return true;
else
return false;
}
}a[1000];
int F[30]; //i點的父節點
int findfa(int x) //查找最先的父節點,既是根節點
{
if(x!=F[x])
return F[x]=findfa(F[x]);
return F[x];
}
int main()
{
int n,nn,len,nown;
char s[5];
while(scanf("%d",&n)!=EOF)
{
if(n==0)
break;
for(int i=1;i<=40;i++)
F[i]=i;
node now,next;
int Len=0;
for(int i=1;i<n;i++)
{
scanf("%s%d",s,&nn);
now.l=s[0]-'A'+1;
while(nn--)
{
scanf("%s%d",s,&len);
now.r=s[0]-'A'+1;
now.len=len;
a[Len++]=now;
}
}
sort(a,a+Len);
int ans=0;
for(int i=0;i<Len;i++)
{
now=a[i];
int dx=findfa(now.l);
int dy=findfa(now.r);
if(dx!=dy) //如果dx=dy,說明有相同的一條邊的兩個端點有相同的父節點,會出現環,則不加這條邊
{
F[dx]=dy; //合併兩個子集合
ans+=now.len;
}
}
printf("%d\n",ans);
}
return 0;
}