HDU 1465 不容易系列之一 (错排)

【题目链接】
http://poj.org/problem?id=1465

题目意思

给定n个封信,问n封信都装错有多少种错误方式。

解题思路

错排公式:F(n)=(n-1)[F(n-1)+F(n-2)]
解释:假定A,B,C,D为已经排列的。当E加入时候就会出现两种情况让排列为错排。
1. A,B,C,D已经为错排,那么只要将E与其中任意一个(4种选择)互换就可以使排列为错排。A,B,C,D错排为F(4)。
2. A,B,C,D中有一个正确,其他3个位错误。那么只要将正确的与E互换排列将为错排。而谁为正确有4种选择。3个错排为F(3).
综合推广就得到错排公式。

代码部分


#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <string>
#include <map>
#include <math.h>
using namespace std;
#define LL long long
#define inf 0x3f3f3f3
const int N = 1e3+7;
LL a[25]; 
int main()
{
    a[2] = 1,a[3] = 2;
    for (int i = 4; i < 25; i++)
        a[i] = a[i-1]*(i-1)+a[i-2]*(i-1);
    int n;
    while (~scanf("%d",&n))
    {
        printf("%lld\n",a[n]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/pashuihou/article/details/81161644