hdu3849 Tarjan求无向图的割边+map


#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

//#include
using namespace std;
const int maxn=100010;

int dfn[maxn],low[maxn],Stack[maxn],head[maxn],vis[maxn],Dfn[maxn];
int bridge[maxn],father[maxn];
int cnt,index,e,n,m;
struct E
{
    int from,to,next;
} edge[maxn*8];

void init()
{
    index=cnt=e=0;
    memset(vis,0,sizeof(vis));

    memset(bridge,0,sizeof(bridge));
    //for(int i=1; i<=n; i++)father[i]=i;
}

int cmp(int a,int b)
{
    return a>b;
}

void Insert(int x,int y)
{
    edge[e].from=x;
    edge[e].to=y;
    edge[e].next=head[x];
    head[x]=e++;
}

void tarjan(int u,int father)
{
    dfn[u]=low[u]=index++;//这里是0开始
    for(int i=head[u]; i!=-1; i=edge[i].next)
    {
        int v=edge[i].to;
        if(father==v)continue;//这里的位置需注意!!调了好久.....太渣
        if(!dfn[v])
        {
            tarjan(v,u);//这里向下一层进行
            low[u]=min(low[u],low[v]);
            if(low[v]>dfn[u])//割边
            {
                bridge[cnt++]=i;
                //cout<<"Yeah"<
            }
        }
        else low[u]=min(low[u],dfn[v]);//反向边
    }
}




int main()
{
    int i,j,x,y;
    int t,sum;
    char str[2][200];
    scanf("%d",&t);
    while(t--)
    {
        init();
        scanf("%d%d",&n,&m);
        memset(head,-1,sizeof(head));
        sum=1;
        map<string,int>mp;
        map<int,string>mmp;
        for(i=0;iscanf("%s%s",str[0],str[1]);
            if(mp[str[0]]==0)
            {
                mp[str[0]]=sum;
                mmp[sum]=str[0];
                sum++;
            }
            if(mp[str[1]]==0)
            {
                mp[str[1]]=sum;
                mmp[sum]=str[1];
                sum++;
            }
            x=mp[str[0]];
            y=mp[str[1]];
            Insert(x,y);
            Insert(y,x);
        }
        memset(dfn,0,sizeof(dfn));

        tarjan(1,-1);
        //if(i<=n){printf("0");continue;}
        printf("%d\n",cnt);
        sort(bridge,bridge+cnt,cmp);
        for(j=0; j2*2;
            x=edge[i].from;
            y=edge[i].to;
            if(x!=y)
                printf("%s %s\n",mmp[edge[i].from].c_str(),mmp[edge[i].to].c_str());
        }
    }
}



转载于:https://www.cnblogs.com/wlxtuacm/p/5712275.html

你可能感兴趣的:(hdu3849 Tarjan求无向图的割边+map)