JZ初中OJ 2293. [noip普及组1]深水旅店

题目描述

一共有N个人在排队,他们都有自己的编号,保证编号大于0且小于2000001,
每个人都有自己前面和后面人的编号,如果他前面或后面没人,则会用 0 代替,
一共只有一条拿酒的队伍。
 

输入

第一行一个整数 N 表示人的个数
接下来 N 行表示每个人记下的编号
保证每个人的标号不同

输出

一行 N 个数,中间用空格隔开,表示这个编号。
 

样例输入

【样例输入 1】
4
92 31
0 7
31 0
7 141
【样例输入 2】
5
0 1
1 4
4 0
3 2
5 3

样例输出

【样例输出 1】
92 7 31 141
【样例输出 2】
5 1 3 4 2
 

数据范围限制

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=2100000;
 4 bool sf[maxn];
 5 int n,x,y,a[maxn],all,next[maxn],last[maxn],first1,first2;
 6 int main()
 7 {
 8     freopen("hotel.in","r",stdin);
 9     freopen("hotel.out","w",stdout);
10     sf[0]=1;
11     memset(last,-1,sizeof(last));
12     cin>>n;
13     for(int i=1;i<=n;i++)
14     {
15         scanf("%d%d",&x,&y);
16         next[x]=y;
17         last[y]=x;
18         if(x==0)
19             first2=y;
20         if(sf[x]==0)
21         {
22             a[++all]=x;
23             sf[x]=1;
24         }
25         if(sf[y]==0)
26         {
27             a[++all]=y;
28             sf[y]=1;
29         }
30     }
31     for(int i=1;i<=all;i++)
32         if(last[a[i]]==-1)
33             first1=a[i];
34     for(int i=1;i<=n/2;i++)
35     {
36         cout<<first1<<" "<<first2<<" ";
37         first1=next[first1];
38         first2=next[first2];
39     }
40     if(n%2==1) cout<<first1;
41     return 0;
42 }

猜你喜欢

转载自www.cnblogs.com/anbujingying/p/11317271.html