As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead your men to the place as quickly as possible, and at the mean time, call up as many hands on the way as possible.
Input Specification:
Each input file contains one test case. For each test case, the first line contains 4 positive integers: N (≤500) - the number of cities (and the cities are numbered from 0 to N−1), M - the number of roads, C1 and C2 - the cities that you are currently in and that you must save, respectively. The next line contains N integers, where the i-th integer is the number of rescue teams in the i-th city. Then M lines follow, each describes a road with three integers c1, c2 and L, which are the pair of cities connected by a road and the length of that road, respectively. It is guaranteed that there exists at least one path from C1 to C2.
Output Specification:
For each test case, print in one line two numbers: the number of different shortest paths between C1 and C2 , and the maximum amount of rescue teams you can possibly gather. All the numbers in a line must be separated by exactly one space, and there is no extra space allowed at the end of a line.
Sample Input:
5 6 0 2
1 2 1 5 3
0 1 1
0 2 2
0 3 1
1 2 1
2 4 1
3 4 1
Sample Output:
2 4
题目大意:给出一个城市地图,包括起点、终点、每个城市的营救人员、以及两城市之间的距离。现为了从起点出发去终点营救人,要求路径最短,并且沿路带上尽可能多的营救人员。输出最短路径的条数、在最短路径下的最多营救人员。
思路:这一题是Dijkstra的一个简单变形,第一因素:边权和最小;第二因素:点权和最大。
- e[ ][ ]存图、a[ ]表示每个城市的营救人员、vis[ ]标记城市;
- dis[ ]表示从源点到该城市的最短距离、num[ ]表示从源点到该城市的最短距离的条数、weight[ ]表示从源点到该城市的最大点权和。
代码如下:
#include <stdio.h>
#define inf 0x3f3f3f3f
int main()
{
int n, m, s, d;
int vis[500]={0}, e[500][500], a[500];
int dis[500], num[500], weight[500];
scanf("%d%d%d%d", &n, &m, &s, &d);
int i, j;
for(i=0; i<n; i++)
{
e[i][i] = 0;
for(j=i+1; j<n; j++)
e[i][j] = e[j][i] = inf;
}
for(i=0; i<n; i++) scanf("%d", &a[i]);
for(i=1; i<=m; i++)
{
int a, b, l;
scanf("%d%d%d", &a, &b, &l);
if(e[a][b] > l) e[a][b] = e[b][a] = l;
}
for(i=0; i<n; i++) dis[i] = i == s ? 0 : e[s][i];
num[s] = 1;
weight[s] = a[s];
for(i=0; i<n; i++)
{
int k = -1;
int min = inf;
for(j=0; j<n; j++)
if(!vis[j] && min > dis[j])
{
k = j;
min = dis[j];
}
if(k == -1) break;
vis[k] = 1;
for(j=0; j<n; j++)
{
if(!vis[j] && dis[j] > dis[k] + e[k][j])/* 如果路径可以更短 */
{
dis[j] = dis[k] + e[k][j];
weight[j] = weight[k] + a[j];/* 首先就取最短路径的点权和 */
num[j] = num[k];/* 因为现在路径更新成了从k到j,所以到j的最短路径的个数和到K的相同 */
}
else if(!vis[j] && dis[j] == dis[k] + e[k][j])/* 路径长度相同,考虑第二因素 */
{
if(weight[j] < weight[k] + a[j])/* 如果点权和可以更大 */
weight[j] = weight[k] + a[j];
num[j] += num[k];/* 路径长度相同,说明从k也可以以最短路径到j,
那么路径数=等于之前已经算过的路径数+到k的路径数 */
}
}
}
printf("%d %d\n", num[d], weight[d]);
return 0;
}