ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • intToPerm, permToInt
    232's competitive-programming templates./misc 2024. 12. 8. 00:15
    constexpr int P = 7;
    
    const auto fac = [] {
      std::array<int, P + 1> f {};
      f[0] = 1;
      for (int i = 1; i <= P; ++i) {
        f[i] = i * f[i - 1];
      }
      return f;
    } ();
    
    std::array<int, P> intToPerm(int k) {
      assert(0 <= k && k < fac[P]);
      std::array<int, P> res;
      for (int i = P - 1; i >= 0; --i) {
        int w = k / fac[P - 1 - i] % (P - i);
        res[i] = w;
        for (int j = i + 1; j < P; ++j) {
          if (res[j] >= w) {
            res[j] += 1;
          }
        }
      }
      return res;
    }
    
    int permToInt(const std::array<int, P>& a) {
      int res = 0;
      for (int i = 0; i < P; ++i) {
        assert(0 <= a[i] && a[i] < P);
        int small = 0;
        for (int j = i + 1; j < P; ++j) {
          assert(a[i] != a[j]);
          if (a[i] > a[j]) {
            small += 1;
          }
        }
        res += small * fac[P - 1 - i];
      }
      return res;
    }
Designed by Tistory.