zoukankan      html  css  js  c++  java
  • 图论--SCC缩点--Tarjan

    // Tarjan算法求有向图强连通分量并缩点
    /*强连通缩点与双连通缩点大同小异,也就是说将强连通分支缩成一个点之后,没有强连通,成为有向无环图,在对图进行题目的操作。*/
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    #include<queue>
    using namespace std;
    const int N = 100010, M = 1000010;
    int ver[M], Next[M], head[N], dfn[N], low[N];
    int stack[N], ins[N], c[N];
    int vc[M], nc[M], hc[N], tc;
    vector<int> scc[N];
    int n, m, tot, num, top, cnt;
     
    void add(int x, int y) {
    	ver[++tot] = y, Next[tot] = head[x], head[x] = tot;
    }
     
    void add_c(int x, int y) {
    	vc[++tc] = y, nc[tc] = hc[x], hc[x] = tc;
    }
     
    void tarjan(int x) {
    	dfn[x] = low[x] = ++num;
    	stack[++top] = x, ins[x] = 1;
    	for (int i = head[x]; i; i = Next[i])
    		if (!dfn[ver[i]]) {
    			tarjan(ver[i]);
    			low[x] = min(low[x], low[ver[i]]);
    		}
    		else if (ins[ver[i]])
    			low[x] = min(low[x], dfn[ver[i]]);
    	if (dfn[x] == low[x]) {
    		cnt++; int y;
    		do {
    			y = stack[top--], ins[y] = 0;
    			c[y] = cnt, scc[cnt].push_back(y);
    		} while (x != y);
    	}
    }
     
    int main() {
    	cin >> n >> m;
    	for (int i = 1; i <= m; i++) {
    		int x, y;
    		scanf("%d%d", &x, &y);
    		add(x, y);
    	}
    	for (int i = 1; i <= n; i++)
    		if (!dfn[i]) tarjan(i);
    	for (int x = 1; x <= n; x++)
    		for (int i = head[x]; i; i = Next[i]) {
    			int y = ver[i];
    			if (c[x] == c[y]) continue;
    			add_c(c[x], c[y]);
    		}
    }
  • 相关阅读:
    测试VPS
    [转] 如何在vps上安装和登录Xwindows
    [转]设置修改CentOS系统时区
    顺序队列
    求二叉树的高度
    VMware Workstation cannot connect to the virtual machine
    如何查看hadoop是32位还是64位
    64位CentOS上编译 Hadoop 2.2.0
    hadoop 2.X下eclipse配置
    删除文件及文件夹
  • 原文地址:https://www.cnblogs.com/lunatic-talent/p/12798655.html
Copyright © 2011-2022 走看看