错排问题是说N个元素对应N个位置上,但是元素编号与位置编号各不对应的方法数,即错排数,用 M ( N ) 表示。
对应公式 M ( N ) = ( N - 1 ) * [ M ( N - 1 ) + M ( N - 2 ) ] 。
N - 1表示第N个元素可以选择1 ~ N - 1 共 N - 1 个位置,假设第N个元素放在了第K个位置。
接下来分两种情况。
1)把第K个元素放在了位置N,此时,剩下的 N - 2 个元素进行错排,错排数为 M ( N - 2 ) 。
2)不把第K个元素放在位置N,即把位置N视为元素K的对应位置,将N - 1 个元素进行错排,错排数为 M ( N - 1 )。
hdu 2049 不容易系列之(4)――考新郎

首先,给每位新娘打扮得几乎一模一样,并盖上大大的红盖头随机坐成一排;
然后,让各位新郎寻找自己的新娘.每人只准找一个,并且不允许多人找一个.
最后,揭开盖头,如果找错了对象就要当众跪搓衣板...
看来做新郎也不是容易的事情...
假设一共有N对新婚夫妇,其中有M个新郎找错了新娘,求发生这种情况一共有多少种可能.
Input
Output
Sample Input
2 2 2 3 2
Sample Output
1 3
排列组合问题,C ( n , m ) * M ( m ) 即从n个元素中找出m个元素并对这m个元素进行错排。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<ctype.h>
#include<algorithm>
#include<string>
#define PI acos(-1.0)
#define maxn 160
#define INF 1<<25
typedef long long ll;
using namespace std;
__int64 num[25];
__int64 jiecheng[25];
__int64 init()
{
num[0]=1;
num[1]=0;
num[2]=1;
for(int i=3;i<=20;i++)
{
num[i]=(i-1)*(num[i-2]+num[i-1]);
}
}
__int64 init2()
{
__int64 aa=1;
jiecheng[0]=1;
for(int i=1;i<=20;i++)
{
aa*=i;
jiecheng[i]=aa;
}
}
int main()
{
init();
init2();
int tot;
scanf("%d",&tot);
int ii,jj;
for(int i=0;i<tot;i++)
{
scanf("%d%d",&ii,&jj);
ll ans=jiecheng[ii]/jiecheng[jj]/jiecheng[ii-jj]*num[jj];
printf("%I64d\n",ans);
}
}
hdu 2068 RPG的错排
Input
Output
1 1
Sample Input
1 2 0
Sample Output
1 1
正确排列元素数量大于等于总元素数量的一半的结果算为一种情况,求总情况数。 C ( n , n / 2 ) * M ( n / 2 ) + C ( n , n / 2 + 1 ) * M ( n / 2 - 1 ) + . . . + C ( n , n ) 。
中间担心会超过long long 范围做了一点点小的处理。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<ctype.h>
#include<algorithm>
#include<string>
#define PI acos(-1.0)
#define maxn 160
#define INF 1<<25
typedef long long ll;
using namespace std;
__int64 num[25];
__int64 jiecheng[25];
__int64 init()
{
num[0]=1;
num[1]=0;
num[2]=1;
for(int i=3;i<=20;i++)
{
num[i]=(i-1)*(num[i-2]+num[i-1]);
}
}
__int64 init2()
{
__int64 aa=1;
jiecheng[0]=1;
for(int i=1;i<=20;i++)
{
aa*=i;
jiecheng[i]=aa;
}
}
int main()
{
init();
init2();
int tot;
while(scanf("%d",&tot))
{
if(tot==0)
break;
__int64 ans=0;
__int64 rec=1;
int ii=tot/2;
if(tot%2)
ii++;
for(int i=ii;i<=tot;i++)
{
rec=1;
for(int j=i+1;j<=tot;j++)
rec*=j;
rec/=jiecheng[tot-i];
rec*=num[tot-i];
ans+=rec;
}
printf("%I64d\n",ans);
}
}