Critical Links——求桥模板题

题目链接 

 

题解:

求桥模板题

需要按照顺序输出桥

代码:

#include 
#include <string.h>
#include 
#include 
#include
#include 
using namespace std;

const int maxn = 5010;//点数
const int maxm = 20010;//边数,因为是无向图,所以这个值要*2

struct Edge
{
    int to,next;
    bool cut;//是否是桥标记
} edge[maxm];
int head[maxn],tot;
int low[maxn],dfn[maxn],Stack[maxn],belong[maxn];//belong数组的值是1~scc
int Index,top;
int scc;//边双连通块数/强连通分量的个数
bool Instack[maxn];
int bridge;//桥的数目
bool cut[maxn];
void addedge(int u,int v)
{
    edge[tot].to = v;
    edge[tot].next = head[u];
    edge[tot].cut=false;
    head[u] = tot++;
}
void Tarjan(int u,int pre)
{
    int v;
    low[u] = dfn[u] = ++Index;
    Stack[top++] = u;
    Instack[u] = true;
    int son=0;
    for(int i = head[u]; i != -1; i = edge[i].next)
    {
        v = edge[i].to;
        if(v == pre)continue;
        if( !dfn[v] )
        {
            son++;
            Tarjan(v,u);
            if( low[u] > low[v] )low[u] = low[v];
            if(low[v] > dfn[u])
            {
                bridge++;
                edge[i].cut = true;
                edge[i^1].cut = true;
            }
            if(u == pre && son > 1)cut[u] = true;
            if(u != pre && low[v] >= dfn[u])cut[u] = true;

        }
        else if( Instack[v] && low[u] > dfn[v] )
            low[u] = dfn[v];
    }

    if(low[u] == dfn[u])
    {
        scc++;
        do
        {
            v = Stack[--top];
            Instack[v] = false;
            belong[v] = scc;
        }
        while( v!=u );
    }

}
void init()
{
    tot = 0;
    memset(head,-1,sizeof(head));
}
void solve(int n)
{
    memset(dfn,0,sizeof(dfn));
    memset(Instack,false,sizeof(Instack));
    memset(cut,0,sizeof cut);
    Index = top = scc = 0;
    bridge = 0;
     for(int i = 1; i <= n; i++)
        if(!dfn[i])
            Tarjan(i,i);
    printf("%d critical links\n",bridge);
    vectorint,int> >ans;
    for(int u=1; u<=n; u++)
    {
        for(int i=head[u]; i!=-1; i=edge[i].next)
        {
            if(edge[i].cut && edge[i].to>u)ans.push_back(make_pair(u,edge[i].to));//双向边只取一条边
        }
    }
    sort(ans.begin(),ans.end());
    for(int i=0; i)
    {
        printf("%d - %d\n",ans[i].first-1,ans[i].second-1);
    }
    printf("\n");

}
//处理重边
map<int,int>mapit;
inline bool isHash(int u,int v)
{
    if(mapit[u*maxn+v])return true;
    if(mapit[v*maxn+u])return true;
    mapit[u*maxn+v] = mapit[v*maxn+u] = 1;
    return false;
}
int g[105][105];
int main()
{
   int n;
    int u,v,m;
    while(~scanf("%d",&n))
    {
        init();
        for(int i=1;i<=n;i++)
        {
            scanf("%d (%d)",&u,&m);
            u++;
            for(int j=1;j<=m;j++)
            {
                scanf("%d",&v);
                v++;
                addedge(u,v);
                addedge(v,u);
            }
        }
        solve(n);
    }
    return 0;
}
/*
5
5 1 2 3 4
0
6
2 1 3
5 4 6 2
0
0
*/
View Code

 

你可能感兴趣的:(Critical Links——求桥模板题)