今天又做了几道最短路颈的题,感觉收货满满,下面来分享一个经典的题目。
Background
Hugo Heavy is happy. After the breakdown of the Cargolifter project he can now expand business. But he needs a clever man who tells him whether there really is a way from the place his customer has build his giant steel crane to the place where it is needed on which all streets can carry the weight.
Fortunately he already has a plan of the city with all streets and bridges and all the allowed weights.Unfortunately he has no idea how to find the the maximum weight capacity in order to tell his customer how heavy the crane may become. But you surely know.
Problem
You are given the plan of the city, described by the streets (with weight limits) between the crossings, which are numbered from 1 to n. Your task is to find the maximum weight that can be transported from crossing 1 (Hugo’s place) to crossing n (the customer’s place). You may assume that there is at least one path. All streets can be travelled in both directions.
Input
The first line contains the number of scenarios (city plans). For each city the number n of street crossings (1 <= n <= 1000) and number m of streets are given on the first line. The following m lines contain triples of integers specifying start and end crossing of the street and the maximum allowed weight, which is positive and not larger than 1000000. There will be at most one street between each pair of crossings.
Output
The output for every scenario begins with a line containing “Scenario #i:”, where i is the number of the scenario starting at 1. Then print a single line containing the maximum allowed weight that Hugo can transport to the customer. Terminate the output for the scenario with a blank line.
题意分析: 这道题的意思就是一个人想从一号城市运送一些货物到第n号城市,问在不损坏道路的前提下,最多能运多少货,每条道路都有一个最大的承载量(权值)。
解题思路:这道题就是dijkstra算法的变形,可以让你对dijkstra有更深刻的理解。
程序代码:
注意:没一个样例结束之后输出的有两个换行。
#include<stdio.h>
#include<math.h>
#include<string.h>//数组置零需要的头文件
int e[1100][1100];
int main()
{
int dis[2000],min;
int i,j,k,n,m,book[2000],inf=-1000,u,v,t,a,b,c,r1=0,max;
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
r1++;
scanf("%d%d",&n,&m);
memset(book,0,sizeof(book));//多样例中每次对数组进行置零处理
memset(e,0,sizeof(e));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j) e[i][j]=0;
else e[i][j]=inf;/*将inf定义为负值可以避免每次找到离他最远
的那个点之后(按dijkstra思想),然后由他扩张出来的的点v,1
v之间没有路的情况*/
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&c);
e[a][b]=c;//因为道路是双向的
e[b][a]=c;
}
for(i=1;i<=n;i++)
dis[i]=e[1][i];
book[1]=1;
for(i=1;i<=n-1;i++)
{
max=inf;
for(j=1;j<=n;j++)
{
if(book[j]==0&&dis[j]>max)//每次找到能运送货物最多的那个路口
{
max=dis[j];
u=j;
}
}
book[u]=1;
for(v=1;v<=n;v++)
{
if(e[u][v]>inf)
{
if(dis[u]>dis[v]&&e[u][v]>dis[v])/*如果从原点到u所
运送的货物比从原点到v所云的货物多并且从u到v云的货也比从
从原点到v运的货多的话就选则这两个中最小的那个,才能不损坏道路*/
{
if(dis[u]<=e[u][v])
dis[v]=dis[u];
else
dis[v]=e[u][v];
}
}
}
}
printf("Scenario #%d:\n",r1);
printf("%d\n",dis[n]);
printf("\n");
}
}
return 0;
}