fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int n;
  5. const int N = 1e5 + 5;
  6. int p[N], parent[N];
  7.  
  8. void make_set(){
  9. // Đặt nút "cha" của mỗi tập hợp là chính nó
  10. for (int i = 1; i <= n; i++) parent[i] = i;
  11. }
  12.  
  13. int find(int x){
  14. // Ta sử dụng kĩ thuật nén đường đi để tối ưu
  15. if (x == parent[x]) return x;
  16. int p = find(parent[x]);
  17. parent[x] = p;
  18. return p;
  19. }
  20.  
  21. // Ở bài toán này thì không cần thao tác Set Union
  22.  
  23. void input(){
  24. cin >> n;
  25. make_set();
  26. for (int i = 1; i <= n; i++) cin >> p[i];
  27. }
  28.  
  29. void solve(){
  30. for (int i = 1; i <= n; i++){
  31. // Tìm vị trí thích hợp
  32. int pos = find(p[i]);
  33.  
  34. cout << pos << " ";
  35. // Cập nhật lại thành vị trí khác phù hợp
  36. parent[pos] = parent[pos % n + 1];
  37. }
  38. }
  39.  
  40. int main(){
  41. input();
  42. solve();
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 5324KB
stdin
3
2 2 2
stdout
2 3 1