不等式数列 百度2017春招笔试

问题描述: 度度熊最近对全排列特别感兴趣,对于1到n的一个排列,度度熊发现可以在中间根据大小关系插入合适的大于和小于符号(即 ‘>’ 和 ‘<’ )使其成为一个合法的不等式数列。但是现在度度熊手中只有k个小于符号(即’<’)和n-k-1个大于符号(即’>’),度度熊想知道对于1至n任意的排列中有多少个排列可以使用这些符号使其为合法的不等式数列。

输入描述:

输入包括一行,包含两个整数n和k(k < n ≤ 1000)

输出描述:

输出满足条件的排列数,答案对2017取模。

输入例子:

5 2

输出例子:

66

Dynamic Programming

dp[i][j] denotes the number of permutations satisfied the condition where there are i numbers and j less-than-signs. When the (i+1)-th number is interpolated, there are four cases:
1) Inserted before the head of permutation. e.g. xbefore head(a<b)(x>a<b) . A greater-than-sign is generated.
2) Inserted after the tail of permutation. e.g. xafter tail(a<b)(a<b<x) . A less-than-sign is generated.
3) Inserted in the middle of a greater-than-sign. e.g xgreaterthansign(a>b)(a<x>b) . A less-than-sign is generated.
4) Inserted in the middle of a less-than-sign. e.g xlessthansign(a<b)(a<x>b) . A greater-than-sign is generated.

Hence, dp[i][j] equals to sum of the four cases below:

  • dp[i1][j] : i-th number is serted before the head. No less-than-sign is producted, so there’re j less-than-signs in this case.
  • dp[i1][j1] : i-th number is serted after the tail. a less-than-sign is generated after inserting a number.
  • dp[i1][j1](ij1) : a less-than-sign is produced when the i-th number inserted in the middle of a greater-than-sign, (ij1) choices in total.
  • dp[i1][j]j : inserted inner a less-than-sign, j choices in total.
    Namely, dp[i][j]=dp[i1][j1](ij)+dp[i1][j](j+1)

Modulo Equivalencies

  • (a+b) mod n=[(a mod n)+(b mod n)] mod n
  • ab mod n=[(a mod n)(b mod n)] mod n

Code in Java

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);  
        int n = sc.nextInt();  
        int k = sc.nextInt();  
        int[][] dp = new int[n+1][k+1];  
        for (int i = 1; i < n+1; i++)
            dp[i][0] = 1;  //all of the other values are initialized as 0.
        for (int i = 2; i < n+1; i++) {  
            for (int j = 1; j <= k && j < i; j++) {  
                dp[i][j] = (dp[i-1][j-1]*(i-j)+dp[i-1][j]*(j+1))%2017;  
            }  
        }  
        System.out.println(dp[n][k]);  
    }  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值