[kuangbin带你飞]专题六 最小生成树
首先介绍一下最小生成树的基本知识吧。
最小生成树(Minimum Spanning Tree,MST):或者称为最小代价树Minimum-cost Spanning Tree:对无向连通图的生成树,各边的权值总和称为生成树的权,权最小的生成树称为最小生成树。
构成生成树的准则有三条:
<1> 必须只使用该网络中的边来构造最小生成树。
<2> 必须使用且仅使用n-1条边来连接网络中的n个顶点
<3> 不能使用产生回路的边。
构造最小生成树的算法主要有:克鲁斯卡尔(Kruskal)算法和普利姆(Prim)算法他们都遵循以上准则。
由于Kruskal算法的易编写且效率很高,我暂时就介绍该算法的情况,基本上大部分的题都能用该算法,但是有时候稠密图用用到Prim算法。
Kruskal算法主要是利用并查集的思想来实现,并查集的内容可以参加我过几天更新的博客。
它是以边为主导地位,始终选择当前可用(所选的边不能构成回路)的最小权植边。所以Kruskal算法的第一步是给所有的边按照从小到大的顺序排序。这一步可以直接使用库函数qsort或者sort。
接下来从小到大依次考察每一条边(u,v)。每次添加选择一条具有最小权植的边时,若该边的两个顶点落在不同的连通分量上,则将此边加入到T中(并查集思想);
否则,即这条边的两个顶点落到同一连通分量上,则将此边舍去(此后永不选用这条边),重新选择一条权植最小的边。一直重复下去知道所有的顶点在同一连通分量上面。
口说无凭,我们直接看代码吧。
A – Jungle Roads POJ – 1251
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
Output
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
题意:给你一个图,里面有很多的路,要你将这个图变成一棵树,要求树要是所有边的权值加起来最小,也就是最小生成树。既然是树,那么就不可能存在环,所以在生成树的是有有两个注意点,无环且最小。
也就是Kruskal模板题。看一下理解一下。其他类型的题只解释模板意外的代码。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=100;
int n;
int fa[maxn];
struct Node
{
int from,to;
int value;
}node[maxn*maxn];//边的数量最大为点的数量乘点的数量,一定不能开小了。
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
void init()
{
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findd(int x)
{
if(x==fa[x])
return fa[x];
else
return fa[x]=findd(fa[x]);
}
bool join(int x,int y)
{
int fx=findd(x);int fy=findd(y);//找出当前两条两个端点所在集合的编号
if(fx!=fy)
{
fa[fx]=fy;
return true;
}
else
return false;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
if(n==0)
break;
init();//初始化并查集
char c,c1;
int cnt,val;
int num=0;
for(int i=1;i<n;i++)
{
cin>>c>>cnt;
while(cnt--)
{
cin>>c1>>val;
node[num].from=c-'A';
node[num].to=c1-'A';
node[num++].value=val;
}
}
int ans=0;
cnt=0;
sort(node,node+num,cmp);//按边的权值排序,每次选权值最小的边
for(int i=0;i<num;i++)
{
if(join(node[i].from,node[i].to))//看能不能加入到同一个连通分量,如果能加上连通所耗费的价值。
{
ans+=node[i].value;
cnt++;
}
if(cnt==n-1)//如果n的点都加到该连通分量当中,就跳出。那为什么是n-1因为我们以边为主导,因为n-1条边就有n个点
break;
}
printf("%d\n",ans);
}
return 0;
}
B – Networking POJ – 1287
Your task is to design the network for the area, so that there is a connection (direct or indirect) between every two points (i.e., all the points are interconnected, but not necessarily by a direct cable), and that the total length of the used cable is minimal.
Input
The maximal number of points is 50. The maximal length of a given route is 100. The number of possible routes is unlimited. The nodes are identified with integers between 1 and P (inclusive). The routes between two points i and j may be given as i j or as j i.
Output
Sample Input
1 0
2 3
1 2 37
2 1 17
1 2 68
3 7
1 2 19
2 3 11
3 1 7
1 3 5
2 3 89
3 1 91
1 2 32
5 7
1 2 5
2 3 7
2 4 8
4 5 11
3 5 10
1 5 6
4 2 12
0
Sample Output
0 17 16 26
题意:Kruskal模板题。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=100;
int n,m;
int fa[maxn];
struct Node
{
int from,to;
int value;
}node[maxn*maxn];
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
void init()
{
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findd(int x)
{
if(x==fa[x])
return fa[x];
else
return fa[x]=findd(fa[x]);
}
bool join(int x,int y)
{
int fx=findd(x);int fy=findd(y);
if(fx!=fy)
{
fa[fx]=fy;
return true;
}
else
return false;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
if(n==0)
break;
scanf("%d",&m);
init();
for(int i=0;i<m;i++)
scanf("%d %d %d",&node[i].from,&node[i].to,&node[i].value);
int ans=0,cnt=0;
sort(node,node+m,cmp);
for(int i=0;i<m;i++)
{
if(join(node[i].from,node[i].to))
{
ans+=node[i].value;
cnt++;
}
if(cnt==n-1)
break;
}
printf("%d\n",ans);
}
return 0;
}
C – Building a Space Station POJ – 2031
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor’, or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells’ surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
n
x1 y1 z1 r1
x2 y2 z2 r2
…
xn yn zn rn
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Sample Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Sample Output
20.000 0.000 73.834
题意:给出三维坐标系上的一些球的球心坐标和其半径,搭建通路,使得他们能够相互连通。如果两个球有重叠的部分则算为已连通,无需再搭桥。求搭建通路的最小费用。也就是最小生成树。
但是要你自己确计算每个球之间的距离,也就是自己确定边权。
就是注意若边权<=0,说明两球接触,即已连通,此时边权为0。其他的没啥区别了
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=105;
int n,m,num;
int fa[maxn];
double x[maxn],y[maxn],z[maxn],r[maxn];
struct Node
{
int from,to;
double value;
}node[maxn*maxn];
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
void init()
{
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findd(int x)
{
if(x==fa[x])
return fa[x];
else
return fa[x]=findd(fa[x]);
}
bool join(int x,int y)
{
int fx=findd(x);int fy=findd(y);
if(fx!=fy)
{
fa[fx]=fy;
return true;
}
else
return false;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
init();
if(n==0)
break;
for(int i=1;i<=n;i++)
scanf("%lf %lf %lf %lf",&x[i],&y[i],&z[i],&r[i]);
num=0;//记录边数。
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==j)
continue;
else
{
double temp=sqrt((x[j]-x[i])*(x[j]-x[i])+(y[j]-y[i])*(y[j]-y[i])+(z[j]-z[i])*(z[j]-z[i]))-r[j]-r[i];//判断是否满足两个球接触
if(temp<0)
temp=0;
node[num].from=i;node[num].to=j;node[num++].value=temp;
}
}
}
double ans=0;
int cnt=0;
sort(node,node+num,cmp);
for(int i=0;i<num;i++)
{
if(join(node[i].from,node[i].to))
{
ans+=node[i].value;
cnt++;
}
if(cnt==n-1)
break;
}
printf("%.3f\n",ans);
}
return 0;
}
D – Constructing Roads POJ – 2421
We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
Input
Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
Output
Sample Input
3
0 990 692
990 0 179
692 179 0
1
1 2
Sample Output
179
题意:还是给你n个点,然后求最小生成树。特殊之处在于有一些点之间已经连上了边。
有两种做法,第一种就是对于已经有边的点,特殊标记一下,加边的时候把这些边的权值赋值为0即可。这样就可以既保证这些边一定存在,又保证了所求的结果正确。
第二种做法,就是在进行Kruskal之前我们就把这些边进行并查集操作合到一个联通分量中,然后再进行Kruskal算法。
我选择了第二种做法。有一个类似的题可以参见UVA1151:这题会比这个复杂一些,但是道理是一样的。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=100;
int n,m;
int fa[maxn];
int ma[maxn][maxn];
struct Node
{
int from,to;
int value;
}node[maxn*maxn];
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
void init()
{
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findd(int x)
{
if(x==fa[x])
return fa[x];
else
return fa[x]=findd(fa[x]);
}
bool join(int x,int y)
{
int fx=findd(x);int fy=findd(y);
if(fx!=fy)
{
fa[fx]=fy;
return true;
}
else
return false;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
init();
int num=0;
int a,b;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&a);
if(i==j)
continue;
else
node[num].from=i;node[num].to=j;node[num++].value=a;
}
}
scanf("%d",&m);
while(m--)
{
scanf("%d %d",&a,&b);
int ffa=findd(a);
int ffb=findd(b);
if(ffa!=ffb)
fa[ffa]=ffb;
}
int ans=0,cnt=0;
sort(node,node+num,cmp);
for(int i=0;i<num;i++)
{
if(join(node[i].from,node[i].to))
{
ans+=node[i].value;
cnt++;
}
if(cnt==n-1)
break;
}
printf("%d\n",ans);
}
return 0;
}
E – QS Network ZOJ – 1586
Sunny Cup 2003 – Preliminary Round
April 20th, 12:00 – 17:00
Problem E: QS Network
In the planet w-503 of galaxy cgb, there is a kind of intelligent creature named QS. QScommunicate with each other via networks. If two QS want to get connected, they need to buy two network adapters (one for each QS) and a segment of network cable. Please be advised that ONE NETWORK ADAPTER CAN ONLY BE USED IN A SINGLE CONNECTION.(ie. if a QS want to setup four connections, it needs to buy four adapters). In the procedure of communication, a QS broadcasts its message to all the QS it is connected with, the group of QS who receive the message broadcast the message to all the QS they connected with, the procedure repeats until all the QS’s have received the message.
A sample is shown below:
A sample QS network, and QS A want to send a message.
Step 1. QS A sends message to QS B and QS C;
Step 2. QS B sends message to QS A ; QS C sends message to QS A and QS D;
Step 3. the procedure terminates because all the QS received the message.
Each QS has its favorate brand of network adapters and always buys the brand in all of its connections. Also the distance between QS vary. Given the price of each QS’s favorate brand of network adapters and the price of cable between each pair of QS, your task is to write a program to determine the minimum cost to setup a QS network.
Input
The 1st line of the input contains an integer t which indicates the number of data sets.
From the second line there are t data sets.
In a single data set,the 1st line contains an interger n which indicates the number of QS.
The 2nd line contains n integers, indicating the price of each QS’s favorate network adapter.
In the 3rd line to the n+2th line contain a matrix indicating the price of cable between ecah pair of QS.
Constrains:
all the integers in the input are non-negative and not more than 1000.
Output
for each data set,output the minimum cost in a line. NO extra empty lines needed.
Sample Input
1
3
10 20 30
0 100 200
100 0 300
200 300 0
Sample Output
370
题意:这题可能就在题意的理解上有点困难,看懂了就知道做了。
在某个外星球有些叫QS的外星人。他们之间要相互联系。但是要买网络适配器,当然不同的QS喜欢不同价格的适配器。而且还需要买网络电缆,而且都需要费用。
让你求用最小的花费去建立他们之间的联系。就是你在连接两个人的时候除了考虑边权还要考虑点权,也就是在每条边的权值上加上两个适配器的价格就可以了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=1005;
int T,n,m,temp;
int fa[maxn],x[maxn];
struct Node
{
int from,to;
int value;
}node[maxn*maxn];
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
void init()
{
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findd(int x)
{
if(x==fa[x])
return fa[x];
else
return fa[x]=findd(fa[x]);
}
bool join(int x,int y)
{
int fx=findd(x);int fy=findd(y);
if(fx!=fy)
{
fa[fx]=fy;
return true;
}
else
return false;
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
init();
for(int i=1;i<=n;i++)
scanf("%d",&x[i]);
int num=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&temp);
if(i==j)
continue;
else
{
node[num].from=i;
node[num].to=j;
node[num++].value=temp+x[i]+x[j];
}
}
}
int ans=0,cnt=0;
sort(node,node+num,cmp);
for(int i=0;i<num;i++)
{
if(join(node[i].from,node[i].to))
{
ans+=node[i].value;
cnt++;
}
if(cnt==n-1)
break;
}
printf("%d\n",ans);
}
return 0;
}
L – 还是畅通工程 HDU – 1233
Input测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
Output对每个测试用例,在1行里输出最小的公路总长度。
Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
Sample Output
3 5
题意:模板题就不说了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=105;
int n,m;
int fa[maxn];
int ma[maxn][maxn];
struct Node
{
int from,to;
int value;
}node[maxn*maxn];
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
void init()
{
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findd(int x)
{
if(x==fa[x])
return fa[x];
else
return fa[x]=findd(fa[x]);
}
bool join(int x,int y)
{
int fx=findd(x);int fy=findd(y);
if(fx!=fy)
{
fa[fx]=fy;
return true;
}
else
return false;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
init();
if(n==0)
break;
int num=n*(n-1)/2;
for(int i=0;i<num;i++)
scanf("%d %d %d",&node[i].from,&node[i].to,&node[i].value);
int ans=0,cnt=0;
sort(node,node+num,cmp);
for(int i=0;i<num;i++)
{
if(join(node[i].from,node[i].to))
{
ans+=node[i].value;
cnt++;
}
if(cnt==n-1)
break;
}
printf("%d\n",ans);
}
return 0;
}
M题和第一题一样,详见第一题的解释。
N – 畅通工程再续 HDU – 1875
Input输入包括多组数据。输入首先包括一个整数T(T <= 200),代表有T组数据。
每组数据首先是一个整数C(C <= 100),代表小岛的个数,接下来是C组坐标,代表每个小岛的坐标,这些坐标都是 0 <= x, y <= 1000的整数。
Output每组输入数据输出一行,代表建桥的最小花费,结果保留一位小数。如果无法实现工程以达到全部畅通,输出”oh!”.Sample Input
2
2
10 10
20 20
3
1 1
2 2
1000 1000
Sample Output
1414.2 oh!
题意:这题和C题一样,就是考虑什么时候加边,不过那题每次都会加边,但是这题要满足题意才加,最后还要考虑是否包含了所有的点。就是跑完了Kruskal算法不一定所有的点都跑到了,给个cnt==n-1;break;只是降低时间复杂度,
保证一旦找到了就直接跳出来,在不一定保证一定有最小生成树的情况下要在最后加一个判断的。!!!注意一下。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=105;
int T,n,m;
int fa[maxn];
int x[maxn],y[maxn];
struct Node
{
int from,to;
double value;
}node[maxn*maxn];
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
void init()
{
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findd(int x)
{
if(x==fa[x])
return fa[x];
else
return fa[x]=findd(fa[x]);
}
bool join(int x,int y)
{
int fx=findd(x);int fy=findd(y);
if(fx!=fy)
{
fa[fx]=fy;
return true;
}
else
return false;
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
init();
for(int i=1;i<=n;i++)
scanf("%d %d",&x[i],&y[i]);
int num=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==j)
continue;
else
{
int temp=(x[j]-x[i])*(x[j]-x[i])+(y[j]-y[i])*(y[j]-y[i]);
if(temp>=100&&temp<=1000000)
{
node[num].from=i;node[num].to=j;node[num++].value=sqrt(temp);
}
}
}
}
double ans=0;
int cnt=0;
sort(node,node+num,cmp);
for(int i=0;i<num;i++)
{
if(join(node[i].from,node[i].to))
{
ans+=node[i].value;
cnt++;
}
if(cnt==n-1)
break;
}
if(cnt!=n-1)
printf("oh!\n");
else
printf("%.1f\n",ans*100);
}
return 0;
}