HDU 5225 Tom and permutation

本文介绍了一个算法问题:给定一个1到n的排列,求所有比该排列字典序小的排列中各排列的逆序数之和,并提供了一个具体的C++实现方案,包括预处理阶乘和逆序数计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description
Tom has learned how to calculate the number of inversions in a permutation of n distinct objects by coding, his teacher gives him a problem:
Give you a permutation of n distinct integer from 1 to n, there are many permutations of 1-n is smaller than the given permutation on dictionary order, and for each of them, you can calculate the number of inversions by coding. You need to find out sum total of them.
Tom doesn't know how to do, he wants you to help him.
Because the number may be very large, output the answer to the problem modulo 109+7.
 

Input
Multi test cases(about 20). For each case, the first line contains a positive integer n, the second line contains n integers, it's a permutation of 1-n.
n100
 

Output
For each case, print one line, the answer to the problem modulo 109+7.
 

Sample Input
3 2 1 3 5 2 1 4 3 5
 

Sample Output
1

75

数位dp

#include<cstdio>
#include<cmath>
#include<queue>
#include<map>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 105;
const int base = 1000000007;
int n, a[maxn], u[maxn];
long long f[maxn], p[maxn], ans, tot, sum;

void get()
{
    p[0] = 1;
    for (int i = 1; i <= 100; i++)
    {
        f[i] = (i * f[i - 1] + p[i - 1] * i * (i - 1) / 2) % base;
        p[i] = (p[i - 1] * i) % base;
    }
}

int main()
{
    get();
    while (scanf("%d", &n) != EOF)
    {
        ans = tot = 0;
        for (int i = 1; i <= n; i++) scanf("%d", &a[i]), u[i] = 1;
        for (int i = 1; i <= n; i++)
        {
            sum = 0;
            for (int j = 1; j < a[i]; j++)
            if (u[j])
            {
                (ans += f[n - i] + p[n - i] * (tot+sum)) %= base;
                sum++;
            }

            tot += sum;
            u[a[i]] = 0;
        }
        cout << ans << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值