大意
次短路模板+记数
在跑dij的过程中考虑四种情况更新最短路和次短路,以及其数量
- 更新最短路,最短路更新为次短路,相应路径数转移,注意次短路入队条件,最短路入队
- 等于最短路,更新最短路路径数
- 大于最短路小于次短路,更新次短路,次短路路径数转移,入队
- 等于次短路,更新次短路路径数
计数数组初始化为1
/*
*@author:bzdhxs
*@date:2022/03/09
*@URL:http://poj.org/problem?id=3463
最短路 + 次短路计数
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<queue>
using namespace std;
template <typename T>
inline void read(T &s){s = 0;T w = 1, ch = getchar();while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^48); ch = getchar();} s *= w;}
template <typename T>
inline void write(T s){if (s < 0) putchar('-'), s = -s;if (s > 9) write(s / 10);putchar(s % 10 + '0');}
#define int long long
#define _orz ios::sync_with_stdio(false),cin.tie(0)
#define mem(str,num) memset(str,num,sizeof(str))
#define forr(i,a,b) for(int i = a; i <= b;i++)
#define forn(i,n) for(int i = 0; i < n; i++)
#define dbg() cout <<"0k!"<< endl;
typedef long long ll;
int pri[16] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};
const int inf = 0x3f3f3f3f;
const int INF = ~0ULL;
const int N = 1e6+10;
const int mod = 1e9+7;
int n,m;
int s,t;
struct edge{
int to,w,ne;
edge(){}
edge(int a,int b,int c):to(a),w(b),ne(c){}
}e[200005 << 1];
int h[200005],cnt = 1;
int dis[200005][2],dp[200005][2];
int vis[200005][2];
void add(int u,int v,int w){
e[++cnt] = edge(v,w,h[u]);
h[u] = cnt;
}
struct node{
int v,w,op;
// op = 0 最短路 op = 1 次短路
node(){}
node(int a,int b,int c):v(a),w(b),op(c){}
bool operator<(const node&t)const{
return w > t.w;
}
};
priority_queue<node> q;
void init(){
cnt = 1;
forr(i,0,n) h[i] = 0;
}
void dij(int s){
forr(i,0,n){
dis[i][0] = dis[i][1] = inf;
dp[i][0] = dp[i][1] = 0;
vis[i][0] = vis[i][1] = 0;
}
q.push(node(s,0,0));
dis[s][0] = 0,dp[s][0] = 1;
while(q.size()){
int u = q.top().v,typ = q.top().op;
q.pop();
if(vis[u][typ]) continue;
vis[u][typ] = 1;
for(int i = h[u];i;i = e[i].ne){
int v= e[i].to,w = e[i].w;
if(dis[v][0] > w + dis[u][typ]){
dis[v][1] = dis[v][0];
dp[v][1] = dp[v][0];
if(dis[v][0] !=inf) q.push(node(v,dis[v][1],1));
dis[v][0] = w+dis[u][typ];
dp[v][0] = dp[u][typ];
q.push({v,dis[v][0],0});
}
else if(dis[v][0] == w+dis[u][typ]){
dp[v][0] = (dp[v][0]+ dp[u][typ])%mod;
}
else if(dis[v][1] > w+dis[u][typ]){
dis[v][1] = w+dis[u][typ];
dp[v][1] = dp[u][typ];
q.push(node(v,dis[v][1],1));
}
else if(dis[v][1] == w+dis[u][typ]){
dp[v][1] = (dp[v][1]+ dp[u][typ])%mod;
}
}
}
}
void solve(){
init();
cin >> n >> m;
cin >> s >> t;
forr(i,1,m){
int u,v;
cin >> u >> v;
add(u,v,1);
add(v,u,1);
}
dij(s);
if(dis[t][1] - dis[t][0] == 1) cout << (dp[t][0]+dp[t][1])%mod << '\n';
else cout << dp[t][0] << '\n';
}
signed main()
{
_orz;
int t;cin >> t;
while(t--) solve();
return 0;
}