tarjan+缩点

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

#include <cstdio>
#include <cstring>
#include <iostream>
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();
  }
}
阅读更多
版权声明:转我原创记得说你是我的脑残粉哟 https://blog.csdn.net/zjy2015302395/article/details/52303864
个人分类: acm 基本算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭