PAT (Advanced Level) Practice 1003 Emergency
Topic Description:
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 ) N (≤500) N(≤500) - the number of cities (and the cities are numbered from 0 to N N N− 1), M M M - the number of roads, C 1 C_1 C1 and C 2 C_2 C2 - the cities that you are currently in and that you must save, respectively. The next line contains N N N integers, where the i i 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 c 1 , c 2 c_1, c_2 c1,c2 and L L 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 C 1 C_1 C1 to C 2 C_2 C2.
Output Specification:
For each test case, print in one line two numbers: the number of different shortest paths between C 1 C_1 C1 and C 2 C_2 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 Test:
Sample Input1:
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 Output1:
2 4
Simple analysis:
- 一个Dijkstra的变形,详细见代码注释
My codes:
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510;
int n, m, c1, c2;
int g[N][N], rescue[N];
int dist[N], cnt[N], tot[N];
// cnt代表最短路的数量综合,tot代表最短路时的最大救援人数
bool st[N];
void dijkstra() {
memset(dist, 0x3f, sizeof dist);
dist[c1] = 0, cnt[c1] = 1, tot[c1] = rescue[c1];
for (int i = 0; i < n - 1; i++) {
int t = -1;
for (int j = 0; j < n; j++)
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
for (int j = 0; j < n; j++) {
if (dist[j] > dist[t] + g[t][j]) {
dist[j] = dist[t] + g[t][j];
cnt[j] = cnt[t];
tot[j] = tot[t] + rescue[j];
}
else if (dist[j] == dist[t] + g[t][j]) {
cnt[j] += cnt[t];
tot[j] = max(tot[j], tot[t] + rescue[j]);
}
}
// 在模板的基础上主要增加了两个信息,cnt和tot
st[t] = true;
}
}
int main() {
cin >> n >> m >> c1 >> c2;
for (int i = 0; i < n; i++) cin >> rescue[i];
memset(g, 0x3f, sizeof g);
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = c;
}
dijkstra();
cout << cnt[c2] << ' ' << tot[c2] << endl;
return 0;
}