• Tarjan 算法求无向图的割顶和桥


    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    const int N = 250;
    
    int head[N], low[N], dfn[N], fa[N];
    int n, m, now = 1, Tarjan_clock;
    bool is_cut[N];
    struct Node{
    	int u, v, nxt;
    }E[N];
    
    inline int read()
    {
    	int x = 0; char c = getchar();
    	while(c < '0' || c > '9') c = getchar();
    	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    	return x;
    }
    
    inline void add(int u, int v)
    {
    	E[now].v = v;
    	E[now].nxt = head[u];
    	head[u] = now ++;
    }
    
    void Tarjan(int x, int fa_x)
    {
    	low[x] = dfn[x] = ++ Tarjan_clock;
    	fa[x] = fa_x;
    	for(int i = head[x]; ~ i; i = E[i].nxt)
    	{
    		int v = E[i].v;
    		if(!dfn[v])
    		{
    			Tarjan(v, x);
    			low[x] = min(low[x], low[v]);
    		}
    		else
    			if(v != fa_x)
    				low[x] = min(low[x], dfn[v]);
    	}
    }
    
    inline void August_13th()
    {
    	int root_son = 0;
    	Tarjan(1, 0);
    	for(int i = 2; i <= n; i ++)
    	{
    		int fa_i = fa[i];
    		if(fa_i == 1)
    			root_son ++;
    		else 
    			if(low[i] >= dfn[fa_i])
    				is_cut[fa_i] = 1;
    	}
    	if(root_son > 1)
    		is_cut[1] = 1;
    	for(int i = 1; i <= n; i ++)
    		if(is_cut[i])
    			printf("%d
    ", i);
    	for(int i = 1; i <= n; i ++)
    	{
    		int fa_i = fa[i];
    		if(fa_i > 0 && low[i] > dfn[fa_i])
    			printf("%d,%d
    ",fa_i,i);
    	}
    }
    
    int main()
    {
    	n = read();
    	m = read();
    	for(int i = 1; i <= n; i ++)
    		head[i] = -1;
    	for(int i = 1; i <= m; i ++)
    	{
    		int u = read();
    		int v = read();
    		add(u, v);
    		add(v, u);
    	}
    	August_13th();
    	
    	
    	return 0;
    }
    

      

  • 相关阅读:
    三数之和(排序+双指针)
    数值的整数次方(类快速幂)
    Z字形变换
    相交链表
    牛妹的蛋糕
    安置路灯
    迷路的牛牛
    Office 2003的卸载 与 Office 2013 的安装
    解决“飞鸽传书”无法显示局域网用户的方法
    bcd(Binary-Coded Decimal‎缩写)
  • 原文地址:https://www.cnblogs.com/lyqlyq/p/7352659.html
Copyright © 2020-2023  润新知