fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. using ll = long long;
  5.  
  6. int main() {
  7. ios::sync_with_stdio(false);
  8. cin.tie(nullptr);
  9.  
  10. ll n, q;
  11. cin >> n >> q;
  12.  
  13. vector<ll> pigeon_loc(n); // For each pigeon, the current logical nest it is in
  14. vector<ll> nest_map(n); // For each logical nest, the physical nest it points to
  15. vector<ll> reverse_map(n); // For each physical nest, the logical nest it points to
  16.  
  17. for (ll i = 0; i < n; ++i) {
  18. pigeon_loc[i] = i;
  19. nest_map[i] = i;
  20. reverse_map[i] = i;
  21. }
  22.  
  23. while (q--) {
  24. ll op, a, b;
  25. cin >> op;
  26.  
  27. if (op == 1) {
  28. cin >> a >> b;
  29. a--; b--;
  30. // Move pigeon a from current logical nest to logical nest b
  31. pigeon_loc[a] = b;
  32. } else if (op == 2) {
  33. cin >> a >> b;
  34. a--; b--;
  35. // Swap logical nests a and b by swapping nest_map[a] and nest_map[b]
  36. swap(nest_map[a], nest_map[b]);
  37. // Update reverse_map to reflect the new mapping
  38. reverse_map[nest_map[a]] = a;
  39. reverse_map[nest_map[b]] = b;
  40. } else if (op == 3) {
  41. cin >> a;
  42. a--;
  43. // The current physical nest of pigeon a is nest_map[pigeon_loc[a]]
  44. cout << nest_map[pigeon_loc[a]] + 1 << '\n';
  45. }
  46. }
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5288KB
stdin
5 4
2 2 5
2 1 2
2 4 1
3 5
stdout
2