【POJ 2762】Going from u to v or from u ? (Tarjan + 拓扑排序)
2017-08-20 20:16
465 查看
传送门
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; }
相关文章推荐
- POJ 2762 Going from u to v or from v to u?(Tarjan + 拓扑排序)
- Going from u to v or from v to u? - POJ 2762 Tarjan+拓扑排序
- POJ-2762 Going from u to v or from v to u? (强连通分量[Tarjan]&&(拓扑排序||树形DP))
- poj 2762 Going from u to v or from v to u? 【判断图是否为弱连通】 【tarjan求SCC + 缩点 + 拓扑排序】
- POJ2762 Going from u to v or from v to u? 强连通 Tarjan缩点+拓扑排序topsort
- poj 2762 Going from u to v or from v to u?(缩点+拓扑排序)
- POJ - 2762 Going from u to v or from v to u? (Tarjan 缩点)
- poj 2762 Going from u to v or from v to u? 【 强连通 拓扑排序】
- POJ 2762 Going from u to v or from v to u? Tarjan缩点+判断链
- poj2762 Going from u to v or from v to u? 有向图 强连通分量 拓扑排序
- poj 2762 Going from u to v or v to u (tarjan+缩点+dfs搜索)
- [练习][poj2762]tarjan缩点 Going from u to v or from v to u?
- [ tarjan + dfs ] poj 2762 Going from u to v or from v to u?
- POJ 2762 Going from u to v or from v to u?(强联通,拓扑排序)
- poj2762 Going from u to v or from v to u? 强连通分量 + 拓扑排序
- POJ 2762【强联通缩点】【拓扑排序】Going from u to v or from v to u?
- POJ 2762 Going from u to v or from v to u? (图论-tarjan)
- [ tarjan + dfs ] poj 2762 Going from u to v or from v to u?
- POJ 2762 Going from u to v or from v to u? (图论-tarjan)
- POJ 2762 Going from u to v or from v to u?(Tarjan)