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.
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 ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi 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.
Print a sequence of n integers x1, x2, ..., xn — 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.
4 92 31 0 7 31 0 7 141
92 7 31 141
The picture illustrates the queue for the first sample.
这几天写代码写懵了....
思路:建立一个向后的链和向前的链。用向后的链,从0开始扫一遍,可以得到排在偶数位的。然后随便找一个没出现过的号,用向前的链跟踪到头,就是排在第一位的,再用向后的链扫一遍,得到排在奇数位的。
其实这思路是借鉴学长的,感觉有点像之前做过的并查集.....留给以后再说吧
AC代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int data1[1000010], data2[1000010], vis[1000010], ans[200010];
int main()
{
int n;
scanf("%d", &n);
memset(data1, -1, sizeof(data1));
memset(data2, -1, sizeof(data2));
memset(vis, 0, sizeof(vis));
for(int i=1; i<=n; i++)
{
int a, b;
scanf("%d %d", &a, &b);
data1[a] = b;
data2[b] = a;
vis[a] = 1;
vis[b] = 1;
}
int tmp=0, k=2;
while(1)
{
ans[k] = data1[tmp];
vis[ans[k]] = 0;
k+=2;
tmp = data1[tmp];
if(tmp<=0)break;
}
int found;
for(int i=1; i<=1000000; i++)
{
if(vis[i])
{
found = i; break;
}
}
tmp = found;
while(1)
{
if(data2[tmp]<0)break;
tmp = data2[tmp];
}
k = 1;
while(1)
{
ans[k] = tmp;
tmp = data1[tmp];
k+=2;
if(tmp<=0) break;
}
int i;
for(i=1; i<n; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[i]);
return 0;
}