0)
题意:已经在部分城市之间建造了道路,求再花费多少钱建造道路使得所有城市连通。
求连接所有点的最小花费,这是最小生成路问题,变形在于已经修建好了部分道路。之前的思路是,在所有未连接的点图中,如何构建出所有需要的道路,而在构建之前如何将已经修好的路放进去,事实上这样的思想不明确也不简洁。好的做法是将修好的道路的修建花费直接赋值为0。然后就可以直接上最小生成树的模板,Prim或者Kruskal都可以。这么来看的话,这个题也是比较裸的。
(Prim从点出发更适合稠密图,Kruskal从边出发更适合稀疏图)
1)
Prim
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
int mat[110][110];
int visted[110];
int dis[110];
int n;
int sum;
void Prim(){
///ini:
int cur=1;
visted[cur]=1;
for(int i=1;i<=n;i++){
dis[i]=mat[cur][i];
}
///松弛
int minn;
for(int i=1;i<=n;i++){
///寻找目前离集合最近的点
minn=INF;
for(int j=1;j<=n;j++){
if(visted[j]==1) continue;
if(minn>dis[j]){
minn=dis[j];
cur=j;
}
}
///加入该点并更新集合到其他未加入集合的所有点的距离
if(minn==INF) return ;
visted[cur]=1;
sum+=minn;
for(int j=1;j<=n;j++){
if(visted[j]==1) continue;
if(dis[j]>mat[cur][j]) dis[j]=mat[cur][j];
}
}
}
int main(){
while(~scanf("%d",&n)){
sum=0;
memset(visted,0,sizeof(visted));
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&mat[i][j]);
}
}
int num,a,b;
scanf("%d",&num);
while(num--){
scanf("%d%d",&a,&b);
mat[a][b]=0;
mat[b][a]=0;
}
Prim();
cout<<sum<<endl;
}
}
Kruskal
......
2)
Description
There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.
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.
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
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.
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.
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
You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.
Sample Input
3 0 990 692 990 0 179 692 179 0 1 1 2
Sample Output
179