
- #include
- #define endl '\n'
- #define int long long
- using namespace std;
- constexpr int N = 1e5, M = N, inf = 0x3f3f3f3f;
- vector<int> g[N];
- bool onpath[N]; // 记录一次递归堆栈中的节点
- bool vis[N]; // 记录遍历过的节点,防止走回头路
- bool cycle; // 记录图中是否有环
- void dfs(int u)
- {
- if (onpath[u])
- {
- cycle = true;
- }
- if (vis[u] || cycle)
- {
- return;
- }
- // 标记节点u已经遍历,且开始遍历节点u;
- vis[u] = onpath[u] = true;
- for (const auto &it : g[u])
- {
- dfs(it);
- }
- onpath[u] = false; // 标记尾部取消;
- }
- void solve()
- {
- int n, m;
- cin >> m;
- for (int i = 0; i < m; i++)
- {
- int a, b;
- cin >> a >> b;
- g[a].push_back(b);
- }
- for (int i = 0; i < m; i++)
- {
- dfs(i);
- }
- if (cycle)
- {
- cout << "yes" << endl;
- }
- else
- cout << "no" << endl;
- }
- signed main()
- {
- ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
-
- solve();
-
- return 0;
- }