[dfs树] Codeforces 521E #295 (Div. 1) E. Cycling City

这个东西啊 题解里讲的太复杂了 直接发现充要条件的两个环有公共部分 那么我们瞎JB dfs以下就好了

但是 这个东西啊 输方案真是蛋疼 我弄来弄去搞了好久 就是写不出优雅的代码


#include  
#include  
#include  
#include  
#define cl(x) memset(x,0,sizeof(x))  
using namespace std;  
  
inline char nc(){  
  static char buf[100000],*p1=buf,*p2=buf;  
  if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }  
  return *p1++;  
}  
  
inline void read(int &x){  
  char c=nc(),b=1;  
  for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;  
  for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;  
}  
  
const int N=200005;  
  
struct edge{  
  int u,v,next;  
}G[N<<1];  
int head[N],inum=1;  
  
inline void add(int u,int v,int p){  
  G[p].u=u; G[p].v=v; G[p].next=head[u]; head[u]=p;  
}

int n,m;
int au,av,flag;
int depth[N],fat[N],tag[N];
#define V G[p].v

int sta[N];

inline void dfs(int u,int fa){
  sta[++*sta]=u;
  for (int p=head[u];p;p=G[p].next)
    if (p!=(fa^1)){
      if (!depth[V])
	fat[V]=u,depth[V]=depth[u]+1,dfs(V,p),tag[u]+=tag[V];
      else if (depth[V]=2)
    flag=1,au=G[fa].u,av=G[fa].v;
}

int instack[N];
int cir1,cir2;
int lst1[N],lst2[N];
int in1[N],in2[N];

inline void find(int u,int fa){
  instack[u]=1;
  for (int p=head[u];p;p=G[p].next)
    if (p!=(fa^1)){
      if (!depth[V])
	depth[V]=depth[u]+1,find(V,p);
      else if (depth[V]=depth[V]) in1[t]=1,lst1[++*lst1]=t,t=fat[t];
	  }
	  else if (!cir2){
	    cir2=p;
	    int t=u; while (depth[t]>=depth[V]) in2[t]=1,lst2[++*lst2]=t,t=fat[t];
	  }
	}
      }
    }
  instack[u]=0;
}

int pnt,lst[N];

inline void Print(){
  printf("%d",pnt);
  for (int i=1;i<=pnt;i++)
    printf(" %d",lst[i]);
  printf("\n");
}

int main(){
  int iu,iv;
  int u1,v1,u2,v2;
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  read(n); read(m);
  for (int i=1;i<=m;i++)
    read(iu),read(iv),add(iu,iv,++inum),add(iv,iu,++inum);
  for (int r=1;r<=n;r++)
    if (!depth[r]){
      *sta=0; *lst1=0; *lst2=0; cir1=0; cir2=0; flag=0;
      depth[r]=1;
      dfs(r,0);
      if (!flag)
	continue;
      for (int i=1;i<=*sta;i++) depth[sta[i]]=0; depth[r]=1;
      find(r,0);
      au=0,av=0;
      for (int i=1;i<=*sta;i++)
	if (in1[sta[i]] && in2[sta[i]]){
	  if (!au || depth[au]>depth[sta[i]])
	    au=sta[i];
	  if (!av || depth[av]=depth[au];i=fat[i]) lst[++pnt]=i;
      Print();
      int pos1,pos2;
  
      for (int i=1;i<=*lst1;i++)
	if (lst1[i]==au) pos1=i; else if (lst1[i]==av) pos2=i;
      pnt=0;
      for (int i=pos2;i!=pos1;i=i==1?*lst1:i-1)
	lst[++pnt]=lst1[i];
      lst[++pnt]=lst1[pos1];
      Print();
  
      for (int i=1;i<=*lst2;i++)
	if (lst2[i]==au) pos1=i; else if (lst2[i]==av) pos2=i;
      pnt=0;
      for (int i=pos2;i!=pos1;i=i==1?*lst2:i-1)
	lst[++pnt]=lst2[i];
      lst[++pnt]=lst2[pos1];
      Print();
      return 0;
    }
  printf("NO\n");
  return 0;
}


你可能感兴趣的:(dfs树)