1-n,共n个数字,初始时每个数都是独立的算作1个串,之后会进行n-1次合并,每次合并操作,会把一个串放到另一个串的后面。
合并时会给出2个数字,x y,表示将以y为开头的串放到x为开头的串的后面。例如:
1 3 (3放到1后面,=> (1 3), 2, 4 )
2 4 (4放到2后面,=> (1 3), (2 4))
1 2 (2放到1后面,=> (1 3 2 4))
在n - 1次合并后,按顺序输出最终剩下的这个串的全部数字。
输入
第1行:1个数n(2 <= n <= 10000)
后面n - 1行,每行2个数x y,对应n - 1次合并操作,把以y为开头的串放到以x为开头的串的末尾。
输出
输出共n行,每行1个数,对应最终串包含的n个数字。
输入样例
4
1 3
2 4
1 2
输出样例
1
3
2
4
题解:
这道题使用STL中的容器list就在好做不过了,首先定义n个单链表,分别的首元素就是1,2,3,…,n,然后输入n-1对x,y,题目的意思就是把以y开头这个链表整体的放到以x开头的链表后面,所以先遍历找到以y开头的单链表,记录下标y_index,然后找到以x开头的单链表,将以y开头的单链表的元素一个个放到以x开头的单链表后面,最后记得把以y开头的单链表清空,因为这个串已经放到x后面去了。
然后最后一次输入的x,就是唯一的一个串了,记录好下标,一次遍历输出元素即可。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e4+5;
int n;
list <int> List[MAX];
int main()
{
/*
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
*/
while(cin >> n)
{
for(int i = 1; i <= n; i++)
{
List[i].push_back(i);
}
// 将y为开头的整个串 放到以x开头的整个串的后面
// 初始:1,2,3,4
// 1 3 (1 3),2,4
// 2 4 (1 3),(2 4)
// 1 2 (1 3 2 4)
int x,y;
int last_x;
for(int i = 1; i <= n-1; i++)
{
cin >> x >> y;
int y_index;
for(int j = 1; j <= n; j++)
{
// 找到以y开头的串
if(List[j].front() == y)
{
y_index = j;
}
}
for(int j = 1; j <= n; j++)
{
// 找到以x开头的串
if(List[j].front() == x)
{
// 将y为开头的整个串 放到以x开头的整个串的后面
// 然后将y串删除
for(auto it = List[y_index].begin(); it != List[y_index].end(); it++)
{
List[j].push_back(*it);
}
List[y_index].clear();
}
}
if(i == n-1)
last_x = x;
}
for(auto it = List[last_x].begin(); it != List[last_x].end(); it++)
{
printf("%d\n",*it);
}
}
return 0;
}