错排:就是类似于将1 ~ n的数放在1 ~ n的位置上,要求每个数都不能放在于自己相同的位置上;
错排公式:符合错排的种类f[ n ] = (n - 1) *( f[ n - 1] + f[n - 2]);
推导过程:
当n个编号元素放在n个编号位置,元素编号与位置编号各不对应的方法数用D(n)表示,那么D(n-1)就表示n-1个编号元素放在n-1个编号位置,各不对应的方法数,其它类推.
第一步,把第n个元素放在一个位置,比如位置k,一共有n-1种方法;
第二步,放编号为k的元素,这时有两种情况:⑴把它放到位置n,那么,对于剩下的n-1个元素,由于第k个元素放到了位置n,剩下n-2个元素就有D(n-2)种方法;⑵第k个元素不把它放到位置n,这时,对于这n-1个元素,有D(n-1)种方法;
综上得到
D(n) = (n-1) [D(n-2) + D(n-1)]
特殊地,D(1) = 0, D(2) = 1.
题意:找出n个数里面恰好有m个数错排的情况数;
思路:((m,n)* D(m);
代码:
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
const int maxn = 20 + 5;
ll a[maxn];
void Init()
{
a[1] = 0;
a[2] = 1;
for(int i = 3; i < maxn; i ++)
a[i] = (i - 1) * (a[i - 1] + a[i - 2]);
}
ll combine(ll x,ll y)
{
if(x > y - x)
x = y - x;
if(x == 0)
return 1;
ll ans = 1;
for(ll t = x, i = y; t > 0 ; i --, t --)
{
ans *= i;
}
for(ll i = x; i > 1; i --)
ans /= i;
return ans;
}
int main()
{
Init();
int Tcase;
scanf("%d",&Tcase);
for(int ii = 1; ii <= Tcase ; ii ++)
{
ll n,m;
scanf("%I64d%I64d",&n,&m);
// cout << combine(m,n) << " " << a[m] << endl;
cout << combine(m,n) * a[m] << endl;
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MOD 2147493647
const int maxn = 26;
ll a[maxn];
void Init()
{
a[1] = 0;
a[2] = 1;
for(int i = 3; i < maxn ; i ++)
a[i] = (i - 1) * (a[i - 1] + a[i - 2]);
}
ll combination(ll x, ll y)
{
ll ans = 1;
x = min(x,y - x);
for(ll i = y, t = x; t > 0;t --,i --)
ans *= i;
for(ll i = 1; i <= x; i ++)
{
ans /= i;
}
return ans;
}
int main()
{
int n;
Init();
while( ~ scanf("%d",&n) && n)
{
ll ans = 1;
for(int i = 1; i <= n/2; i ++)
{
ans += a[i] * combination(i,n);
}
cout << ans << endl;
}
return 0;
}