1192.查找集群内的关键连接-Leetcode(tarjan+差分区间+链式前向星)

题目

在这里插入图片描述

思路

链式前向星
一种图的存储方式。不懂可以看一下董晓算法。使用这种存储方式是为了方便寻找反向边。
Tarjan
通过dfs,记录时间戳。
差分区间
不记录最早能到达的节点而是用差分,减少比较的次数。

题解

class Solution {
    // 环边依然会重复遍历
private:
    const static int N = 100010, M = 200010;
    vector<vector<int>> edge;
    int index = 0;
    int c = 0;
    int nxt[M];
    int h[N];
    int first[N];
    int second[N];
    int to[M]{0};
    bool pair_visited[M]{0};
    int low[N]{0};
    int dfn[N]{0};
    int k = -1;
    int st = -1;
public:
    inline void add(int a, int b) {
        nxt[index] = h[a];
        h[a] = index;
        to[index] = b;
        ++index;
    }
    vector<vector<int>> criticalConnections(int n,
                                            vector<vector<int>>& connections) {
        int m = connections.size();
        std::fill_n(h, n, -1);
        while (++k < m) {
            int u = connections[k][0], v = connections[k][1];
            add(u, v);
            add(v, u);
        }
        int p;
        first[++st] = 0;
        dfn[st] = ++c;
        second[st] = -1;
        while (true) {
        next:

            int cur = first[st];
            int l = h[cur];

            while (~l) {
                int j = to[l];

                if (pair_visited[l ^ 1] | pair_visited[l]) {
                    // 异或的方法,
                    l = nxt[l];
                    continue;
                }
                else
                    pair_visited[l] = 1;
                l = nxt[l];

                if (!dfn[j]) {
                    dfn[j] = ++c;
                    
                    first[++st] = j;
                    second[st] = cur;
                    goto next;
                    // goto效率
                }
                ++low[cur];
                --low[j];
            }
            p = second[st];
            
            if (!~p)
                return edge;
            if (low[cur]) {
                low[p] += low[cur];
            } else {
                edge.push_back({cur, p});
            }
            --st;
        }
    }
};

运行效果

在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值