题目链接: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;
}
}