Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 19843 | Accepted: 8298 |
Description
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
源代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define N 101
int n,result;
int map[N][N],dis[N],visit[N];
void prim()
{
result=0;
int i,j,flag,min;
visit[1]=1;
for (i=1;i<=n;i++)
dis[i]=map[1][i];
for (i=1;i<n;i++)
{
min=999999999;
for (j=1;j<=n;j++)
if (!visit[j] && dis[j]<min) {min=dis[j],flag=j;}
visit[flag]=1;result+=dis[flag];
for (j=1;j<=n;j++)
if (!visit[j] && map[flag][j]<dis[j]) {dis[j]=map[flag][j];}
}
}
int main()
{
int t,a,b,i,j;
cin>>n;
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
{
cin>>map[i][j];
}
}
cin>>t;
for (i=1;i<=t;i++)
{
cin>>a>>b;
map[a][b]=0;
map[b][a]=0;
}
prim();
cout<<result<<endl;
return 0;
}
本题题意:
给出所有的路径,求出连起来的花的最少的情况,输出最小值,普利姆算法,套用普利姆模板求最小生成树。第一道mst!