#include using namespace std; typedef long long ll; typedef pair P; #define p_ary(ary,a,b) do { cout << "["; for (int count = (a);count < (b);++count) cout << ary[count] << ((b)-1 == count ? "" : ", "); cout << "]\n"; } while(0) #define p_map(map,it) do {cout << "{";for (auto (it) = map.begin();;++(it)) {if ((it) == map.end()) {cout << "}\n";break;}else cout << "" << (it)->first << "=>" << (it)->second << ", ";}}while(0) struct UnionFind { private: vector par,depth; public: UnionFind (int n) { par.resize(n); depth = vector(n,0); for (int i = 0;i < n;++i) par[i] = i; } int find(int x) { if (par[x] == x) return x; else return par[x] = find(par[x]); } void unite(int x,int y) { x = find(x); y = find(y); if (x == y) return; par[y] = x; if (depth[x] == depth[y]) depth[x]++; else depth[x] = max(depth[x],depth[y]); } bool same(int x,int y) { return find(x) == find(y); } }; int main() { int n,m; cin >> n; vector a(n),b(n); for (int i = 0;i < n;++i) cin >> a[i] >> b[i]; map mp; for (int i = 0;i < n;++i) mp[a[i]] = i; m = n; for (int i = 0;i < n;++i) if (mp.find(b[i]) == mp.end()) mp[b[i]] = m,m++; UnionFind uf(m); for (int i = 0;i < n;++i) uf.unite(mp[b[i]],mp[a[i]]); vector used(m,false); for (int i = 0;i < n;++i) if (uf.find(mp[b[i]]) == mp[b[i]] && !used[mp[b[i]]]) { cout << b[i] << "\n"; used[mp[b[i]]] = true; } }