[ABC376D] Cycle
[ABC376D] Cycle
题意
对一个边权为 \(1\) 的简单有向图找一个经过点 \(1\) 的环的最小长度。
思路
因为边权为 \(1\),所以可以直接从点 \(1\) 跑 bfs,找出到每个点的最短路径,最短环即为连向点 \(1\) 的最短路径点 \(v\) 的路径长度 \(+1\)。
代码
#include<bits/stdc++.h>
using namespace std;
int n,m;
bool vis[200005];
struct node{
int x,d;
};
vector<int> t[200005];
int bfs(){
queue<node> q;
q.push({1,0});//从点1开始,路径长度为0
while(!q.empty()){
node u=q.front();q.pop();
vis[u.x]=true;
for(int v:t[u.x]){
if(v==1)
return u.d+1;//该点连向点1
if(vis[v])
continue;
q.push({v,u.d+1});
}
}
return -1;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(),cout.tie();
cin>>n>>m;
for(int x,y,i=1;i<=m;i++){
cin>>x>>y;
t[x].push_back(y);
}
cout<<bfs();
return 0;
}

浙公网安备 33010602011771号