标签:des style http color java os strong io
3 3 1 2 2 3 3 1 3 3 1 2 2 3 3 2 0 0
Yes No
模拟栈写的tarjan算法:
#include"stdio.h" #include"string.h" #include"queue" #include"vector" #include"stack" #include"algorithm" using namespace std; #define N 10005 #define min(a,b) (a<b?a:b) int n,t,stop,bcnt,index; int dfn[N],instack[N],head[N]; int low[N],stap[N],belong[N]; int ans; struct node { int u,v,next; }e[N*10]; void add(int u,int v) //邻接表存边 { e[t].u=u; e[t].v=v; e[t].next=head[u]; head[u]=t++; } void tarjan(int i) { int j,t; dfn[i]=low[i]=++index; //Low(u)为u或u的子树能够追溯到的最早的栈中节点的次序号 instack[i]=true; //模拟栈的存储方式,代表节点i入栈(标记) stap[++stop]=i; //stop指向栈顶元素,stap记录栈内元素 for(t=head[i];t!=-1;t=e[t].next) { j=e[t].v; if(!dfn[j]) { tarjan(j); low[i]=min(low[i],low[j]); } else if(instack[j]) low[i]=min(low[i],dfn[j]); } if(dfn[i]==low[i]) { bcnt++; do { j=stap[stop--]; //取栈顶元素 instack[j]=false; //出栈 belong[j]=bcnt; //记录该强连通分量的代号 } while(j!=i); ans++; } } void solve() { int i; stop=bcnt=index=0; memset(dfn,0,sizeof(dfn)); //定义DFN(u)为节点u搜索的次序编号(时间戳) for(i=1;i<=n;i++) { if(!dfn[i]) tarjan(i); } } int main() { int i,u,v,m; while(scanf("%d%d",&n,&m),n||m) { memset(head,-1,sizeof(head)); t=0; ans=0; for(i=0;i<m;i++) { scanf("%d%d",&u,&v); add(u,v); } solve(); if(ans==1) printf("Yes\n"); else printf("No\n"); } return 0; }
#include"stdio.h" #include"string.h" #include"queue" #include"vector" #include"stack" #include"algorithm" using namespace std; #define N 10005 #define min(a,b) (a<b?a:b) int t,n,index,ans; int head[N],instack[N]; int dfn[N],low[N]; struct node { int u,v,next; }e[N*10]; void add(int u,int v) { e[t].u=u; e[t].v=v; e[t].next=head[u]; head[u]=t++; } void tarjan(int u) { int i,v; stack<int>s; s.push(u); dfn[u]=low[u]=index++; instack[u]=true; for(i=head[u];i!=-1;i=e[i].next) { v=e[i].v; if(!dfn[v]) { tarjan(v); low[u]=min(low[u],low[v]); } else if(instack[v]) low[u]=min(low[u],dfn[v]); } if(low[u]==dfn[u]) { while(u!=v) { v=s.top(); s.pop(); } ans++; } } void solve() { int i; memset(dfn,0,sizeof(dfn)); index=1; for(i=1;i<=n;i++) { if(!dfn[i]) tarjan(i); } } int main() { int u,v,m; while(scanf("%d%d",&n,&m),n||m) { memset(head,-1,sizeof(head)); ans=t=0; while(m--) { scanf("%d%d",&u,&v); add(u,v); } solve(); if(ans==1) printf("Yes\n"); else printf("No\n"); } return 0; }
hdu 1269 迷宫城堡 (tarjan算法学习),布布扣,bubuko.com
标签:des style http color java os strong io
原文地址:http://blog.csdn.net/u011721440/article/details/38356969