【LightOJ】 - 1026(tarjan算法求桥,模板问题)

题目链接:

http://lightoj.com/login_main.php?url=volume_showproblem.php?problem=1026

题目链接:就是给一个具有N个点的图,下面的输入还是比较花哨的,但是没什么关系的,有N条,

思路:找到桥之后,这里我用一个PAIR存储的,剩下的基本上就是tarjan算法了

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
const int maxn=3e5+5;
const int N=1e4+5;


int head[N], nxt[maxn], pnt[maxn], eban[maxn], txt;
int n;
int dfn[N], low[N], instack[N];
int dex,cnt;
stack<int>sta;
pair<int, int>ans[maxn];
void Add_edge(int u,int v)
{
    pnt[txt]=v;
    nxt[txt]=head[u];
    head[u]=txt++;
}

void Tarjan(int u)
{
    sta.push(u);
    low[u] = dfn[u] = ++dex;
    instack[u] = 1;
    for (int i = head[u]; ~i; i = nxt[i])
    {
        if (eban[i])
            continue;
        eban[i] = eban[i^1] = 1;
        int v = pnt[i];
        if (!dfn[v])
        {
            Tarjan(v);
            low[u] = min(low[u], low[v]);
//			if (low[v] > dfn[u])// 桥
//				ans[++cnt] = make_pair(min(u,v), max(u,v));
        }
        else if (instack[v])
            low[u] = min(low[u], dfn[v]);
        if (low[v] > dfn[u])// 桥
            ans[++cnt] = make_pair(min(u,v), max(u,v));
    }
    if (dfn[u] == low[u])
    {
        while (1)
        {
            int v = sta.top();
            sta.pop();
            instack[v] = 0;
            if (v == u)
                break;
        }
    }
}

int main()
{
    int T,u,v,t,kase=0;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        memset(head,-1,sizeof(head));
        txt=0;
        for(int i=1; i<=n; i++)
        {
            scanf("%d (%d)",&u,&t);
            while(t--)
            {
                scanf("%d",&v);
                if (v > u)
                {
                    Add_edge(u, v);
                    Add_edge(v, u);
                }
            }
        }
        memset(dfn,0,sizeof(dfn));
        memset(low,0,sizeof(low));
        memset(instack,0,sizeof(instack));
        memset(eban,0,sizeof(eban));
        while (!sta.empty())
            sta.pop();
        dex = cnt = 0;
        for (int i = 0; i < n; i++)
            if (!dfn[i])
                Tarjan(i);
        printf("Case %d:\n", ++kase);
        printf("%d critical links\n", cnt);
        sort(ans+1, ans+1+cnt);
        for (int i = 1; i <= cnt; i++)
            cout << ans[i].first << " - " << ans[i].second << endl;

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值