题目链接:
https://vjudge.net/problem/POJ-3255
题目大意:
给无向图,求1到n的次短路长度
思路:
由于边数较多,应该使用dijkstra的队列优化
用d数组存储最短路,用d2数组存储次短路,每次更新的时候,先松弛更新最短路,如果松弛更新成功,把之前的最短路取出,再和次短路比较,更新次短路。每次更新两个数组
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 #include<algorithm> 5 #include<cstring> 6 #include<cstdio> 7 using namespace std; 8 typedef pair<int, int> Pair; 9 const int maxn = 5000 + 10; 10 const int INF = 0x3f3f3f3f; 11 int n, m; 12 struct edge 13 { 14 int v, w; 15 edge(int v, int w):v(v), w(w){} 16 }; 17 vector<edge>G[maxn]; 18 int d[maxn], d2[maxn]; 19 void dijkstra() 20 { 21 memset(d, INF, sizeof(d)); 22 memset(d2, INF, sizeof(d2)); 23 d[1] = 0; 24 priority_queue<Pair, vector<Pair>, greater<Pair> >q; 25 q.push(Pair(0, 1));//1为当前节点,0位最短距离 26 while(!q.empty()) 27 { 28 Pair now = q.top(); 29 q.pop(); 30 int dis = now.first, u = now.second; 31 //cout<<dis<<" "<<u<<endl; 32 if(dis > d2[u])continue;//距离比次短距离大,直接continue 33 for(int i = 0; i < G[u].size(); i++) 34 { 35 edge &e = G[u][i]; 36 int dis2 = dis + e.w; 37 if(d[e.v] > dis2) 38 { 39 swap(d[e.v], dis2);//dis2保存较小的值和后面进行比较 40 q.push(Pair(d[e.v], e.v)); 41 } 42 if(d2[e.v] > dis2 && d[e.v] < dis2)//保证dis2为次短路 43 { 44 d2[e.v] = dis2; 45 q.push(Pair(d2[e.v], e.v));//次短路也入队列 46 } 47 } 48 } 49 cout<<d2[n]<<endl; 50 } 51 int main() 52 { 53 cin >> n >> m; 54 int u, v, w; 55 while(m--) 56 { 57 scanf("%d%d%d", &u, &v, &w); 58 G[u].push_back(edge(v, w)); 59 G[v].push_back(edge(u, w)); 60 } 61 dijkstra(); 62 }