鏈接:https://ac.nowcoder.com/acm/problem/16498
來源:牛客網
在有向圖G中,每條邊的長度均爲1,現給定起點和終點,請你在圖中找一條從起點到終點的路徑,該路徑滿足以下條件:
1.路徑上的所有點的出邊所指向的點都直接或間接與終點連通。
2.在滿足條件1的情況下使路徑最短。
注意:圖G中可能存在重邊和自環,題目保證終點沒有出邊。
請你輸出符合條件的路徑的長度。
第一行有兩個用一個空格隔開的整數n和m,表示圖有n個點和m條邊。 接下來的m行每行2個整數x、y,之間用一個空格隔開,表示有一條邊從點x指向點y。 最後一行有兩個用一個空格隔開的整數s、t,表示起點爲s,終點爲t。
輸出只有一行,包含一個整數,表示滿足題目描述的最短路徑的長度。如果這樣的路徑不存在,輸出-1。
示例1
3 2 1 2 2 1 1 3
-1
如上圖所示,箭頭表示有向道路,圓點表示城市。起點1與終點3不連通,所以滿足題目描述的路徑不存在,故輸出-1。
示例2
6 6 1 2 1 3 2 6 2 5 4 5 3 4 1 5
3
如上圖所示,滿足條件的路徑爲1->3->4->5。注意點2不能在答案路徑中,因爲點2連了一條邊到點6,而點6不與終點5連通。
對於30%的數據,0< n≤10,0< m≤20; 對於60%的數據,0< n≤100,0< m≤2000; 對於100%的數據,0< n≤10,000,0< m≤200,000,0< x,y,s,t≤n,x≠t。
思路:
反着 建邊,走兩邊bfs即可。
代碼如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <map> #include <vector> #include <queue> using namespace std; const int maxn=1e4+5; int n,m; vector<int>v2[maxn]; int vis1[maxn],vis2[maxn]; int st,en; int ans=0; struct node { int pos; int num; }; void dfs(int x) { queue<int>q; q.push(en); while (!q.empty()) { int t=q.front();q.pop(); vis2[t]=1; int Size=v2[t].size(); for (int i=0;i<Size;i++) { int u=v2[t][i]; if(!vis2[u]) { q.push(u); } } } } bool bfs () { queue<node>q; node now,next; now.pos=en,now.num=0; q.push(now); while (!q.empty()) { now=q.front();q.pop(); if(now.pos==st) { ans=now.num; return true; } int t=now.pos; for (int i=0;i<v2[t].size();i++) { int u=v2[t][i]; if(!vis1[u]) { next.pos=u; next.num=now.num+1; q.push(next); } } } return false; } int main() { memset (vis1,0,sizeof(vis1)); memset (vis2,0,sizeof(vis2)); scanf("%d%d",&n,&m); for (int i=0;i<m;i++) { int x,y; scanf("%d%d",&x,&y); v2[y].push_back(x); } scanf("%d%d",&st,&en); dfs(en); for (int i=1;i<=n;i++) { if(!vis2[i]) { for (int j=0;j<v2[i].size();j++) { int u=v2[i][j]; vis1[u]=1; } } } if(bfs()) printf("%d\n",ans); else printf("-1\n"); return 0; }