题目:
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 (≤) - 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 Nintegers, 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
题目分析:
深搜DFS。具体分析见代码注释。
代码:
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 5 int N; //城市数量 6 int M; //道路数量 7 int C1; //起始城市编号 8 int C2; //终点城市编号 9 10 int teams[501]; //城市含有的救援队数 11 int road[501][501]; //道路情况 12 13 int roadNum; //最短路径数量 14 int teamNum; //最大的救援队数量 15 int lengthMin; //最短路径长度 16 17 //深搜算法,三个参数为:当前的城市编号,当前救援队伍数量,当前的路径长度 18 void dfs(int from,int teamTemp,int lengthTemp){ 19 if(from==C2){ //若已经抵达终点 20 if(lengthTemp<lengthMin){ //若路径比最短路径还要短,就更新最短路径 21 lengthMin=lengthTemp; 22 teamNum=teamTemp; 23 roadNum=1; 24 }else if(lengthTemp==lengthMin){ //若跟最短路径一样短,最短路径数量增加1 25 if(teamTemp>teamNum){ 26 teamNum=teamTemp; 27 } 28 roadNum++; 29 } 30 return; 31 } 32 for(int i=0;i<N;i++){ //进行深搜遍历 33 if(road[from][i]!=0){ 34 int t=road[from][i]; 35 road[from][i]=0; 36 road[i][from]=0; 37 dfs(i,teamTemp+teams[i],lengthTemp+t); 38 road[from][i]=t; 39 road[i][from]=t; 40 } 41 } 42 } 43 44 int main(){ 45 memset(road,0,sizeof(road)); 46 roadNum=0; 47 teamNum=0; 48 lengthMin=1000000; 49 cin>>N>>M>>C1>>C2; 50 for(int i=0;i<N;i++){ 51 cin>>teams[i]; 52 } 53 int c1,c2; //两个城市 54 for(int i=0;i<M;i++){ 55 cin>>c1>>c2; 56 cin>>road[c1][c2]; 57 road[c2][c1]=road[c1][c2]; 58 } 59 dfs(C1,teams[C1],0); 60 cout<<roadNum<<" "<<teamNum; 61 return 0; 62 }