Tarjan 模板

#include <bits/stdc++.h>
#define LL long long
using namespace std;

#define maxn 200007
const int INF=0x3f3f3f3f;


int DFN[maxn],low[maxn],num,index;
bool inStack[maxn];
vector <int> G[maxn];
stack <int> S;
int in[maxn],belong[maxn];
void Tarjan(int u)
{
    int v;
    DFN[u]=low[u]=index++;
    inStack[u]=true;
    S.push(u);
    for(int i=0;i<G[u].size();i++)
    {
        v=G[u][i];
        if(!DFN[v])
        {
            Tarjan(v);
            low[u]=min(low[u],low[v]);
        }
        else if(inStack[v])
        {
            low[u]=min(low[u],DFN[v]);
        }
    }
    if(DFN[u]==low[u])
    {
        num++;
        do
        {
            v=S.top();
            S.pop();
            belong[v]=num;
        }while(v!=u);
    }
}

void SCC(int n)
{
    for(int i=1;i<=n;i++)
    {
        if(!DFN[i])
        {
            Tarjan(i);
        }
    }
}

int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)&&(n||m))
    {
        int a,b;
        memset(DFN,0,sizeof(DFN));
        memset(low,0,sizeof(low));
        index=num=0;
        for(int i=0;i<=n;i++)
        {
            G[i].clear();
        }
        while(m--)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            G[a].push_back(b);
        }
        SCC(n);
        if(num==1) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}
### Tarjan算法求解强连通分量的Python模板代码 以下是基于Tarjan算法的一个标准实现,用于在有向图中查找所有的强连通分量 (Strongly Connected Components, SCC)。此方法通过深度优先搜索 (DFS) 和栈结构来识别图中的强连通子图。 #### Python 实现代码 ```python class TarjanSCC: def __init__(self, graph): self.graph = graph # 图的邻接表表示 self.index_counter = 0 # 节点索引计数器 self.stack = [] # 辅助栈 self.on_stack = set() # 当前节点是否在栈中 self.indices = {} # 记录每个节点的访问顺序 self.low_links = {} # 记录当前节点能到达的最小索引 self.sccs = [] # 存储所有强连通分量的结果 def find_scc(self): for node in self.graph.keys(): if node not in self.indices: self.dfs(node) def dfs(self, node): self.indices[node] = self.index_counter self.low_links[node] = self.index_counter self.index_counter += 1 self.stack.append(node) self.on_stack.add(node) for neighbor in self.graph.get(node, []): # 遍历邻居节点 if neighbor not in self.indices: # 如果未访问过该邻居,则继续深搜 self.dfs(neighbor) self.low_links[node] = min(self.low_links[node], self.low_links[neighbor]) elif neighbor in self.on_stack: # 如果邻居已经在栈中,则更新low_link值 self.low_links[node] = min(self.low_links[node], self.indices[neighbor]) # 判断是否找到一个新的强连通分量 if self.low_links[node] == self.indices[node]: scc = [] while True: top_node = self.stack.pop() self.on_stack.remove(top_node) scc.append(top_node) if top_node == node: break self.sccs.append(scc) # 测试用例 if __name__ == "__main__": # 构建一个简单的有向图(邻接表形式) adj_list = { 'A': ['B'], 'B': ['C', 'E'], 'C': ['D', 'F'], 'D': ['C', 'G'], 'E': ['A', 'F'], 'F': [], 'G': ['D'] } tarjan = TarjanSCC(adj_list) tarjan.find_scc() print("强连通分量:") for i, component in enumerate(tarjan.sccs, start=1): print(f"Component {i}: {component}") ``` 上述代码实现了Tarjan算法的核心逻辑,并提供了一个测试用例展示如何构建输入图以及获取输出结果[^1]。 --- ### 关键概念解释 - **`indices`**: 这是一个字典,记录了每个节点首次被访问的时间戳。 - **`low_links`**: 它也是一个字典,存储的是某个节点能够回溯到的最早祖先节点的时间戳。 - **`stack`**: 辅助数据结构,在遍历时保存路径上的节点。 - **`on_stack`**: 表明哪些节点目前仍在栈中尚未弹出。 - **`graph`**: 输入图为邻接表的形式,便于快速查询某节点的所有相邻节点。 当 `low_links[u] == indices[u]` 成立时,说明找到了一个新的强连通分量,此时需要从辅助栈中依次弹出直到回到当前节点为止[^2]。 --- ### 输出示例 对于上面给出的测试用例,程序会打印如下内容: ``` 强连通分量: Component 1: ['F'] Component 2: ['E', 'A', 'B'] Component 3: ['G', 'D', 'C'] ``` 这表明整个图由三个独立的强连通分量组成。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值