POJ 2553 The Bottom of a Graph 强连通分量

链接:http://poj.org/problem?id=2553

题意:题意读起来压力大,是找到自己能找到并且还能找到自己,并且在图的底部的点。

思路:找到出度为零的强连通分量,用Tarjan缩点。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cmath>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <ctype.h>
#include <algorithm>
#include <string>
#define PI acos(-1.0)
#define maxn 5500
#define INF 1<<25
#define MAX 0x7fffffff
#define mem(a,b) memset(a,b,sizeof(a))
#define f(i,a,b) for(i=a;i<b;i++)
typedef long long ll;
using namespace std;
struct Edge
{
    int v;
    int next;
} edge[maxn*maxn];
stack <int> S;
int head[maxn],dfn[maxn],low[maxn],ins[maxn],ou[maxn],belong[maxn];
int top,cnt,t,jud,to;
int init()
{
    mem(head,-1);
    mem(ins,0);
    mem(dfn,0);
    mem(low,0);
    mem(ou,0);
    mem(belong,0);
    top=t=cnt=jud=0;
}
int add_edge(int u,int v)
{
    edge[top].v=v;
    edge[top].next=head[u];
    head[u]=top++;
}
int tarjan(int u)
{
    dfn[u]=low[u]=cnt++;
    S.push(u);
    ins[u]=1;
    for(int i=head[u]; i!=-1; i=edge[i].next)
    {
        int v=edge[i].v;
        if(!dfn[v])
        {
            tarjan(v);
            low[u]=min(low[u],low[v]);
        }
        else if(dfn[v]<low[u]&&ins[v])
        {
            low[u]=dfn[v];
        }
    }
    if(dfn[u]==low[u])
    {
        t++;
        int to;
        do
        {
            to=S.top();
            S.pop();
            belong[to]=t;
            ins[to]=0;
        }
        while(to!=u);
    }
}
int main()
{
    int tot,tt;
    while(scanf("%d",&tot))
    {
        init();
        while(!S.empty())
        {
            S.pop();
        }
        if(!tot)
            return 0;
            scanf("%d",&tt);
        for(int i=1;i<=tt;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            add_edge(a,b);
        }
        for(int i=1; i<=tot; i++)
        {
            if(!dfn[i])
                tarjan(i);
        }

        for(int i=1;i<=tot;i++)
        for(int j=head[i]; j!=-1; j=edge[j].next)
        {
            int s=edge[j].v;
            if(belong[i]!=belong[s])
            {
                ou[belong[i]]++;
            }
        }
        for(int j=1;j<=tot;j++)
        {
            if(!ou[belong[j]])
            {
                if(!jud)
                {
                    printf("%d",j);
                    jud=1;
                }
                else printf(" %d",j);
            }
        }
        printf("\n");
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值