HDU 4587 TWO NODES 剔除两个点求连通分量

HDU 4587 TWO NODES 删除两个点求连通分量
点击打开链接

TWO NODES

Time Limit: 24000/12000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 649    Accepted Submission(s): 203


Problem Description
Suppose that G is an undirected graph, and the value of stab is defined as follows:
HDU 4587 TWO NODES  剔除两个点求连通分量

Among the expression,G-i, -j is the remainder after removing node i, node j and all edges that are directly relevant to the previous two nodes. cntCompent is the number of connected components of X independently.
Thus, given a certain undirected graph G, you are supposed to calculating the value of stab.
 

Input
The input will contain the description of several graphs. For each graph, the description consist of an integer N for the number of nodes, an integer M for the number of edges, and M pairs of integers for edges (3<=N,M<=5000).
Please note that the endpoints of edge is marked in the range of [0,N-1], and input cases ends with EOF.
 

Output
For each graph in the input, you should output the value of stab.
 

Sample Input
4 5 0 1 1 2 2 3 3 0 0 2
 

Sample Output
2
 

Source
2013 ACM-ICPC南京赛区全国邀请赛——题目重现

让你删除两个点,求最多有多少个连通分量。
枚举要删除的第一个点,然后根据tarjan算法求剩下的每一个点被删除后的连通分量个数。如果一个连通分量只有一个点的话,删除此点此连通分量也就没有了。

//4843MS	420K
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define M 5007
using namespace std;
int low[M],dfn[M],head[M],cut[M];
bool vis[M];
int cnt,num,n,m;
struct E
{
    int v,next;
}edg[M*20];

void addedge(int u,int v)
{
    edg[cnt].v=v;
    edg[cnt].next=head[u];
    head[u]=cnt++;
}
void tarjan(int u,int fa)
{
    low[u]=dfn[u]=++num;
    vis[u]=true;
    for(int i=head[u];i!=-1;i=edg[i].next)
    {
        int v=edg[i].v;
        if(v==fa)continue;
        if(!dfn[v])
        {
            tarjan(v,fa);
            if(low[u]>low[v])
                low[u]=low[v];
            if(low[v]>=dfn[u])
                cut[u]++;//删除u点可以得到cut[u]个连通分量
        }
        else if(low[u]>dfn[v])
            low[u]=dfn[v];
    }
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int u,v;
        memset(head,-1,sizeof(head));
        cnt=0;
        while(m--)
        {
            scanf("%d%d",&u,&v);
            addedge(u,v);
            addedge(v,u);
        }
        int ans=-1,sum;
        for(int i=0;i<n;i++)
        {
            memset(dfn,0,sizeof(dfn));
            memset(low,0,sizeof(low));
            memset(vis,false,sizeof(vis));
            for(int j=0;j<n;j++)cut[j]=1;
            num=sum=0;//sum代表连通分量的个数
            for(int j=0;j<n;j++)
            {
                if(i!=j&&!vis[j])
                {
                    sum++;cut[j]=0;
                    tarjan(j,i);
                }
            }
            for(int j=0;j<n;j++)
                if(j!=i)ans=max(ans,sum+cut[j]-1);
        }
        printf("%d\n",ans);
    }
    return 0;
}