2018徐州邀请赛B - Array - 动态规划

题解链接

http://www.lucien.ink/archives/251/


题目

题目描述

JSZKC is the captain of the lala team.
There are N girls in the lala team. And their height is [1,N] and distinct. So it means there are no two girls with a same height.
JSZKC has to arrange them as an array from left to right and let h[i] be the height of the ith girl counting from the left. After that, he can calculate the sum of the inversion pairs. A inversion pair counts if h[i]>h[j] with i

输入

The input file contains several test cases, each of them as described below.
The first line of the input contains two integers N and K (1 ≤ N ≤ 5000, 0 ≤ K ≤ 5000), giving the number of girls and the pairs that JSZKC asked.
There are no more than 5000 test cases.

输出

An integer in one line for each test case, which is the number of the plans mod 1000000007.

样例输入

3 2
3 3

样例输出

2
1

题意

  问你1~n的所有排列中有多少种排列拥有k对逆序数。


思路

   f[i][j] f [ i ] [ j ] 代表长度为 i i 的排列有j对逆序数的方案数,考虑放第 i i 个数的时候,前面i1个数的所有方案都已知,且都比 i i 小,如果i放在前 i1 i − 1 个数的最左边,则会新产生 i1 i − 1 对逆序数,如果 i i 放在前i1个数的最右边,则不会产生逆序数。也就是说在前 i1 i − 1 个数已经固定,准备放置第 i i 个数时,可以产生的逆序数对的数量x[0,i1],于是有:

f[i][j]=x=0i1f[i1][jx] f [ i ] [ j ] = ∑ x = 0 i − 1 f [ i − 1 ] [ j − x ]

  题目只给了 64MB 64 M B 说的内存,所以需要把询问离线下来,然后用滚动数组求解同时离线答案。


实现

#include <bits/stdc++.h>
const int maxn = 5007, mod = int(1e9) + 7;
int ans[maxn], f[3][maxn], cnt, cur;
struct Query { int n, k, index; } query[maxn];
int main() {
    while (~scanf("%d%d", &query[cnt].n, &query[cnt].k)) {
        query[cnt].index = cnt;
        cnt++;
    }
    std::sort(query, query + cnt, [](Query x, Query y) { return x.n < y.n; });
    f[0][0] = 1;
    for (int i = 1; i <= 5000; i++) {
        int sum = 0;
        for (int j = 0; j <= 5000; j++) {
            sum = (sum + f[i - 1 & 1][j]) % mod;
            if (j - i >= 0) sum = (sum - f[i - 1 & 1][j - i] + mod) % mod;
            f[i & 1][j] = sum;
        }
        while (cur < cnt && query[cur].n == i) {
            ans[query[cur].index] = f[i & 1][query[cur].k];
            cur++;
        }
    }
    for (int i = 0; i < cnt; i++) printf("%d\n", ans[i]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值