Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define pb push_back
- #define mp make_pair
- #define sz(x) (int)(x).size()
- #define ll long long
- #define ld long double
- #define ft first
- #define sc second
- #define pii pair<int, int>
- #define pll pair<ll, ll>
- #define forn(i, t) for(int i = 0; i < (t); i++)
- #define fore(i, f, t) for(int i = (f); i < (t); i++)
- #define forr(i, f, t) for(int i = (f) - 1; i >= (t); i--)
- #define all(x) (x).begin(), (x).end()
- #define ins insert
- const int INF = 1e9;
- const int MOD = 1000000007;
- const ll INF64 = 9223372036854775807;
- const ld EPS = 1e-7;
- using namespace std;
- struct edge{
- int v, u, w;
- edge(int v, int u, int w) : v(v), u(u), w(w){}
- };
- const int N = 1001;
- vector<pii> g[N], z[N], r[N];
- vector<edge> e;
- void Dijkstra(int s, vector<int> &d) {
- d[s] = 0;
- set<pii> q;
- q.insert(mp(d[s], s));
- while (!q.empty()){
- int u = q.begin()->sc;
- q.erase(q.begin());
- forn(i, sz(g[u])){
- int v = g[u][i].ft;
- int w = g[u][i].sc;
- if (d[u] + w < d[v]) {
- q.erase(mp(d[v], v));
- d[v] = d[u] + w;
- q.insert(mp(d[v], v));
- }
- }
- }
- }
- void DijkstraRev(int s, vector<int> &d) {
- d[s] = 0;
- set<pii> q;
- q.insert(mp(d[s], s));
- while (!q.empty()){
- int u = q.begin()->sc;
- q.erase(q.begin());
- forn(i, sz(z[u])){
- int v = z[u][i].ft;
- int w = z[u][i].sc;
- if (d[u] + w < d[v]) {
- q.erase(mp(d[v], v));
- d[v] = d[u] + w;
- q.insert(mp(d[v], v));
- }
- }
- }
- }
- vector<char> used;
- int dp[N][2], n;
- vector<int> d1, d2;
- void dfs(int v, int &k){
- used[v] = 1;
- int u, w;
- forn(i, sz(r[v])){
- u = r[v][i].ft;
- w = r[v][i].sc;
- if (!used[u])
- dfs(u, k);
- if (d1[v] + d2[u] + w == k){
- dp[v][0] += dp[u][0];
- dp[v][1] += dp[u][1];
- }
- else if (d1[v] + d2[u] + w == k + 1)
- dp[v][1] += dp[u][0];
- }
- }
- void solve(){
- int m, f, t, w;
- scanf("%d%d", &n, &m);
- memset(dp, 0, sizeof(dp));
- e = vector<edge>();
- used = vector<char>(n, 0);
- forn(i, n)
- r[i] = z[i] = g[i] = vector<pii>();
- d1 = d2 = vector<int>(n, INF);
- forn(i, m){
- scanf("%d%d%d", &f, &t, &w);
- g[--f].pb(mp(--t, w));
- z[t].pb(mp(f, w));
- e.pb(edge(f, t, w));
- }
- scanf("%d%d", &f, &t);
- --f, --t;
- Dijkstra(f, d1);
- DijkstraRev(t, d2);
- int k = d1[t];
- forn(i, m)
- if (d1[e[i].v] + d2[e[i].u] + e[i].w <= k + 1){
- r[e[i].v].pb(mp(e[i].u, e[i].w));
- }
- dp[t][0] = 1;
- dfs(f, k);
- printf("%d\n", dp[f][0] + dp[f][1]);
- }
- int main(){
- int n;
- scanf("%d", &n);
- forn(i, n)
- solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement