CF427C Checkposts(tarjan求强连通)

本文介绍了一种基于Tarjan算法求解强连通分量的方法,并记录每个分量内的最小值及其出现次数。通过遍历图中的节点,实现对图进行分解,最终输出所有强连通分量的最小值总和及最小值出现次数的乘积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每个强连通分量记最小值,及最小值的个数。

#include <bits/stdc++.h>
using namespace std;
#define N 100010
#define M 300010
#define inf 0x3f3f3f3f
#define ll long long
const int mod=1e9+7;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,m,w[N],h[N],num=0,dfn[N],low[N],dfnum=0,bel[N],scc=0,sw[N],size[N];
ll ans1=0,ans2=1;
bool inq[N];
stack<int>q;
struct edge{
    int to,next;
}data[M];
void tarjan(int x){
    dfn[x]=low[x]=++dfnum;q.push(x);inq[x]=1;
    for(int i=h[x];i;i=data[i].next){
        int y=data[i].to;
        if(!dfn[y]){tarjan(y);low[x]=min(low[x],low[y]);}
        else if(inq[y]) low[x]=min(low[x],dfn[y]);
    }
    if(dfn[x]==low[x]){
        ++scc;sw[scc]=inf;while(1){
            int y=q.top();q.pop();inq[y]=0;bel[y]=scc;
            if(w[y]==sw[scc]) size[scc]++;
            if(w[y]<sw[scc]){sw[scc]=w[y];size[scc]=1;}
            if(y==x) break;
        }
    }
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();for(int i=1;i<=n;++i) w[i]=read();m=read();
    while(m--){
        int x=read(),y=read();data[++num].to=y;data[num].next=h[x];h[x]=num;
    }
    for(int i=1;i<=n;++i) if(!dfn[i]) tarjan(i);
    for(int i=1;i<=scc;++i) ans1+=sw[i],ans2=ans2*size[i]%mod;
    printf("%I64d %I64d\n",ans1,ans2);
    return 0;
}
### Tarjan算法实现连通分量的详细步骤 Tarjan算法是一种基于深度优先搜索(DFS)的方法,用于寻找有向图中的连通分量。以下是其实现的核心逻辑: #### 1. 定义关键变量 - **dfn[u]**:表示节点 `u` 的访问时间戳,在 DFS 遍历时记录每个节点第一次被访问的时间。 - **low[u]**:表示节点 `u` 能够回溯到的最早祖先节点的访问时间戳。 这些变量帮助我们判断当前子图是否构成一个连通分量[^1]。 #### 2. 构建辅助数据结构 - 使用栈来存储当前路径上的节点,当发现某个节点满足条件时,可以弹出栈中属于同一连通分量的所有节点。 #### 3. 深度优先搜索过程 在 DFS 过程中,对于每一个未访问过的节点 `u`: - 初始化 `dfn[u]` 和 `low[u]` 均为当前时间戳。 - 将节点 `u` 入栈并标记为已访问。 - 对于 `u` 的所有邻接点 `v`: - 如果 `v` 尚未被访问,则递归调用 DFS 并更新 `low[u] = min(low[u], low[v])`。 - 如果 `v` 已经在栈中,则说明存在一条指向祖先的反向边,此时应更新 `low[u] = min(low[u], dfn[v])`。 #### 4. 判断连通分量 如果 `dfn[u] == low[u]`,则表明以 `u` 为根的子树构成了一个新的连通分量。此时可以从栈中依次弹出节点直到弹出 `u`,并将它们作为一个独立的连通分量保存下来[^2]。 --- ### Java代码示例 以下是一个完整的 Java 实现示例: ```java import java.util.*; public class TarjanSCC { private static int index; private static Stack<Integer> stack; public static List<List<Integer>> tarjan(List<List<Integer>> graph, int n) { int[] dfn = new int[n]; Arrays.fill(dfn, -1); int[] low = new int[n]; boolean[] onStack = new boolean[n]; stack = new Stack<>(); List<List<Integer>> sccs = new ArrayList<>(); for (int i = 0; i < n; i++) { if (dfn[i] == -1) { dfs(i, graph, dfn, low, onStack, sccs); } } return sccs; } private static void dfs(int u, List<List<Integer>> graph, int[] dfn, int[] low, boolean[] onStack, List<List<Integer>> sccs) { dfn[u] = low[u] = ++index; stack.push(u); onStack[u] = true; for (int v : graph.get(u)) { if (dfn[v] == -1) { dfs(v, graph, dfn, low, onStack, sccs); low[u] = Math.min(low[u], low[v]); } else if (onStack[v]) { low[u] = Math.min(low[u], dfn[v]); } } if (low[u] == dfn[u]) { List<Integer> scc = new ArrayList<>(); while (true) { int node = stack.pop(); onStack[node] = false; scc.add(node); if (node == u) break; } sccs.add(scc); } } public static void main(String[] args) { int n = 7; List<List<Integer>> graph = new ArrayList<>(n); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } graph.get(0).add(1); graph.get(1).add(2); graph.get(2).add(0); graph.get(2).add(3); graph.get(3).add(4); graph.get(4).add(5); graph.get(5).add(3); graph.get(5).add(6); List<List<Integer>> result = tarjan(graph, n); System.out.println("Strongly Connected Components:"); for (List<Integer> component : result) { System.out.println(component); } } } ``` --- ### Python代码示例 Python 版本的实现如下所示: ```python def tarjan_scc(graph): index_counter = [0] stack = [] on_stack = {} indices = {} lows = {} sccs = [] def strongconnect(vertex): indices[vertex] = index_counter[0] lows[vertex] = index_counter[0] index_counter[0] += 1 stack.append(vertex) on_stack[vertex] = True for neighbor in graph[vertex]: if neighbor not in indices: strongconnect(neighbor) lows[vertex] = min(lows[vertex], lows[neighbor]) elif on_stack[neighbor]: lows[vertex] = min(lows[vertex], indices[neighbor]) if lows[vertex] == indices[vertex]: scc = set() while True: w = stack.pop() on_stack[w] = False scc.add(w) if w == vertex: break sccs.append(scc) for vertex in graph.keys(): if vertex not in indices: strongconnect(vertex) return sccs if __name__ == "__main__": graph = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [5], 5: [3, 6], 6: []} components = tarjan_scc(graph) print("Strongly Connected Components:") for comp in components: print(comp) ``` --- ### 性能优势 Tarjan算法具有线性时间复杂度 \( O(V + E) \),其中 \( V \) 是顶点数量,\( E \) 是边的数量。这种高效性能使其成为解决大规模图问题的理想工具[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值