hdu 4612 tarjian求桥双连通分量缩点+树直径

感觉hdu上数据有点水,但不知道哪组数据可以cha掉我的代码,求告知>-<

感觉以后树的直径代码还是统一规范一下,即兴写的。

//hdu 4612 tarjian边双连通缩点+树的直径
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <vector>
#include <stack>
#define inf 0x3f3f3f3f
#define lowbit(x) ((x)&(-x))
#define maxn 200050
using namespace std;
int dfn[maxn],low[maxn],n,m,ans,head[maxn],cnt,cntt,instack[maxn],belong[maxn],anss,block,mn,deep;
struct ee
{
    int next,to,w;
}eage[maxn*10];
stack<int> s;
vector<int> q[maxn];

void add(int a,int b)
{
    eage[cntt].to=b;
    //eage[cntt].w=c;
    eage[cntt].next=head[a];
    head[a]=cntt++;
}

void init()
{
    memset(head,-1,sizeof(head));
    memset(dfn,0,sizeof(dfn));
    memset(low,0,sizeof(low));
    memset(belong,0,sizeof(belong));
    cnt=cntt=0;
    ans=anss=0;
    mn=deep=0;
    block=0;
    while(!s.empty())
        s.pop();
    for(int i=0;i<=n;i++)
        q[i].clear();
}

void tarjian(int a,int b)
{
    low[a]=dfn[a]=++cnt;
    s.push(a);
    for(int i=head[a];i!=-1;i=eage[i].next)
    {
        int j=eage[i].to;
        if(i==(b^1))
            continue;
        if(!dfn[j])
        {
            tarjian(j,i);
            low[a]=min(low[a],low[j]);

        }
        else
            low[a]=min(low[a],dfn[j]);
    }
     if(dfn[a]==low[a])
     {
            block++;
            int k;
            while(k!=a)
            {
                k=s.top();
                s.pop();
                belong[k]=block;
            }
     }
}

void dfs1(int a,int b,int c)                                      //树的直径乱写的
{
    if(c>deep)
    {
        deep=c;
        mn=a;
    }
    for(int i=0;i<q[a].size();i++)
    {
        int j=q[a][i];
        if(j==b)
            continue;
        dfs1(j,a,c+1);
    }
}

int dfs2(int a,int b)
{
    int dep=0;
    for(int i=0;i<q[a].size();i++)
    {
        int j=q[a][i];
        if(j==b)
            continue;
       dep=max(dep,dfs2(j,a));
    }
    return dep+1;
}

int main () {
    //freopen("d:\\in.txt","r",stdin);
    while(scanf("%d%d",&n,&m)==2)
    {
        if(n==0&&m==0)
            break;
        init();
        for(int i=1;i<=m;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            add(a,b);
            add(b,a);
        }
        tarjian(1,-1);
        for(int i=0;i<2*m;i+=2)
        {
            if(belong[eage[i].to]!=belong[eage[i+1].to])
            {
                q[belong[eage[i].to]].push_back(belong[eage[i+1].to]);
                q[belong[eage[i+1].to]].push_back(belong[eage[i].to]);
            }
        }
        dfs1(1,-1,1);
        ans=dfs2(mn,-1);
        printf("%d\n",block-ans);
    }
    return 0;
}

你可能感兴趣的:(hdu 4612 tarjian求桥双连通分量缩点+树直径)