poj 2553 The Bottom of a Graph (强联通分量+缩点)

题目意思大概是要求输出这样的点u满足:对于任意一个v,如果u可以到达v,并且v也可以到达u。
做法:求出缩点以后满足出度为0的点,然后输出这个点的所有内点。
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define B(x) (1<<(x))
typedef long long ll;
void cmax(int& a,int b){ if(b>a)a=b; }
void cmin(int& a,int b){ if(b<a)a=b; }
const int oo=0x3f3f3f3f;
const int MOD=1000000007;
const int maxn=5100;
const int maxm=26000000;
struct EDGE{
    int v,next,c,f;
}E[maxm];
int head[maxn],tol;
int low[maxn],dfn[maxn],instack[maxn],Stack[maxn],id[maxn];
int d[maxn];
int g_cnt,top,ID;
int ans[maxn];
struct Node{
    int n;
    Node(int x){ n=x; }
    bool operator<(const Node& a)const{
        return a.n<n;
    }
};

void Init(){
    memset(head,-1,sizeof head);
    tol=0;
    memset(low,0,sizeof low);
    memset(dfn,0,sizeof dfn);
    memset(instack,0,sizeof instack);
    g_cnt=top=ID=0;
}

void add_edge(int u,int v){
    E[tol].v=v;
    E[tol].next=head[u];
    head[u]=tol++;
}

void Tarjan(int u){
    dfn[u]=low[u]=++g_cnt;
    Stack[++top]=u;
    instack[u]=1;
    int v;
    for(int i=head[u];i!=-1;i=E[i].next){
        v=E[i].v;
        if(!dfn[v]){
            Tarjan(v);
            if(low[v]<low[u])
                low[u]=low[v];
        }else if(instack[v]&&dfn[v]<low[u])
            low[u]=dfn[v];
    }
    if(dfn[u]==low[u]){
        ID++;
        do{
            v=Stack[top--];
            instack[v]=0;
            id[v]=ID;
        }while(u!=v);
    }
}

void gao(int n){
    memset(d,0,sizeof d);
    for(int i=1;i<=n;i++){
        int u=i;
        for(int j=head[u];j!=-1;j=E[j].next){
            int v=E[j].v;
            if(id[u]!=id[v]){
                d[id[u]]++;
            }
        }
    }
    int cnt=0;
    for(int i=1;i<=n;i++){
        if(d[id[i]]==0)
            ans[cnt++]=i;
    }
    for(int i=0;i<cnt;i++)
        printf("%d%c",ans[i],i==cnt-1?'\n':' ');
}

int main(){
    //freopen("E:\\read.txt","r",stdin);
    int n,m,u,v,k;
    while(scanf("%d",&n)!=EOF){
        if(n==0)break;
        scanf("%d",&m);
        Init();
        for(int i=1;i<=m;i++){
            scanf("%d %d",&u,&v);
            add_edge(u,v);
        }
        for(int i=1;i<=n;i++)
            if(!dfn[i])
                Tarjan(i);
        gao(n);
    }
    return 0;
}
/*
4
2 1 2
2 1 2
2 2 3
2 3 4
1 2 3 4
*/


题目意思大概是要求输出这样的点u满足:对于任意一个v,如果u可以到达v,并且v也可以到达u。
做法:求出缩点以后满足出度为0的点,然后输出这个点的所有内点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值