UVA796 Critical Links(无向图求桥模板)

https://www.luogu.com.cn/problem/UVA796


注意一下每组结束都有额外的endl;另外0的时候不是停止;对桥排序。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=200;
typedef long long LL;
vector<LL>g[maxn];
LL dfn[maxn],low[maxn],fa[maxn],times=0,cnt=0;
struct bridge{
  LL x,y;
}bridges[maxn];
bool cmp(bridge A,bridge B)
{
    if(A.x==B.x) return A.y<B.y;
    return A.x<B.x;
}
void tarjan2(LL x)
{
    dfn[x]=low[x]=++times;
    LL child=0;
    for(LL i=0;i<g[x].size();i++)
    {
        LL to=g[x][i];
        if(!dfn[to])
        {
            child++;fa[to]=x;
            tarjan2(to);
            //if(-1==fa[x]&&child>=2)
            //if(-1!=fa[x]&&low[to]>=dfn[x])
            if(low[to]>dfn[x])
            {
                bridges[++cnt].x=min(x,to);bridges[cnt].y=max(x,to);
            }
            low[x]=min(low[x],low[to]);
        }
        else if(to!=fa[x]) low[x]=min(low[x],dfn[to]);
    }
}
int main(void)
{
  //cin.tie(0);std::ios::sync_with_stdio(false);
  LL n;
  while(cin>>n)
  {
        memset(dfn,0,sizeof(dfn));memset(low,0,sizeof(low));memset(fa,-1,sizeof(fa));
        for(LL i=0;i<maxn;i++) g[i].clear();
        times=0;cnt=0;
        char op1,op2;LL num,k;
        for(LL i=1;i<=n;i++)
        {
            cin>>num>>op1>>k>>op2;
            num++;
            for(LL j=1;j<=k;j++)
            {
                LL x;cin>>x;x++;
                g[num].push_back(x);g[x].push_back(num);
            }
        }
        for(LL i=1;i<=n;i++) if(!dfn[i]) tarjan2(i);
        sort(bridges+1,bridges+cnt+1,cmp);
        cout<<cnt<<" critical links"<<endl;
        for(LL i=1;i<=cnt;i++)
        {
            cout<<bridges[i].x-1<<" - "<<bridges[i].y-1<<endl;
        }
        cout<<endl;
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/108888947