poj 2762 Going from u to v or from v to u?
2014-04-22 18:59
337 查看
tarjan算法学习 https://www.byvoid.com/blog/scc-tarjan/
#include<iostream> #include<cstring> #include<cstdio> #define N 1010 #define M 6010 using namespace std; struct node{ int to,next; }edge[M]; int head ,tot; int dfn ,low ,stap ,belong ; bool instack ,mat ; int index,bcnt,top; int dg ; int n; void init() { tot=0; memset(head,-1,sizeof(head)); memset(dfn,0,sizeof(dfn)); memset(instack,false,sizeof(instack)); memset(mat,false,sizeof(mat)); index=top=bcnt=0; } void insert(int u,int v) { edge[tot].to=v; edge[tot].next=head[u]; head[u]=tot++; } void tarjan(int u) { dfn[u]=low[u]=++index; instack[u]=true; stap[++top]=u; for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].to; if(!dfn[v]) { tarjan(v); low[u]=min(low[u],low[v]); } else if(instack[v]&&dfn[v]<low[u]) low[u]=dfn[v]; } if(low[u]==dfn[u]) { int x; bcnt++; do{ x=stap[top--]; instack[x]=false; belong[x]=bcnt; }while(x!=u); } } void build() { for(int i=1;i<=n;i++) for(int j=head[i];j!=-1;j=edge[j].next) { int v=edge[j].to; mat[belong[i]][belong[v]]=true; } return; } /* void show() { for(int i=1;i<=bcnt;i++) { for(int j=1;j<=bcnt;j++) cout<<mat[i][j]<<" "; cout<<endl; } } */ bool toposort() { int i,j,k,pos,del; memset(dg,0,sizeof(dg)); for(i=1;i<=bcnt;i++) { for(j=1;j<=bcnt;j++) if(i!=j) dg[i]+=mat[j][i]; //cout<<dg[i]<<" "; } //cout<<endl; for(i=1;i<=bcnt;i++) { pos=0; del=0; for(j=1;j<=bcnt;j++) { if(dg[j]==0) { dg[j]=-1; del=j; pos++; } if(pos>1) return false; } if(pos==0) return false; for(k=1;k<=bcnt;k++) dg[k]-=mat[del][k]; } return true; } int main() { int t; int i; int u,v; int m; scanf("%d",&t); while(t--) { init(); scanf("%d%d",&n,&m); for(i=1;i<=m;i++) { scanf("%d%d",&u,&v); insert(u,v); } for(i=1;i<=n;i++) if(!dfn[i]) tarjan(i); if(bcnt==1) { printf("Yes\n"); continue; } build(); //show(); if(toposort()) printf("Yes\n"); else printf("No\n"); } return 0; }
相关文章推荐
- 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?
- 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+拓扑排序)
- [POJ 2762] 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?
- 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? 缩点
- poj 2762 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]&&(拓扑排序||树形DP))
- POJ 2762 Going from u to v or from v to u?
- POJ 2762 Going from u to v or 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?
- POJ 2762 Going from u to v or from v to u? 图的单连通性 tarjan or kosaraju