zoukankan      html  css  js  c++  java
  • 【图论】简单环

        stack<int> S;
        vector<int> circle;
        int dep[100005];
        void dfs(int u, int p, int d) {
            dep[u] = d;
            if(!circle.empty())
                return;
            //printf("u=%d
    ", u);
            vis[u] = 1;
            S.push(u);
            int latestA = 0;
            for(int v : G[u]) {
                if(vis[v] == 2)
                    continue;
                if(v == p)
                    continue;
                if(vis[v] == 1) {
                    if(latestA == 0 || dep[v] > dep[latestA])
                        latestA = v;
                }
            }
            if(latestA) {
                while(vis[latestA] == 1) {
                    assert(S.size());
                    circle.push_back(S.top());
                    vis[S.top()] = 2;
                    S.pop();
                }
                return;
            }
            for(int v : G[u]) {
                if(v == p)
                    continue;
                if(vis[v]) {
                    assert(vis[v] == 2);
                    continue;
                }
                dfs(v, u, d + 1);
            }
            if(!S.empty())
                S.pop();
            vis[u] = 2;
        }
    

    利用dfs的性质,每个点先遍历看看是否有反向边,若有反向边则记录最近的祖先。

  • 相关阅读:
    boostrapvalidator
    bootstrap 整理
    emil 的使用
    sass笔记
    sql 语句的优化
    多线程笔记
    mysql笔记
    react
    优雅的创建map/list集合
    spring中路径的注入
  • 原文地址:https://www.cnblogs.com/purinliang/p/14126016.html
Copyright © 2011-2022 走看看