1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <iostream> #include <cstring> #include <algorithm> #include <queue>
using namespace std;
struct node{ int ver, type, dist; bool operator > (const node& nod) const{ return dist > nod.dist; } };
const int N = 1010, M = 10010; int h[N], e[M], ne[M], w[M], idx; int dist[N][2], cnt[N][2]; bool st[N][2]; int t, n, m, S, T;
void add(int a, int b, int c){ e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++; }
int dijkstra(){ memset(st, false, sizeof(st)); memset(dist, 0x3f, sizeof(dist)); memset(cnt, 0, sizeof(cnt)); dist[S][0] = 0, cnt[S][0] = 1; priority_queue<node, vector<node>, greater<node>> q; q.push({S, 0, 0}); while(q.size()){ node tt = q.top(); q.pop(); int ver = tt.ver, type = tt.type, dis = tt.dist; int count = cnt[ver][type]; if(st[ver][type]) continue; st[ver][type] = true; for(int i = h[ver]; ~i; i = ne[i]){ int j = e[i]; if(dist[j][0] > dis + w[i]){ dist[j][1] = dist[j][0], cnt[j][1] = cnt[j][0]; q.push({j, 1, dist[j][1]}); dist[j][0] = dis + w[i], cnt[j][0] = count; q.push({j, 0, dist[j][0]}); } else if(dist[j][0] == dis + w[i]) cnt[j][0] += count; else if(dist[j][1] > dis + w[i]){ dist[j][1] = dis + w[i], cnt[j][1] = count; q.push({j, 1, dist[j][1]}); } else if(dist[j][1] == dis + w[i]) cnt[j][1] += count; } } int res = cnt[T][0]; if(dist[T][0] + 1 == dist[T][1]) res += cnt[T][1]; return res; }
int main(){ cin >> t; while(t--){ cin >> n >> m; memset(h, -1, sizeof(h)); idx = 0; for(int i = 0; i < m; i++){ int a, b, c; cin >> a >> b >> c; add(a, b, c); } cin >> S >> T; cout << dijkstra() << endl; } return 0; }
|