【POJ 2762】Going from u to v or from u ? (Tarjan + 拓扑排序)

传送门

    Going from u to v or from u ?
    题意:给出一张图,判断任意点对(x,y)是否能够从x走到y 或者 从y走到x。

I think

    先用tarjan求强连通分量缩点。然后拓扑排序检查是否存在1个以上的点入度为0,若是,则不满足条件。

Code

#include<cstdio>
const int sm = 1e3+5;
const int sn = 6e3+5;

int T,N,M,tot,cnt,Bcnt;
int to[sn],nxt[sn],hd[sm];
int _to[sn],_nxt[sn],_hd[sm];
int Bn[sm],Lw[sm];
int top,instk[sm],stk[sm];
int Blg[sm],Rd[sm];

void read(int &x) {
    char ch=getchar();x=0;
    while(ch>'9'||ch<'0') ch=getchar();
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
}
int Min(int x,int y) { return x<y?x:y; }

void Add(int u,int v) {
    to[++tot]=v,nxt[tot]=hd[u],hd[u]=tot;
}
void Ins(int u,int v) {
    _to[++tot]=v,_nxt[tot]=_hd[u],_hd[u]=tot,Rd[v]++;
}
void Tarjan(int x) {
    int j;
    Bn[x]=Lw[x]=++cnt;
    instk[x]=true,stk[++top]=x;
    for(int i=hd[x];i;i=nxt[i]) {
        j=to[i];
        if(!Bn[j]) {
            Tarjan(j);
            Lw[x]=Min(Lw[x],Lw[j]);
        } 
        else if(instk[j]&&Lw[j]<Lw[x])
            Lw[x]=Lw[j];
    }
    if(Lw[x]==Bn[x]){ 
        ++Bcnt;
        do{
            j=stk[top--];
            instk[j]=false;
            Blg[j]=Bcnt;
        }while(j!=x);
    }
}
bool Topsort() {
    int t;top=0;
    for(int i=1;i<=Bcnt;++i)
        if(Rd[i]==0)
            stk[++top]=i;
    while(top) {
        t=stk[top--]; 
        if(top) return false;
        for(int i=_hd[t];i;i=_nxt[i]) {
            Rd[_to[i]]--;
            if(Rd[_to[i]]==0) 
                stk[++top]=_to[i];
        }
    }
    return true;
}
int main() {
    int u[sn],v[sn]; bool flag;
    read(T);
    while(T--) {
        read(N),read(M);

        tot=cnt=Bcnt=top=0;
        for(int i=1;i<=N;++i) 
            Rd[i]=Bn[i]=_hd[i]=hd[i]=instk[i]=0;

        for(int i=1;i<=M;++i) {
            read(u[i]),read(v[i]);
            Add(u[i],v[i]);
        }
        for(int i=1;i<=N;++i) 
            if(!Bn[i]) Tarjan(i);

        tot=0;
        for(int i=1;i<=M;++i) 
            if(Blg[u[i]]!=Blg[v[i]])
                Ins(Blg[u[i]],Blg[v[i]]);

        flag=Topsort();
        puts(flag?"Yes":"No");      
    }
    return 0;   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值