这题挺好的吧~
先处理出不能走的点,然后再跑最短路的时候去判断就行。
对于不能走的点:
先建反图跑最短路,给不能走到终点的点打上标记,然后和这些点相连的点也打上标记。
// Author: levil #include<bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int,int> pii; const int N = 1e4+5; const int M = 2e5+5; const LL Mod = 1e9+7; #define rg register #define pi acos(-1) #define INF 1e9 #define CT0 cin.tie(0),cout.tie(0) #define IO ios::sync_with_stdio(false) #define dbg(ax) cout << "now this num is " << ax << endl; namespace FASTIO{ inline LL read(){ LL x = 0,f = 1;char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -1;c = getchar();} while(c >= '0' && c <= '9'){x = (x<<1)+(x<<3)+(c^48);c = getchar();} return x*f; } void print(int x){ if(x < 0){x = -x;putchar('-');} if(x > 9) print(x/10); putchar(x%10+'0'); } } using namespace FASTIO; void FRE(){/*freopen("data1.in","r",stdin); freopen("data1.out","w",stdout);*/} int n,m,dis[N],vis[N],s,t; vector<int> e[N],G[N]; void dij() { for(rg int i = 1;i <= n;++i) dis[i] = INF; dis[t] = 0; priority_queue<pii,vector<pii>,greater<pii> >Q; Q.push(pii{0,t}); while(!Q.empty()) { int u = Q.top().second; int d = Q.top().first; Q.pop(); if(d > dis[u]) continue; for(auto v : G[u]) { if(dis[v] > dis[u]+1) { dis[v] = dis[u]+1; Q.push(pii{dis[v],v}); } } } } void dij2() { for(rg int i = 1;i <= n;++i) dis[i] = INF; dis[s] = 0; priority_queue<pii,vector<pii>,greater<pii> >Q; Q.push(pii{0,s}); while(!Q.empty()) { int u = Q.top().second; int d = Q.top().first; Q.pop(); if(d > dis[u]) continue; for(auto v : e[u]) { if(vis[v]) continue; if(dis[v] > dis[u]+1) { dis[v] = dis[u]+1; Q.push(pii{dis[v],v}); } } } } int main() { n = read(),m = read(); for(rg int i = 1;i <= m;++i) { int x,y;x = read(),y = read(); e[x].push_back(y); G[y].push_back(x); } s = read(),t = read(); dij(); for(rg int i = 1;i <= n;++i) { if(dis[i] != INF) continue; vis[i] = 1; for(auto v : G[i]) vis[v] = 1; } if(vis[s]) printf("-1 "); else { dij2(); if(dis[t] == INF) printf("-1 "); else printf("%d ",dis[t]); } system("pause"); }