HDU_2068 RPG的错排(错排+组合数)

时间:2022-10-06 11:27:59

题目请点我
题解:
这是一道错排问题,题意是说猜出>N/2才算是成功,那我们就需主要找到1~N/2的错排相加。
错排公式:D[i] = (i-1)*(D[i-1]+D[i-2]); 错排的数序要用组合数求出。
代码实现:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define MAX 30
#define LL long long

using namespace std;

int N;
LL D[MAX];
LL result;
void pre();
LL C(int n,int m);
int main()
{
    pre();
    while( scanf("%d",&N) && N ){
        result = 1;
        int len = N/2;
        for( int i = 0; i <= len; i++ ){
            result += C(N,i)*D[i];
        }
        printf("%I64d\n",result);
    }
    return 0;
}

void pre(){
    memset(D,0,sizeof(D));
    D[1] = 0;
    D[2] = 1;
    for( int i = 3; i < 15; i++ ){
        D[i] = (i-1)*(D[i-1]+D[i-2]);
    }
}

LL C(int n,int m){
    if( m == 0 ){
        return 1;
    }
    LL A = 1;
    LL B = 1;
    int len = m;
    for( int i = 0; i < len; i++ ){
        A *= n;
        B *= m;
        n--;m--;
    }
    return A/B;
}