poj 2762 Going from u to v or from v to u?

来源:互联网 发布:视频特效制作软件 编辑:程序博客网 时间:2024/05/17 06:24

tarjan算法学习 https://www.byvoid.com/blog/scc-tarjan/

#include<iostream>#include<cstring>#include<cstdio>#define N 1010#define M 6010using namespace std;struct node{int to,next;}edge[M];int head[N],tot;int dfn[N],low[N],stap[N],belong[N];bool instack[N],mat[N][N];int index,bcnt,top;int dg[N];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");elseprintf("No\n");}return 0;}


0 0
原创粉丝点击