hdu 3371(prim算法)

时间:2023-08-14 22:30:32

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3371

Connect the Cities

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10313    Accepted Submission(s):
2937

Problem Description
In 2100, since the sea level rise, 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
The first line contains the number of test
cases.
Each test case starts with three integers: n, m and k. n (3 <= n
<=500) stands for the number of survived cities, m (0 <= m <= 25000)
stands for the number of roads you can choose to connect the cities and k (0
<= k <= 100) stands for the number of still connected cities.
To make
it easy, the cities are signed from 1 to n.
Then follow m lines, each
contains three integers p, q and c (0 <= c <= 1000), means it takes c to
connect p and q.
Then follow k lines, each line starts with an integer t (2
<= 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
1
6 4 3
1 4 2
2 6 1
2 3 5
3 4 33
2 1 2
2 1 3
3 4 5 6
Sample Output
1
题目大意:
这一题也就是一个很简单的prim算法的变形,题意很容易理解,大概是这样的:一场大雨摧毁可很多路,但是还有一些依然存留,所以题目给出了一些路,还给了已经建好的一些,目的是求所有的路全部连通的最小花费。
在比赛的时候一直想用克鲁斯卡尔,结果不知道是哪里出问题了,一直不能ac,所有。。。。依旧是差这一题ak,在这里反思一下,应该学会转变,不能一直一个思路走下去,结果比赛后,看了这个题目,用prim很容易的解决了,只要在建好路的地图map[a][b]=map[b][a]=0就ok了!还有要注意判重~
详见代码。
 #include <iostream>
#include <cstdio>
using namespace std; int map[][],r[],Min,n,sum,node[];
const int INF=; void set()
{
for (int i=; i<=n; i++)
{
node[i]=INF;
for (int j=; j<=n; j++)
map[i][j]=INF;
}
} void prim()
{
int tm=,m;
int vis[]= {};
node[tm]=;
vis[tm]=;
for (int k=; k<=n; k++)
{
Min=INF;
for (int i=; i<=n; i++)
if (!vis[i])
{
if (node[i]>map[tm][i])
node[i]=map[tm][i];
if (Min>node[i])
{
Min=node[i];
m=i;
}
}
tm=m;
sum+=Min;
vis[m]=;
}
} int main ()
{
int T;
cin>>T;
while (T--)
{
sum=;
int m,k;
scanf("%d%d%d",&n,&m,&k);
set();
for (int i=; i<=m; i++)
{
int p,q,c;
scanf("%d%d%d",&p,&q,&c);
if (map[p][q]>c)
map[p][q]=map[q][p]=c;
}
while (k--)
{
int t;
scanf("%d",&t);
for (int i=; i<=t; i++)
{
cin>>r[i];
}
for (int i=; i<=t; i++)
{
for (int j=; j<=t; j++)
{
map[r[i]][r[j]]=map[r[j]][r[i]]=;
}
}
}
prim();
if (sum<INF)
printf ("%d\n",sum);
else
printf ("-1\n");
}
return ;
}