#include using namespace std; using ll = long long; // 長さnの順列のうち、辞書順でm番目(0-indexed)の順列(0-indexed)を返す. #include #include vector permutation(const int &n, const long long &m) { vector r(n); long long d = m; for (int i = 0; i < n; ++i) { r[n - i - 1] = d % (i + 1); d /= i + 1; } __gnu_pbds::tree, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> s; for (int i = 0; i < n; ++i) s.insert(i); vector p(n); for (int i = 0; i < n; ++i) { p[i] = *s.find_by_order(r[i]); s.erase(p[i]); } return p; } // 受け取った順列(0-indexed)の辞書順での順列番号(0-indexed)を返す. #include template T permorder(const vector &p) { int n = p.size(); vector f(n + 1, 1); for (int i = 1; i <= n; ++i) f[i] = f[i - 1] * i; atcoder::fenwick_tree bit(n); T res = 0; for (int i = 0; i < n; ++i) { res += (p[i] - bit.sum(0, p[i])) * f[n - i - 1]; bit.add(p[i], 1); } return res; } // https://yukicoder.me/problems/no/1311 int main() { ll n; int s; cin >> n >> s; vector p = permutation(s, n); vector pinv(s); for (int i = 0; i < s; ++i) pinv[p[i]] = i; cout << permorder(pinv) << endl; }