最小生成树--poj1251

来源:互联网 发布:java 产生随机数 编辑:程序博客网 时间:2024/04/28 15:15
Jungle Roads
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 17473 Accepted: 7885

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

The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, capitalized. Each data set is completed with n-1 lines that start with village labels in alphabetical order. There is no line for the last village. Each line for a village starts with the village label followed by a number, k, of roads from this village to villages with labels later in the alphabet. If k is greater than 0, the line continues with data for each of the k roads. The data for each road is the village label for the other end of the road followed by the monthly maintenance cost in aacms for the road. Maintenance costs will be positive integers less than 100. All data fields in the row are separated by single blanks. The road network will always allow travel between all the villages. The network will never have more than 75 roads. No village will have more than 15 roads going to other villages (before or after in the alphabet). In the sample input below, the first data set goes with the map above. 

Output

The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages. Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit. 

Sample Input

9A 2 B 12 I 25B 3 C 10 H 40 I 8C 2 D 18 G 55D 1 E 44E 2 F 60 G 38F 0G 1 H 35H 1 I 353A 2 B 10 C 40B 1 C 200

Sample Output

21630

应该也算是比较简单的最小生成树吧,本来想用prim算法,但没想出来,所以就用了Kruskal。

题意:求维护道路花的最小费用,要求所有村庄联通。

思路:输入后,从1到100枚举道路长度,并判断两个村庄是否在一个集合里,如不是则答案要加上距离,并把它们设为一个集合。

kruskal算法代码如下:

#include<iostream>#include<cstring>#include<cstdio>using namespace std;int map[30][30];int fa[30];int set_find(int p){    if(fa[p]==p)        return p;    return fa[p]=set_find(fa[p]);}int main(){    //freopen("in.txt","r",stdin);    int n,m;    char x,y;    int dist;    while(cin>>n,n)    {        memset(map,0,sizeof(map));        for(int i=1;i<n;i++)        {            cin>>x>>m;            for(int j=1;j<=m;j++)            {                cin>>y>>dist;                map[x-'A'+1][y-'A'+1]=dist;            }        }        int ans=0;        for(int i=1;i<=n;i++)            fa[i]=i;        for(int k=1;k<=100;k++)            for(int i=1;i<27;i++)                for(int j=1;j<27;j++)                if(map[i][j]==k&&set_find(i)!=set_find(j))                {                    ans+=map[i][j];                    fa[set_find(i)]=set_find(j);                }        cout<<ans<<endl;    }    return 0;}


还有一段代码使用结构体做的,结构体中是边的两个节点和边的权值,这样直接对边的权值从小到大进行排序,然后判断节点是否在一个集合。

代码如下:

#include<iostream>#include<fstream>#include<algorithm>#include<string.h>using namespace std;int parent[26];int n;//vertex numint edge_num;struct Edge{int v1;int v2;int weight;}edges[100];int cmp(const void *edge1,const void *edge2){Edge *e1=(Edge *)edge1;Edge *e2=(Edge *)edge2;return e1->weight-e2->weight;}int find(int v){while(parent[v]>=0)v=parent[v];return v;}void Union(int r1,int r2)   {if(parent[r1]<=parent[r2]){parent[r1]+=parent[r2];parent[r2]=r1;}else{parent[r2]+=parent[r1];parent[r1]=r2;}}int main(){freopen("input.txt","r",stdin);while(scanf("%d\n",&n)!=EOF&&n!=0){edge_num=0;memset(parent,-1,sizeof(int)*n);char ch;int v1,v2;int k;for(int t=0;t<n-1;t++){scanf("%c %d",&ch,&k);v1=ch-'A';for(int i=0;i<k;i++){int w;scanf(" %c %d",&ch,&w);edges[edge_num].v1=v1;edges[edge_num].v2=ch-'A';edges[edge_num++].weight=w;}scanf("\n");}qsort(edges,edge_num,sizeof(Edge),cmp);int output=0;int count=0;for(int i=0;i<edge_num;i++){if(count==n-1) //successedbreak;int r1=find(edges[i].v1);int r2=find(edges[i].v2);if(r1==r2)continue;Union(r1,r2);output+=edges[i].weight;count++;}/*for(int i=0;i<edge_num;i++){cout<<edges[i].v1<<" "<<edges[i].v2<<" "<<edges[i].weight<<endl;}*/        printf("%d\n",output);}return 0;}

 

下面是别人写的prim算法代码:

#include<iostream>。using namespace std;const int Max = 30;const int inf = 0xfffffff;int n, ans;int map[Max][Max], dis[Max];int min(int a, int b){    return a < b ? a : b;}void prim(){    int i, j, now, min_node, min_edge;    for(i = 1; i <= n; i ++)        dis[i] = inf;    now = 1;    ans = 0;    for(i = 1; i < n; i ++){        dis[now] = -1;        min_edge = inf;        for(j = 1; j <= n; j ++)            if(now != j && dis[j] >= 0){                dis[j] = min(dis[j], map[now][j]);                if(dis[j] < min_edge){                    min_edge = dis[j];                    min_node = j;                }            }now = min_node;ans += min_edge;    }}int main(){    int i, j, num, edge;    char u, v;    while(scanf("%d", &n) && n != 0){        for(i = 1; i <= n; i ++)            for(j = 1; j <= n; j ++)                map[i][j] = inf;for(i = 1; i < n; i ++){scanf(" %c%d", &u, &num);   // 这里或用cin,代替scanf("%c %d", &u, &num); getchar()。while(num --){scanf(" %c%d", &v, &edge);   //  同上。map[u-'A'+1][v-'A'+1] = edge;map[v-'A'+1][u-'A'+1] = edge;}}prim();printf("%d\n", ans);    }    return 0;}

一题多解,有助于理解!