题意:在一张有重边的有向图中有若干城市,有若干个询问每次告诉你最多能经过q个城市,让你求最多经过q个城市从1号城市到n号城市的最短路是什么?
思路:很容易想到用Dijkstra稍作变形就能解决这一题,只要在我们计算最短路的dis数组中再增加一维,表示最多经过的城市数,这样每次放进队列中的第二个状态变成两个,最后再遍历一下dis数组求一下最小值就能得出答案了。
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cmath> 5 #include <cstring> 6 #include <algorithm> 7 #include <queue> 8 #include <stack> 9 #include <vector> 10 #define MP(a, b) make_pair(a, b) 11 #define PB(a) push_back(a) 12 13 using namespace std; 14 15 typedef long long ll; 16 typedef pair<int ,int> pii; 17 typedef pair<unsigned int, unsigned int> puu; 18 typedef pair<int ,double> pid; 19 typedef pair<ll, int> pli; 20 21 const int INF = 0x3f3f3f3f; 22 const double eps = 1e-6; 23 const int LEN = 110; 24 struct V{char name[22];}; 25 typedef struct{int v, n;}St; 26 typedef pair<int, St> pis; 27 V vex[LEN]; 28 int n, m, dis[LEN][LEN]; 29 vector<pii> Map[LEN]; 30 31 struct cmp{ 32 bool operator ()(pis a, pis b){return a.first>b.first;} 33 }; 34 35 void Dijkstra(int s) 36 { 37 priority_queue<pis, vector<pis>, cmp> q; 38 int vis[LEN][LEN] = {0};St temp; 39 memset(dis, 0x3f, sizeof dis); 40 dis[s][0] = 0; 41 temp.v = s;temp.n = 0; 42 q.push(MP(dis[s][0], temp)); 43 while(!q.empty()){ 44 pis nvex = q.top(); q.pop(); 45 St nv = nvex.second; 46 if(vis[nv.v][nv.n])continue; 47 vis[nv.v][nv.n] = 1; 48 for(int i=0; i<Map[nv.v].size(); i++){ 49 int x = Map[nv.v][i].first, y = Map[nv.v][i].second; 50 if(dis[x][nv.n+1]>dis[nv.v][nv.n]+y){ 51 dis[x][nv.n+1] = dis[nv.v][nv.n]+y; 52 temp.v = x;temp.n = nv.n+1; 53 q.push(MP(dis[x][nv.n+1], temp)); 54 } 55 } 56 } 57 } 58 59 int main() 60 { 61 // freopen("in.txt", "r", stdin); 62 63 int T, val, a, b, q, qn; 64 char from[22], to[22]; 65 scanf("%d", &T); 66 for(int kase = 1; kase<=T; kase++){ 67 for(int i=0; i<LEN; i++)Map[i].clear(); 68 scanf("%d", &n); 69 for(int i=1; i<=n; i++){ 70 scanf("%s", vex[i].name); 71 } 72 scanf("%d", &m); 73 for(int i=0; i<m; i++){ 74 scanf("%s%s%d", from, to, &val); 75 for(int j=1; j<=n; j++){ 76 if(!strcmp(vex[j].name, from))a = j; 77 if(!strcmp(vex[j].name, to))b = j; 78 } 79 Map[a].PB(MP(b, val)); 80 } 81 Dijkstra(1); 82 printf("Scenario #%d ", kase); 83 scanf("%d", &qn); 84 for(int i=0; i<qn; i++){ 85 scanf("%d", &q); 86 int ans = INF; 87 for(int j=0; j<=q+1; j++){ 88 ans = min(ans, dis[n][j]); 89 } 90 if(ans!=INF)printf("Total cost of flight(s) is $%d ", ans); 91 else printf("No satisfactory flights "); 92 } 93 if(kase!=T)printf(" "); 94 } 95 return 0; 96 }