dijsktra次短路計數問題 阿新 • • 發佈:2021-08-20 題目連結:https://www.acwing.com/problem/content/385/ 次短距離一定只能由次短距離更新 程式碼: #include <iostream>#include <cstring>#include <algorithm>#include <queue>#include<vector>using namespace std;const int N = 2010,M=2e5+10;int t,m,n;int h[N], e[M], ne[M], w[M],idx;int dist[N][2],st[N][2],cnt[N][2];//拆點,將一個點拆成最短長度和次短長度兩個,當成兩個點分別加入dij的pq中int S,T;void add(int a, int b,int c) // 新增一條邊a->b{ e[idx] = b, ne[idx] = h[a],w[idx]=c, h[a] = idx ++ ;}struct ver{ int id,type,dist; bool operator>(const ver&other)const{ return dist>other.dist; }};int dij(){ dist[S][0]=0; cnt[S][0]=1; priority_queue<ver,vector<ver>,greater<ver> > pq; pq.push({S,0,0}); while(pq.size()){ auto cur=pq.top(); pq.pop(); int id=cur.id,type=cur.type,distance=cur.dist,count=cnt[id][type]; if(st[id][type])continue; st[id][type]=true; for(int i=h[id];~i;i=ne[i]){ int k=e[i]; if(dist[k][0]>distance+w[i]){//如果更新了最短路,那次短路也要更新,注意注意 dist[k][1]=dist[k][0]; dist[k][0]=distance+w[i]; cnt[k][1]=cnt[k][0];