洛谷 P3388 【模板】割点

题目链接:

https://www.luogu.org/problemnew/show/P3388

题意:

给定一个n个点,m条边的无向图,告诉你哪些点相连,让你求割点个数,并从小到达输出割点

分析:

模板,tarjan

tarjan求割点:

同tarjan求强连通分量,需引入 l o w [ x ] low[x] d f n [ x ] dfn[x] 数组;
某个 x x 点是割点那么它有两种可能,(1)在以该 x x 点为根的dfs树中,它的子树个数一定大于等于2个(显然);(2)该 x x 点不为根,在dfs树中,存在它的一个子节点 y y ,使得 d f n [ x ] < = l o w [ y ] dfn[x]<=low[y] ;对于第二种情况,若不存在这样的一个 y y 点使得 d f n [ x ] < = l o w [ y ] dfn[x]<=low[y] ,或者说存在 y y 使得 d f n [ x ] > l o w [ y ] dfn[x]>low[y] ,即存在一条边连接 y y x x 的父亲或着更上面的节点,这样的话显然 x x 就不是割点;

代码:

#include<iostream>
#include<string>
#include<queue>
#include<set>
#include<vector>
#include<stack>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;

const double inf=0x7f7f7f7f;
const int maxn=1e5+50;
const int N=2e4+50;
typedef long long ll;
typedef struct{
    int u,v,next,lca;
}Edge;
Edge e[2*maxn];

int cnt,head[maxn];

void add(int u,int v){
    e[cnt].u=u;
    e[cnt].v=v;
    /*e[cnt].w=w;
    e[cnt].f=f;*/
    e[cnt].next=head[u];
    head[u]=cnt++;
    e[cnt].u=v;
    e[cnt].v=u;
/*	e[cnt].w=0;
    e[cnt].f=-f;*/
    e[cnt].next=head[v];
    head[v]=cnt++;
}

int read()
{
    int x = 0;
    int f = 1;
    char c = getchar();
    while (c<'0' || c>'9')
    {    
        if (c == '-')
            f = -1;
        c = getchar();
    }
    while (c >= '0'&&c <= '9')
    {
        x = x * 10 + c - '0';
        c = getchar();
    }
    return x*f;
}

int root,n,m,dfn[N],low[N],_cut[N],_time,_num,vis[N];
void tarjan(int u){
    int son=0;
    low[u]=dfn[u]=++_time;
    for(int i=head[u];i!=-1;i=e[i].next){
            int v=e[i].v;
            if(!dfn[v]){
                son++;
                tarjan(v);
                low[u]=min(low[v],low[u]);
                if(root==u&&son>=2){//该点是根的情况
                    if(!vis[u]){	//我这里是将割点存在_cut数组里面,_num是割点数目,vis用来标记这个割点是不是已经存入数组了
                        vis[u]=1;	//可能会出现多次存割点的情况(比如一个割点同时连接了三四个连通块),所以有vis数组
                        _cut[_num++]=u;
                    }
                }
                else if(root!=u&&dfn[u]<=low[v]){//不是根的情况
                    if(!vis[u]){				//这里同理
                        vis[u]=1;
                        _cut[_num++]=u;
                    }
                }
            }
            else low[u]=min(dfn[v],low[u]);//这里和tarjan求连通量不一样,tarjan可以写成low[u]=min(low[u],low[v])这两种都可以;这里只能这样写,
    }									   //dfn[k]可能!=low[k],所以不能用low[k]代替dfn[k],否则会上翻过头了。
}

int main() {
    cin>>n>>m;
    int a,b;
    memset(head,-1,sizeof(head));
    for(int i=0;i<m;i++){
        cin>>a>>b;

        add(a,b);    
    }
    for(int i=1;i<=n;i++){
        if(!dfn[i]){
            root=i;
            tarjan(i);
        }
    }
    cout<<_num<<endl;
    sort(_cut,_cut+_num);
    for(int i=0;i<_num;i++)
        cout<<_cut[i]<<" ";
    return 0;
}

(仅供个人理解)

猜你喜欢

转载自blog.csdn.net/UoweMee/article/details/88675246