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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include<bits/stdc++.h> #define fo(i,a,b) for(int i=a;i<=b;i++) using namespace std;
typedef long long LL; typedef pair<int,int> pr;
const int maxn=1e5+5;
int n,m; LL a,b; vector<pr> e[maxn],ef[maxn];
LL dis1[maxn],disn[maxn]; bool vis[maxn]; void dijkstra(int st,vector<pr> *e,LL *dis) { memset(dis,127,sizeof(LL)*(n+2)); dis[st]=0; memset(vis,0,sizeof(vis)); priority_queue<pair<LL,int>> Q; Q.push(make_pair(0,st)); fo(i,1,n) { while (!Q.empty() && vis[Q.top().second]) Q.pop(); if (Q.empty()) break; auto tp=Q.top(); Q.pop(); vis[tp.second]=1; for(pr go:e[tp.second]) if (!vis[go.first] && dis[go.first]>-tp.first+go.second) { dis[go.first]=-tp.first+go.second; Q.push(make_pair(-dis[go.first],go.first)); } } }
bool valid[maxn],arrived[maxn]; vector<pr> et[maxn]; LL dp[maxn]; int dg[maxn]; void bfs(LL mid) { memset(dg,0,sizeof(dg)); memset(arrived,0,sizeof(arrived)); queue<int> Q; fo(i,1,n) { et[i].clear(); if (valid[i] && dis1[i]<=a+mid-disn[i]) { Q.push(i); arrived[i]=1; } } while (!Q.empty()) { int cur=Q.front(); Q.pop(); for(auto go:e[cur]) if (go.second+disn[go.first]<=mid) { if (!arrived[go.first]) Q.push(go.first), arrived[go.first]=1; et[cur].push_back(go); dg[go.first]++; } } } bool topo(LL mid) { memset(dp,0xbf,sizeof(dp)); queue<int> Q; fo(i,1,n) if (arrived[i] && !dg[i]) Q.push(i); while (!Q.empty()) { int cur=Q.front(); Q.pop(); if (dis1[cur]<=a+mid-disn[cur]) dp[cur]=max(dp[cur],a+mid-disn[cur]); if (dp[cur]>=b) return 1; for(auto go:et[cur]) { dp[go.first]=max(dp[go.first],dp[cur]+go.second); if (--dg[go.first]==0) Q.push(go.first); } } fo(i,1,n) if (arrived[i] && dg[i]) return 1; return 0; } bool check(LL mid) { fo(i,1,n) valid[i]=(disn[i]<=mid); if (valid[1]) return 1; bfs(mid); return topo(mid); }
int main() { scanf("%lld %lld",&a,&b); scanf("%d %d",&n,&m); fo(i,1,m) { int x,y,z; scanf("%d %d %d",&x,&y,&z); e[x].push_back(make_pair(y,z)); ef[y].push_back(make_pair(x,z)); } dijkstra(1,e,dis1); dijkstra(n,ef,disn); LL l=0, r=dis1[n]; while (l<=r) { LL mid=(l+r)>>1; if (check(mid)) r=mid-1; else l=mid+1; } printf("%lld\n",r+1); }
|