P5367 【模板】康托展开

P5367 【模板】康托展开

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 1e6+5;
 5 const int mod = 998244353;
 6 ll n, a[maxn], c[maxn], fac[maxn], ans;
 7 template<typename T> inline T read(T a) {
 8     T res = 0, f = 1;
 9     char ch = getchar();
10     while (!isdigit(ch)) {
11         if (ch == '-') f = -1;
12         ch = getchar();
13     }
14     while (isdigit(ch)) {
15         res = (res<<3)+(res<<1) + ch - 48;
16         ch = getchar();
17     }
18     return res*f;
19 }
20 int lowbit(int x) { return x&(-x); }
21 void add(int x, int k) {
22     while (x <= n) {
23         c[x] += k;
24         x += lowbit(x);
25     }
26 }
27 int sum(int x) {
28     int res = 0;
29     while (x > 0) {
30         res += c[x];
31         x -= lowbit(x);
32     }
33     return res;
34 }
35 int main() {
36     n = read(n);
37     fac[0] = fac[1] = 1;
38     for (int i = 2; i <= n; ++i) {
39         fac[i] = fac[i-1]*i%mod;
40     }
41     for (int i = 1; i <= n; ++i) {
42         add(i,1);
43     }
44     for (int i = 1; i <= n; ++i) {
45         a[i] = read(a[i]);
46         ans = (ans + ((sum(a[i]-1))*fac[n-i]%mod))%mod;
47         add(a[i],-1);
48     }
49     printf("%lld\n",ans+1);
50     return 0;
51 }

猜你喜欢

转载自www.cnblogs.com/wstong/p/11781313.html
今日推荐