Iamtui1010

shhv.cpp

Feb 18th, 2022
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<algorithm>
  4. #include<vector>
  5.  
  6. #define long long long
  7. #define nln '\n'
  8.  
  9. using namespace std;
  10.  
  11. long factorial(long n)
  12. {
  13.     if (n <= 1)
  14.         return 1;
  15.     return factorial(n-1)*n;
  16. }
  17.  
  18. void transform(vector<long> &a)
  19. {
  20.     vector<pair<long, long>> b;
  21.     for (long i = 0; i < (long)a.size(); ++i)
  22.         b.push_back({a[i], i+1});
  23.     sort(b.begin(), b.end());
  24.     vector<pair<long, long>> ord;
  25.     for (long i = 0; i < (long)a.size(); ++i)
  26.         ord.push_back({b[i].second, i+1});
  27.     sort(ord.begin(), ord.end());
  28.     for (long i = 0; i < (long)a.size(); ++i)
  29.         a[i] = ord[i].second;
  30. }
  31.  
  32. long find_id(long n, vector<long> a)
  33. {
  34.     long res = 0;
  35.     while (a.size() > 1){
  36.         res += (a[0]-1)*factorial(--n);
  37.         a.erase(a.begin());
  38.         transform(a);
  39.     }
  40.     return res+a[0];
  41. }
  42.  
  43. vector<long> find_permutation(long id, long n)
  44. {
  45.     vector<long> a, b;
  46.     for (long i = 0; i < n; ++i)
  47.         b.push_back(i+1);
  48.  
  49.     while (id > 0){
  50.         long dgt = id/factorial(--n);
  51.         id %= factorial(n);
  52.         if (id == 0)
  53.             --dgt;
  54.         a.push_back(b[dgt]);
  55.         b.erase(b.begin()+dgt);
  56.     }
  57.     while (!b.empty()){
  58.         a.push_back(b.back());
  59.         b.pop_back();
  60.     }
  61.     return a;
  62. }
  63.  
  64. int main()
  65. {
  66.     cin.tie(0)->sync_with_stdio(0);
  67.     cout.tie(0)->sync_with_stdio(0);
  68.     //freopen("shhv.inp", "r", stdin);
  69.     //freopen("shhv.out", "w", stdout);
  70.     vector<long> a;
  71.     long n;
  72.     while (cin >> n)
  73.         a.push_back(n);
  74.     long p = a.back();
  75.     a.pop_back();
  76.     n = a.size();
  77.     cout << find_id(n, a) << nln;
  78.     a = find_permutation(p, n);
  79.     for (const auto i : a)
  80.         cout << i << ' ';
  81.     cout << nln;
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment