https://pintia.cn/problem-sets/994805342720868352/problems/994805523835109376
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.
Each input file contains one test case. For each test case, the first line contains 4 positive integers: N (≤) - the number of cities (and the cities are numbered from 0 to N−1), M - the number of roads, C?1?? and C?2?? - 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 c?1??, c?2?? 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 C?1?? to C?2??.
For each test case, print in one line two numbers: the number of different shortest paths between C?1?? and C?2??, 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.
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
2 4
给定一个无向图,求从c1到c2的最短路径条数及最大救援人数。
图论算法的入门题,需要注意的是更新路径数,不是简单的加一,而是增加前一点的最短路径数。具体可看代码。
#include <iostream> #include <cstring> using namespace std; int dis[505]; //从起点到目标点的距离 int a[505][505]; //记录从a到b的距离 int r[505]; //记录此地最初有多少救援人员 int vis[505]; //记录此地是否经过 int nowr[505]; //记录此地此时有多少救援人员 int sum[505]; //记录到此地的最短路线共有几条 int main() { memset(vis,0,sizeof(vis)); memset(a,0x3f3f3f,sizeof(a)); //初始化 int n,m,c1,c2; cin >> n >> m >> c1 >> c2; for(int i=0;i<n;i++) { cin >> r[i]; nowr[i] = r[i]; } for(int i=1;i<=m;i++) { int s,e,l; cin >> s >> e >> l; a[s][e] = l; a[e][s] = l; //无向图!! } for(int i=0;i<n;i++) a[i][i] = 0; sum[c1] = 1; for(int i=0;i<n;i++) dis[i] = a[c1][i]; /*dijkstra*/ for(int i=0;i<n;i++) { int u,minum= 0x3f3f3f; for(int j=0;j<n;j++) //找出距离当前距离最短的位置 { if(dis[j]<minum && vis[j] == 0) { minum = dis[j]; u = j; } } vis[u] = 1; for(int j=0;j<n;j++) { if(vis[j] == 1) continue; if(dis[u] + a[u][j] < dis[j]) sum[j] = sum[u]; //找到了更短的路径,路径数重置 else if(dis[u] + a[u][j] == dis[j]) sum[j] += sum[u]; //找到了距离相同的路径,与之前路径数 相加 if(dis[u] + a[u][j] <= dis[j]) { dis[j] = dis[u] + a[u][j]; if(nowr[u] + r[j] > nowr[j]) //距离相同时,若救援人数更多,则更新 nowr[j] = nowr[u] + r[j]; } } } cout << sum[c2] << ‘ ‘ << nowr[c2] << endl; return 0; }
原文:https://www.cnblogs.com/abszse/p/11919497.html