参考
https://oi-wiki.org/math/cantor/
https://zh.wikipedia.org/zh-hans/%E5%BA%B7%E6%89%98%E5%B1%95%E5%BC%80
luogu5367
题解
代码(树状数组优化)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int const mod = 998244353;
int const N = 1e6 + 10;
int n,a[N],c[N];
ll f[N];
int lowbit(int n){return n & -n;}
void add(int i,int x){
while(i <= n){
c[i] += x;
i += lowbit(i);
}
}
int getsum(int i){
int sum = 0;
while(i){
sum += c[i];
i -= lowbit(i);
}
return sum;
}
ll KT(){
ll ans = 0;
for(int i=1;i<=n;i++){
ans = (ans + f[i-1] * getsum(a[i])) % mod;
add(a[i],1);
}
return ans + 1;
}
void init(){
f[0] = 1;
for(int i=1;i<=n;i++)
f[i] = f[i-1] * i % mod;
}
int main(){
scanf("%d",&n);
for(int i=n;i>=1;i--)
scanf("%d",&a[i]);
init();
cout<<KT()<<endl;
return 0;
}
51nod2188
题解
代码
#include <bits/stdc++.h>
using namespace std;
#define lson (id<<1)
#define rson (id<<1|1)
#define mid ((l + r) >> 1)
typedef long long ll;
int const N = 1e6 + 10;
ll f[N];
int n;
struct Node
{
int l,r;
int sum;
}node[10<<2];
void init(){
f[0] = 1;
for(int i=1;i<=10;i++)
f[i] = f[i-1] * i;
}
void push_up(int id){
node[id].sum = node[lson].sum + node[rson].sum;
}
void build(int id,int l,int r){
node[id].l = l, node[id].r = r;
if(l == r) node[id].sum = 1;
else{
build(lson,l,mid);
build(rson,mid + 1,r);
push_up(id);
}
}
void update(int id,int k){ //把第k个数权值置为0
int l = node[id].l, r = node[id].r;
if(l == r) node[id].sum = 0;
else{
if(k <= mid) update(lson,k);
else update(rson,k);
push_up(id);
}
}
int query(int id,int k){
int l = node[id].l, r = node[id].r;
if(l == r) return node[id].l;
else{
if(node[lson].sum >= k) return query(lson,k);
else return query(rson,k - node[lson].sum);
}
}
void IKT(int n){
build(1,1,10);
n--;
for(int i=9;i>=0;i--){
int k = n / f[i]; //表示有k个数小于它,所以它是第(k + 1)个数
int num = query(1,k + 1); //表示从左到右第k大的数
update(1,num); //第num个数置为0
n -= k * f[i];
cout<<num - 1;
}
cout<<endl;
}
int main(){
init();
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
IKT(n);
}
return 0;
}