51nod 1649 齐头并进 (djikstra求最短路径,只用跑一次)
生活随笔
收集整理的這篇文章主要介紹了
51nod 1649 齐头并进 (djikstra求最短路径,只用跑一次)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
這道題有一個坑點:兩種交通工具同時出發,中途不能停留在同一個小鎮。
其實想通了就很簡單,因為要么火車一步到達,要么汽車一步到達。不可能停留在同一個地方。
可是我還WA了好幾次,蠢哭。想用BFS寫,一直TLE,后來想到這點之后,用djikstra求單源最短路徑就出來了。
如果火車一步到,就求汽車的單源最短路徑;如果汽車一步到,就求火車的單源最短路徑。
代碼:
#include <iostream> #include <algorithm> #include <map> #include <vector> #include <set> #include <math.h> #include <queue> #include <assert.h> #include <stdio.h> #include <stdlib.h> using namespace std; typedef long long ll; //#define INF 2147483647 #define INF 2000000000int n,m; #define MAX_V 410 int cost[MAX_V][MAX_V]; //cost[u][v]表示e = (u,v)的權值 int d[MAX_V]; //源點s出發的最短距離 bool used[MAX_V]; //標記使用過的點 int djikstra(){fill(d,d+n+1,INF);fill(used,used+n,false);d[1] = 0;while(true){int v = -1;for(int i = 1;i <= n; i++){if(!used[i]&&(v == -1 || d[i] < d[v])) v = i;}if(v == -1) break;used[v] = true;for(int i = 1;i <= n; i++){if(cost[v][i] == 1){d[i] = min(d[i],d[v]+cost[v][i]);}}}if(d[n] == INF) return -1;else return d[n]; }int main() {cin >> n >> m;for(int i = 1;i <= n; i++){for(int j = 1;j <= n; j++){cost[i][j] = -1;if(i == j) cost[i][j] = 0; }}for(int i = 1;i <= m; i++){int u,v;cin >> u >> v;cost[u][v] = 1;cost[v][u] = 1;}if(cost[1][n] == 1){for(int i = 1;i <= n; i++){for(int j = 1;j <= n; j++){cost[i][j] = -cost[i][j];}}}cout << djikstra() << endl;return 0; }總結
以上是生活随笔為你收集整理的51nod 1649 齐头并进 (djikstra求最短路径,只用跑一次)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 51nod 1562 玻璃切割 (STL
- 下一篇: 51nod 1127 最短的包含字符串(