B. Queue
阅读原文时间:2023年07月10日阅读:2

During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break
and it temporarily stopped working.

Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands
before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated
from 1).

After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.

Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.

Input

The first line contains integer n (2 ≤ n ≤ 2·105)
— the number of students in the queue.

Then n lines follow, i-th line contains the pair
of integers a__i, b__i (0 ≤ a__i, b__i ≤ 106),
where a__i is
the ID number of a person in front of a student and b__i is
the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't
exist.

The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.

Output

Print a sequence of n integers x_1, _x_2, …, _x__n —
the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.

Sample test(s)

input

4
92 31
0 7
31 0
7 141

output

92 7 31 141

这道题错了很久,不是wa,re就是te,最后发现是数组开小了。。。这题先记录每个数的前面和后面分别是谁,分两种情况讨论,一种总数是偶数,那么只要找到0,然后从0向前循环一遍,向后循环一遍就行了,如果是奇数,那么除了0向后循环一遍外,还要找到除0外的最后一个数,然后再向前循环一遍。

#include

#include

#define count 1000005

int next[count],pre[count],c[count],vis[count],a[count],b[count];

int main()

{
int n,m,i,j,t,u;
while(scanf("%d",&n)!=EOF)
{
memset(next,-1,sizeof(next));memset(pre,-1,sizeof(pre));memset(c,0,sizeof(c));
memset(vis,0,sizeof(vis));memset(a,0,sizeof(a));memset(b,0,sizeof(b));
if(n==2){
for(i=1;i<=n;i++){ scanf("%d%d",&a[i],&b[i]); if(a[i]==0){ c[1]=b[i]; } else if(b[i]==0){ c[0]=a[i]; } }    printf("%d %d\n",c[0],c[1]); continue; } for(i=1;i<=n;i++){ scanf("%d%d",&a[i],&b[i]); next[a[i]]=b[i]; pre[b[i]]=a[i]; } if(n%2==0){  t=1;  for(i=next[0];i!=-1 && t=0;i=pre[i]){
c[t]=i;t=t-2;
 }
}

if(n%2!=0){
 t=1;
 for(i=next[0];i!=-1 && t<n;i=next[i]){
c[t]=i;t=t+2;vis[i]=1;
 }
 u=-1;
 for(i=1;i<=n;i++){

  if(vis[a[i]]==0 && a[i]!=0){
  u=a[i];break;
}

   }

   while(next[u]!=-1){

    u=next[u];

   }

   t=n-1;

   for(i=u;i!=-1 && t>=0;i=pre[i]){

  c[t]=i;t=t-2;

  }
 
}

for(i=0;i<n;i++){
if(i!=n-1){
printf("%d ",c[i]);
}
else printf("%d\n",c[i]);
}
}
return 0;

}