Problem D:Connect city
Time Limit:3000MS Memory Limit:65536K
Total Submit:19 Accepted:9 Page View:241
Description
At the year of 20?? , since some strange reasons, most of the cities disappear.
Though some survived cities are still connected with others, but most of them become disconnected.
The government wants to build some roads to connect all of these cities again,
but they don’t want to take too much money.
Input
There are many test cases .
Each test case starts with three integers: N, M and K.
N (2 <= N <= 1000) stands for the number of survived cities, the cities are signed from 1 to N.
M (0 <= m <= 100000) stands for the number of roads you can choose to connect the cities,
K (0 <= K < 10) stands for the number of still connected cities.
Then follow M lines, each contains three integers A, B and C (0 <= C < 1000), means it takes C to connect A and B.
Then follow K lines, each line starts with an integer T (1 <= T <= n) stands for the number of this connected cities.
Then T integers follow stands for the id of these cities.
Output
For each case, output the least money you need to take, if it’s impossible, just output -1.
Sample Input
6 4 3
1 4 2
2 6 1
2 3 5
3 4 33
2 1 2
2 1 3
6 4 5 6 4 5 6
2 3 2
1 2 2
1 2 22
1 2 222
2 1 2
2 2 1
100 3 1
100 100 100
1 2 254
99 98 524
5 1 2 55 88 99
Sample Output
1
0
-1
最小生成树问题,用的prim算法!
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
#define inf 1000111222
#define N 1005
int map[N][N],p[N][N];
int use[N],dis[N],n,m,con[N];
void prim()
{
int i,j,start=1,min,x;
fill(dis,dis+N,inf);
memset(use,0,sizeof(use));
dis[start]=0;
int ans=0;
for(i=1;i<=n;i++)
{
min=inf;
for(j=1;j<=n;j++)
if(!use[j]&&min>=dis[j])
min=dis[x=j];
if(min==inf)
break;
use[x]=1;
ans+=min;
for(j=1;j<=n;j++)
if(dis[j]>map[x][j])
dis[j]=map[x][j];
}
int flag=1;
for(i=1;i<=n;i++)
if(!use[i])
{
flag=0;
break;
}
if(flag)
printf("%d\n",ans);
else
printf("-1\n");
}
int main()
{
int i,j,k,t,st,en,len;
while(scanf("%d%d%d",&n,&m,&k)==3)
{
memset(con,0,sizeof(con));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
map[i][j]=inf;
while(m--)
{
scanf("%d%d%d",&st,&en,&len);
if(st!=en&&map[st][en]>len)
{
map[st][en]=map[en][st]=len;
}
}
while(k--)
{
scanf("%d",&t);
for(i=0;i<t;i++)
scanf("%d",&con[i]);
for(i=0;i<t;i++)
{
j=i+1;
map[con[i]][con[j]]=map[con[j]][con[i]]=0;
}
}
prim();
}
}