poj2117 tarjan()+割点

//题意:给你一个无向图不保证是连通的,去掉某一个顶点之后,询问最多可以形成的分支数目。
//思路:
//1.处理孤立点的情况
//2.利用tarjan求解去掉的顶点,然后满足条件(最多).
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define maxn 10001
typedef vector<int>::iterator it;
vector<int> g[maxn];
int dfn[maxn],low[maxn];
bool vit[maxn];
int n,idx,sons;
int ans;
void dfs(int u,bool root)
{
    vit[u]=1;
    dfn[u]=low[u]=++idx;
    int child=0;
    for(it i=g[u].begin(); i!=g[u].end(); ++i)
    {
        int v=*i;
        if(!dfn[v])
        {
            dfs(v,false);
            low[u]=min(low[u],low[v]);
            if(root)
                sons++;
            else if(low[v]>=dfn[u])
                child++;
        }
        else low[u]=min(low[u],dfn[v]);
    }
    ans=max(ans,child+1);//low[v]>=dfn[u]得到的是child+1个支点
}
int tarjan(int root)
{
    if(g[root].size()==0)
        return 0;
    memset(dfn,0,sizeof(dfn));
    ans=idx=sons=0;
    dfs(root,true);
    if(sons>1)
        ans=max(ans,sons);
    return ans;
}
int main()
{
    int m,u,v;
    while(scanf("%d%d",&n,&m)!=EOF && n)
    {
        for(int i=0; i<n; i++)
            g[i].clear();
        while(m-->0)
        {
            scanf("%d%d",&u,&v);
            g[u].push_back(v);
            g[v].push_back(u);
        }
        memset(vit,0,sizeof(vit));
        int ma=0,total=0;
        for(int i=0; i<n; i++)
            if(!vit[i])
                total++,ma=max(ma,tarjan(i));//求解分支的个数和判断删除一个点之后,所分割的最大值ma.
        printf("%d\n",total+ma-1);
    }
    return 0;
}

你可能感兴趣的:(poj2117 tarjan()+割点)