A city has n intersections and m bidirectional roads connecting pairs of intersections. Each road has a certain traffic flow capacity, measured in cars per minute. There is a path from every intersection to every other intersection along some sequence of roads. The road maintenance department is over budget and needs to close as many roads as possible without disconnecting any intersections. They want to do it in such a way that the minimum capacity among all of the remaining roads is as large as possible.
Input
The first line of input gives the number of cases, N. N test cases follow. Each one starts with a line containing n (0<n<=100) and m (0<m<=10000). The next m lines will describe the m roads, each one using 3 integers, u, v and c (0<=u,v<n), (0<c<=1000). u and v are the endpoints of the road and c is its capacity.
Output
For each test case, output one line containing "Case #x:" followed by the capacity of the minimum-capacity remaining road.
經過分析題意可以清楚知道要讓所有的道路都通同時要讓cost最大,因此很明顯要採用maximum spanning tree來實作,這裡我採用了prim's algorithm
#include <cstdio>
#include <iostream>
#include <memory.h>
using namespace std;
#define INF -1000
int g[100][100];
int prim( int n )
{
int pos, min, j;
int smallest = 10000;
int v[100];
int l[100];
memset(v,0,sizeof(v));
v[0] = 1;
pos = 0;
for( int i=0;i<n;i++ )
if( i!=pos ) l[i] = g[pos][i];
for( int i=0;i<n-1;i++ )
{
int maxi = INF;
for( j=0;j<n;j++ )
{
if( v[j]==0 && maxi < l[j] )
{
maxi = l[j];
pos = j;
}
}
if( maxi<smallest ) smallest = maxi;
v[pos] = 1;
for( j=0;j<n;j++ )
{
if( v[j]==0 && l[j]<g[pos][j])
l[j] = g[pos][j];
}
}
return smallest;
}
int main()
{
int N;
int n, m;
int a, b, c;
int counter = 0;
scanf("%d",&N);
while(N--)
{
scanf("%d%d",&n,&m);
counter++;
memset(g,-1,sizeof(g));
while(m--)
{
scanf("%d%d%d",&a,&b,&c);
if(a!=b)
if( c>g[a][b] )
{
g[a][b] = c;
g[b][a] = c;
}
}
printf("Case #%d: %d\n",counter,prim(n));
}
return 0;
}
本文介绍了一个城市道路维护部门面临预算超支的问题时,如何通过关闭部分道路并保持交通连接的同时,最大化剩余道路中最小通行能力的方法。采用Prim算法实现最大生成树来解决此问题。

被折叠的 条评论
为什么被折叠?



