判环
无向图
#include <bits/stdc++.h> #include <vector> #define PI acos(-1.0) #define mem(a,b) memset((a),b,sizeof(a)) #define TS printf("!!!\n") #define pb push_back //std::ios::sync_with_stdio(false); using namespace std; //priority_queue<int,vector<int>,greater<int>> que; const double EPS = 1.0e-9; typedef pair<int, int> pairint; typedef long long ll; typedef unsigned long long ull; const int maxn = 1e5 + 10; const int maxm = 300; int visit[maxn]; int flag=0; int dfs(int x, int pre) { visit[x]=true; int len=p[x].size(); for(int i=0;i<len;i++) { int to=p[x][i]; if(to=pre) continue; if(visit[to]==1) flag=1,
return 0;
else dfs(to,x); } } int main() { int n, m; cin >> n >> m; for (int i = 1; i <= m; i++) { scanf("%d %d", &from, &to); p[from].pb(to); p[to].pb(from); } dfs(1,1); if(flag) cout<<"yes"<<endl; else cout<<"no"<<endl; }
有向图
#include <bits/stdc++.h> #include <vector> #define PI acos(-1.0) #define mem(a,b) memset((a),b,sizeof(a)) #define TS printf("!!!\n") #define pb push_back //std::ios::sync_with_stdio(false); using namespace std; //priority_queue<int,vector<int>,greater<int>> que; const double EPS = 1.0e-9; typedef pair<int, int> pairint; typedef long long ll; typedef unsigned long long ull; const int maxn = 1e5 + 10; const int maxm = 300; int visit[maxn]; int flag=0; int dfs(int x, int pre) { visit[x]=true; int len=p[x].size(); for(int i=0;i<len;i++) { int to=p[x][i]; if(visit[to]==1) flag=1, return ; else dfs(to,x); } } int main() { int n, m; cin >> n >> m; for (int i = 1; i <= m; i++) { scanf("%d %d", &from, &to); p[from].pb(to); } dfs(1); if(flag) cout<<"yes"<<endl; else cout<<"no"<<endl; }