tarjan+缩点

之前有写过tarjan的模板,反正图论大大真是各种模板,比赛时候就不会,看出来也不会,看不出来更不会=。=,经常我们找到强连通分量之后不是数数个数就结束了,tarjan经常是帮别人一点而已,比如2-sat啊,桥啊,割点 啊什么的,这次只是简单的做了把连通块缩成一个点

#include 
#include 
#include 
using namespace std;
#define maxn 2010

int dfn[maxn],low[maxn],belong[maxn];
int instack[maxn],stack[maxn],top;
int n,ans,from[maxn],ANS;

struct node{
  int to;
  int next;
}edges[maxn*maxn/2];
int head[maxn];

void init(){
  memset(dfn,0,sizeof(dfn));
  memset(low,0,sizeof(low));
  memset(head,-1,sizeof(head));
  ans = 0;
  top = 0;
  memset(instack,0,sizeof(instack));
  memset(stack,0,sizeof(stack));
  for(int i =1 ; i <= n ;i++)
    belong[i] = i;
  int k = 0;
  for(int i = 1; i <= n; i++){
    while(1){
      int v;
      scanf("%d",&v);
      if(v == 0)
        break;
      edges[k].to = v;
      edges[k].next = head[i];
      head[i] = k++;
    }
  }
}

void tarjan(int u){
  int t;
  dfn[u] = low[u] = ++ans;
  instack[u] = 1;
  stack[top++] = u;
  for(int i = head[u] ; i != -1;i = edges[i].next){
    int j = edges[i].to;

    if(!dfn[j]){
      tarjan(j);
      low[u] = min (low[u],low[j]);
    }
    else if(instack[j])
      low[u] = min(low[u],dfn[j]);
  }

  if(dfn[u] == low[u]){
    do{
      t = stack[--top];
      instack[t] = 0;
      belong[t] = u;
    }while(t != u);
  }
}

void sov(){
  for(int i = 1; i <= n;i++)
      for(int k = head[i] ; k != -1;k = edges[k].next){
        int j = edges[k].to;
        if(belong[j] != belong[i])
          from[belong[j]] = belong[i];
      }
  int flag = 0;
  for(int i = 1; i <= n ;i++)
    if(belong[i] == i && from[i] == i){
      ANS = i;
      flag ++;
      if(flag >= 2)
        break;
    }
  if(flag == 1)
  for(int i =1 ; i<= n ;i++)
    if(belong[i] == ANS )
      printf("%d ",i);
  printf("0\n");
}


int main(){

  while(scanf("%d",&n) != EOF){
    init();
    for(int i = 1; i <= n ;i++)
      if(!dfn[i]) tarjan(i);

    for(int i =1 ; i <= n ;i++)
      from[i] = i;
    ANS = 0;
    sov();
  }
}

你可能感兴趣的:(acm,基本算法)