强连通分量 学习记录

来源:互联网 发布:wlan办理软件下载 编辑:程序博客网 时间:2024/06/05 11:53

HDU1269

#include<bits/stdc++.h>#define MEM(a,x) memset(a,x,sizeof(a));#define MEMINF(a) memset(a,0x3f,sizeof(a));using namespace std;typedef long long LL;const int MAXN=1e4+5;const int MAXM=1e5+5;const int INF=0x3f3f3f3f;const int MOD=1000000007;struct Edge{  int u,v,next;}edge[MAXM];int dfn[MAXN],low[MAXN],col[MAXN],s[MAXN],be[MAXN],head[MAXN];int m,n,top=0,cnt=0,ans=0,times=0,t=0;void Addedge(int u,int v) {  edge[++top].u=u,edge[top].v=v;  edge[top].next=head[u],head[u]=top;}void init() {  top=0,cnt=0,ans=0,times=0,t=0;  MEM(dfn,0);  MEM(low,0);  MEM(col,0);  MEM(be,0);  MEM(head,0);}void Tarjan(int u) {  int v,i;  times++,t++;  dfn[u]=low[u]=times;  col[u]=1,s[t]=u;  for (int i=head[u]; i; i=edge[i].next) {    v=edge[i].v;    if (col[v]==0) {      Tarjan(v);      low[u]=min(low[u],low[v]);    }    if (col[v]==1) {      low[u]=min(low[u],dfn[v]);    }  }  if (dfn[u]==low[u]) {    cnt++;    do {      v=s[t--];      be[v]=cnt;      col[v]=2;    }    while (v!=u);  }}int main() {  while (~scanf("%d %d",&n,&m)) {    init();    if (n==0&&m==0) break;    while (m--) {      int u,v;      scanf("%d %d",&u,&v);      Addedge(u,v);    }    for (int i=1; i<=n; ++i) {      if (col[i]==0) Tarjan(i);    }    if (cnt>=2) puts("No");    else puts("Yes");  }}
POJ2186

#include <cstdio>#include <cstring>#include <algorithm>#define MEM(a,x) memset(a,x,sizeof(a));#define MEMINF(a) memset(a,0x3f,sizeof(a));using namespace std;typedef long long LL;const int MAXN=2e5+10;const int MAXM=5e5+10;const int INF=0x3f3f3f3f;const int MOD=1000000007;int head[MAXN],inst[MAXN],dfn[MAXN],low[MAXN],deg[MAXN],be[MAXN],st[MAXM];int tot,cnt,top,deep;struct Edge{  int u,v,next;}edge[MAXM]; void init() {  tot=top=cnt=deep=0;  MEM(head,-1);  MEM(deg,0);  MEM(dfn,0);  MEM(inst,0);}void Addedge(int u,int v) {  edge[top].v=v,edge[top].u=u,edge[top].next=head[u],head[u]=top++;}void Tarjan(int u) {  inst[u]=1;  st[tot++]=u;  dfn[u]=low[u]=++deep;  for (int i=head[u]; ~i; i=edge[i].next) {    int v=edge[i].v;    if (!dfn[v]) {      Tarjan(v);      low[u]=min(low[u],low[v]);    } else if (inst[v]) {      low[u]=min(low[u],dfn[v]);    }  }  if (low[u]==dfn[u]) {    int v;    cnt++;    do {      v=st[--tot];      inst[v]=0;      be[v]=cnt;    } while (u!=v) ;  }}int main() {  int n,m;  scanf("%d %d",&n,&m);  init();  int u,v;  for (int i=0; i<m; ++i) {    scanf("%d %d",&u,&v);    Addedge(u,v);  }  for (int i=1; i<=n; ++i) {    if (!dfn[i]) Tarjan(i);  }  for (int i=1; i<=n; ++i) {    for (int j=head[i]; ~j; j=edge[j].next) {      int v=edge[j].v;      if (be[v]!=be[i]) {        deg[be[i]]++;        break;      }    }  }  int ans=0,num=0,pos;  for (int i=1; i<=cnt; ++i) {    if (deg[i]==0) {      num++,pos=i;    }  }  if (num==1 ) {    for (int i=1; i<=n; ++i) {      if (be[i]==pos) ans++;    }    printf("%d\n",ans);  }  else puts("0");}    


0 0
原创粉丝点击