题意:N条路,M个村庄,已知N条路各自连接的村庄代号和道路成本,求连通所有村庄的最低成本
思路:本体既可以并查集也可以最小生成树,都需要判断是否联通
|
畅通工程
Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
Sample Input
Sample Output
|
// #define DISJOINT_SET
#ifndef DISJOINT_SET // 并查集
#include<cstdio>
#include<algorithm>
using namespace std;
#define MAX 105
int father[MAX];
typedef struct node
{
int x,y,cost;
}node;
node a[MAX];
int find(int x)
{
if( x != father[x] )
father[x] = find(father[x]);
return father[x];
}
int merge(int x,int y)
{
x = find(x);
y = find(y);
if(x != y)
{
father[x] = y;
return 1;
}
return 0;
}
int cmp(node a,node b)
{
return a.cost < b.cost; //升序
}
int main()
{
int i,n,m;
int res,count;
// freopen("a.txt","r",stdin);
while(~scanf("%d %d",&n,&m),n)
{
for(i=1;i<=m;i++)
father[i] = i;
for(i=1;i<=n;i++)
{
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].cost);
} //i从1开始,所以sort(a+1,…)
sort(a+1,a+n+1,cmp); //排序目的:当a点可以和b、c点组成集合时优先和成本低的组合
res = 0;
count = 0;
for(i=1;i<=n;i++)
{
if(merge(a[i].x,a[i].y))
res += a[i].cost;
}
for(i=1;i<=m;i++) //判断连通
if(father[i] == i)
count ++;
if(count > 1)
printf("?\n");
else
printf("%d\n",res);
}
return 0;
}
#else
// prim
#include<cstdio>
#include<cstring>
#define MAX 102
#define MAXINT 99999999
int vist[MAX],dp[MAX],n,N,map[MAX][MAX];
void prim()
{
int i,j,k,res,temp;
for(i=1;i<=n;i++)
dp[i] = map[1][i];
vist[1] = 1;
res = 0;
for(i=1;i<n;i++)
{
temp = MAXINT;
for(j=1;j<=n;j++)
{
if(!vist[j] && dp[j] < temp)
{
temp = dp[j];
k = j;
}
}
if(temp == MAXINT) //如果某次找不到相连点则表示不联通
{
printf("?\n");
return ;
}
vist[k] = 1;
res += temp;
for(j=1;j<=n;j++)
if(!vist[j] && map[k][j] < dp[j] )
dp[j] = map[k][j];
}
printf("%d\n",res);
}
int main()
{
int i,cost,a,b;
int j;
// freopen("a.txt","r",stdin);
while(~scanf("%d%d",&N,&n) ,N)
{
memset(vist,0,sizeof(vist));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
map[i][j] = map[j][i] = MAXINT;
for(i=1;i<=N;i++)
{
scanf("%d%d%d",&a,&b,&cost);
map[a][b] = map[b][a] = cost;
}
prim();
}
return 0;
}
#endif