1. 程式人生 > 其它 >dijsktra次短路計數問題

dijsktra次短路計數問題

題目連結: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];
cnt[k][0]=count;
pq.push({k,0,dist[k][0]});
pq.push({k,1,dist[k][1]});//要同時加入兩個點,因為兩個點都被更新過
}
else if(dist[k][0]==distance+w[i])cnt[k][0]+=count;
else if(dist[k][1]>distance+w[i]){
dist[k][1]=distance+w[i];
cnt[k][1]=count;
pq.push({k,1,dist[k][1]});
}
else if(dist[k][1]==distance+w[i])cnt[k][1]+=count;
}
}
int res=cnt[T][0];
if(dist[T][1]==dist[T][0]+1)res+=cnt[T][1];
return res;
}

int main(){
cin>>t;
while(t--){
memset(h, -1, sizeof h);
idx=0;
memset(dist,0x3f,sizeof dist);
memset(st, 0, sizeof st);
memset(cnt,0,sizeof cnt);
cin>>n>>m;
while(m--){
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
cin>>S>>T;
cout<<dij()<<endl;

}
}