UVA - 10497 Sweet Child Makes Trouble

来源:互联网 发布:骚男的淘宝店网址 编辑:程序博客网 时间:2024/06/06 02:29

Children are always sweet but they can sometimesmake you feel bitter. In this problem, you will see how Tintin, a five year’sold boy, creates trouble for his parents. Tintin is a joyful boy and is alwaysbusy in doing something. But what he does is not always pleasant for hisparents. He likes most to play with household things like his father’swristwatch or his mother’s comb. After his playing he places it in some otherplace. Tintin is very intelligent and a boy with a very sharp memory. To makethings worse for his parents, he never returns the things he has taken forplaying to their original places.

Think about a morning when Tintin has managed to‘steal’ three household objects. Now, in how many ways he can place thosethings such that nothing is placed in their original place. Tintin does notlike to give his parents that much trouble. So, he does not leave anything in acompletely new place; he merely permutes the objects.

Input

There will be several test cases. Each will havea positive integer less than or equal to 800 indicating the number of thingsTintin has taken for playing. Each integer will be in a line by itself. The inputis terminated by a –1 (minus one) in a single line, which should not beprocessed.

Output

For each test case print an integer indicating inhow many ways Tintin can rearrange the things he has taken.

Sample Input

2
3
4
-1

SampleOutput

1
2
9

题意:这个题还和张胜飞学长理解的还有些出入,他理解的是至少有一样东西在原来的位置,我的理解是所有物品都在不同的位置。(事实证明我是正确的)这个题在第二天才详细读,就是说淘气的孩子喜欢把n件物品放在不同的位置(调换他们的位置),问有多少不同的放法!
思路:这是一个错排的问题,需要简单推理一下,以下我的推理过程:
首先,可以把n-1个数排好,那么最后一个数与前面n-1个数对调,情况为(n-1)*f【n-1】;
其次,可以把n-2个数排好,剩下的两个数可以原封不动的和原来对调,也可以两个数对调之后在和前面的对调,情况为(n-2+1)*f[n-2];
所以 f[n]=(n-1)*(f[n-2]+f[n-1])
按理说,到这里,只要打表就行了,可是不然,最后的结果非常大,要用到高精度,这里不推荐运算符重载什么的,推荐模拟运算,存数组然后模拟,每6位存一位!
code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;

const int N=805;
const int M=1000000;
int f[N][N]; //第一维是n,第二维是存的数,每6位一位

void my_way() //打表
{
int t;
memset(f,0,sizeof(f));
f[2][0]=1;
for (int i=3;i<N;i++)
{
t=0;
for (int j=0;j<N;j++)
{
f[i][j]=(f[i-1][j]+f[i-2][j])*(i-1)+t;
t=f[i][j]/M;
f[i][j]=f[i][j]%M;
}
}
}

int main()
{
//freopen("out.txt","w",stdout);
my_way();
int n;
while (~scanf("%d",&n))
{
if (n==-1) break;
int i,j;
for (i=N-1;i>=0;i--)
if (f[n][i]!=0) break;
printf("%d",f[n][i]);
for (j=i-1;j>=0;j--)
printf("%06d",f[n][j]);
printf("\n");
}
}

0 0