HDU 1465 错排问题

  错排问题简单的理解就是{123..n}的排列中每个数字都不在原来位置上的排列, 设Dn为n个元素错排的数量, 那么Dn = (n-1)*(Dn-1+Dn-2)。其中D1=0, D2=1。关于错排的另外一个数学表达式就是n!*(1-1/1!+2/2!+...+(-1)^n/n!)。。这一题就是求Dn直接递推即可。代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>

using namespace std;
long long D[100];

int main()
{
    D[0] = 1; D[1] = 0;
    for(int i=2; i<=30; i++)
        D[i] = (i-1)*(D[i-1]+D[i-2]);
    int n;
    while(cin>>n)
    {
        cout<<D[n]<<endl;
    }
    return 0;
}

 

posted @ 2016-02-23 13:19  xing-xing  阅读(113)  评论(0编辑  收藏  举报