您的位置:首页 > 其它

最小生成树

2015-08-11 21:37 134 查看
--------如何求最小生成树?A)Prim算法(从点入手)B)Kruskal算法(从边入手)-------Kruskal算法步骤:一、把原始图的N个节点看成N个独立子图;二、每次选取当前最短的边(将权值进行排序可得),看两端是否属于不同的子图;若是,加入;否则,放弃;三、循环操作该步骤二,直到有N-1条边;例题:poj--1258DescriptionThe 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 tooexpensive 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 thevillages 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.InputThe 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, andthe 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 villagelabel 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 roadfollowed 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 networkwill 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.OutputThe 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 everypossible set of roads will not finish within the one minute time limit.Sample Input
9
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
3
A 2 B 10 C 40
B 1 C 20
0
Sample Output
216
30
#include<cstdio>
#include<algorithm>
using namespace std;
struct stu
{
int s;
int e;
int w;
}vt[80];
int per[30];
void chu()
{
int i;
for(i=0;i<=27;i++)
{
per[i]=i;
}
}
int cmp(stu a,stu b)
{
return a.w<b.w;
}
int find(int x)
{
int r;
r=x;
while(r!=per[r])
{
r=per[r];
}
per[x]=r;
return r;
}
bool join(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
per[fx]=fy;
return true;
}
else return false;
}
int main()
{
char c1[3],c2[3];
int m1,m2,t,k,sum,j,i;
while(scanf("%d",&t)&&t)
{
k=0;sum=0;
chu();
for(j=1;j<=t-1;j++)
{

scanf("%s%d",c1,&m1);
for(i=0;i<m1;i++)
{
scanf("%s%d",c2,&m2);
vt[k].s=c1[0]-'A';
vt[k].e=c2[0]-'A';
vt[k].w=m2;
k++;
}
}
sort(vt,vt+k,cmp);
for(i=0;i<k;i++)
{
if(join(vt[i].s,vt[i].e))
sum+=vt[i].w;
}
printf("%d\n",sum);
}
return 0;
}
Prim算法步骤:步骤一:树T初始状态为空;步骤二:从图中任意选取一个点加入T;步骤三:从图中找出能与T形成树的所有边,将代价最小的边加入T,形成新的树T;步骤四:检查T中边的条数;步骤五:如果条数小于n-1,返回步骤三,否则程序结束,T为最小代价生成树。例题:poj--1789Truck HistoryTime Limit: 2000MS Memory Limit: 65536KTotal Submissions: 21586 Accepted: 8391DescriptionAdvanced Cargo Movement, Ltd. uses trucks of different types. Some trucks are used for vegetable delivery, other for furniture, or for bricks. The company has its own code describing each type of a truck. The code is simply a string of exactly seven lowercaseletters (each letter on each position has a very special meaning but that is unimportant for this task). At the beginning of company's history, just a single truck type was used but later other types were derived from it, then from the new types another typeswere derived, and so on.Today, ACM is rich enough to pay historians to study its history. One thing historians tried to find out is so called derivation plan -- i.e. how the truck types were derived. They defined the distance of truck types as the number of positions with differentletters in truck type codes. They also assumed that each truck type was derived from exactly one other truck type (except for the first truck type which was not derived from any other type). The quality of a derivation plan was then defined as1/Σ(to,td)d(to,td)where the sum goes over all pairs of types in the derivation plan such that to is the original type and td the type derived from it and d(to,td) is the distance of the types.Since historians failed, you are to write a program to help them. Given the codes of truck types, your program should find the highest possible quality of a derivation plan.InputThe input consists of several test cases. Each test case begins with a line containing the number of truck types, N, 2 <= N <= 2 000. Each of the following N lines of input contains one truck type code (a string of seven lowercase letters). You may assume thatthe codes uniquely describe the trucks, i.e., no two of these N lines are the same. The input is terminated with zero at the place of number of truck types.OutputFor each test case, your program should output the text "The highest possible quality is 1/Q.", where 1/Q is the quality of the best derivation plan.Sample Input4aaaaaaabaaaaaaabaaaaaaabaaaa0Sample OutputThe highest possible quality is 1/3.代码如下:
#include<stdio.h>
#include<string.h>
#define M 0xfffffff
int n;
char a[2010][10];
int mark[2010][2010];
int lowcost[2010];
int vist[2010];
int prim()
{
int i,j,temp,k,sum;
vist[1]=true;sum=0;
for(i=1;i<=n;i++)
lowcost[i]=mark[1][i];
for(i=1;i<=n;i++)
{
temp=M;
for(j=1;j<=n;j++)
{
if(!vist[j]&&temp>lowcost[j])
{
k=j;
temp=lowcost[j];
}
}
if(temp==M)break;
vist[k]=1;
sum+=lowcost[k];
for(j=1;j<=n;j++)
{
if(!vist[j]&&lowcost[j]>mark[k][j])
lowcost[j]=mark[k][j];
}
}
return sum;
}
int main()
{
int i,j,k,count,toal;
while(scanf("%d",&n)&&n)
{
for(i=1;i<=n;i++)
scanf("%s",a[i]);
memset(mark,0,sizeof(mark));
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
{
count=0;
for(k=0;k<7;k++)
{
if(a[i][k]!=a[j][k])
count++;
}
mark[i][j]=count;
mark[j][i]=count;
}
memset(vist,0,sizeof(vist));
toal=prim();
printf("The highest possible quality is 1/%d.\n",toal);
}
return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: