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 78 79 80 81 82
| #include <bits/stdc++.h> #define MAX 500005 #define INF 1e18 #define int long long #define pii pair<int, int> #define weight first #define val second typedef long long LL; using namespace std;
int n,m,q; vector< pii > ahead[MAX]; vector< pii > back[MAX]; int ahead_dis[MAX], back_dis[MAX];
signed main() { ios::sync_with_stdio(0); cin.tie(0); memset(ahead_dis, 0, sizeof(ahead_dis)); memset(back_dis, 0, sizeof(back_dis)); cin >> n >> m >>q; for(int i = 0; i<m; i++){ int a,b,w; cin >> a >> b >> w; ahead[a].push_back(make_pair(w,b)); back[b].push_back(make_pair(w,a)); } for(int i = 0 ;i<MAX;i++){ ahead_dis[i] = INF, back_dis[i] = INF; } ahead_dis[1] = 0, back_dis[n] = 0; bool visA[MAX], visB[MAX]; memset(visA, 0, sizeof(visA)); memset(visB, 0, sizeof(visB)); priority_queue<pii, vector<pii>, greater<pii> > QA; priority_queue<pii, vector<pii>, greater<pii> > QB; QA.push( make_pair(0,1)); QB.push( make_pair(0,n)); while(!QA.empty()){ int cur = QA.top().val; QA.pop(); if(!visA[cur]){ for(pii i : ahead[cur]){ int v = i.val, w= i.weight; if(ahead_dis[cur]+w < ahead_dis[v]){ ahead_dis[v] = ahead_dis[cur]+w; QA.push(make_pair(ahead_dis[v],v)); } } visA[cur] = true; } } while(!QB.empty()){ int cur = QB.top().val; QB.pop(); if(!visB[cur]){ for(pii i : back[cur]){ int v = i.val, w= i.weight; if(back_dis[cur]+w < back_dis[v]){ back_dis[v] = back_dis[cur]+w; QB.push(make_pair(back_dis[v],v)); } } visB[cur] = true; } } while(q--){ int a, b; cin >> a >> b; int ori = ahead_dis[n]; int aft = ahead_dis[a]+1+back_dis[b]; cout << min(ori, aft) << '\n'; } return 0; }
|