Problem 4. derange
Input file: derange.in
Output file: derange.out
Time limit: 1 second
Memory limit: 256 MB
Mr. Hu 需要给机房的n 位同学重新安排位置,为了使换位的效果好,需要保证每位同学在排位前和排
位后所在的位置都不同。
Mr. Hu 想知道有多少种可能的排位方法。因为排位数可能很大,所以你只需要输出它模109 +7 的结果。
Input
输入文件中只有1 个数n,表示学生人数。
Output
输出可能的排位数取模后的结果。
Sample
derange.in derange.out
3 2
Note
样例说明:假设一开始三个人的位置为(1; 2; 3),那么合法的换位结果为:(2; 3; 1) 和(3; 1; 2)。
• 对于30% 的数据,1 n 9
• 对于70% 的数据,1 n 103
• 对于100% 的数据,1 n 106
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<set>
#include<queue>
#include<algorithm>
#include<vector>
#include<cstdlib>
#include<cmath>
#include<ctime>
#include<stack>
#define INF 2100000000
#define LL long long
#define clr(x) memset(x,0,sizeof(x))
#define ms(a,x) memset(x,a,sizeof(x))
#ifdef win32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
const int MOD = 1e9+7;
const int maxn = 1e6+7;
LL a[maxn];
int n;
/*int f(int x) {
if(x == 1) return 0;
if(x == 2) return 1;
else return ((x-1)%MOD)*((f(x-1)%MOD)+(f(x-2)%MOD))%MOD;
}*/
LL f(int x) {
if(x == 1) return 0;
if(x == 2) return 1;
a[1] = 0; a[2] = 1;
for(int i = 3; i <= x; i++) a[i] = (LL)((i-1)%MOD)*((a[i-1]%MOD)+(a[i-2]%MOD))%MOD;
return a[x];
}
int main() {
freopen("derange.in","r",stdin);
freopen("derange.out","w",stdout);
scanf("%d",&n);
printf("%d",f(n)%MOD);
return 0;
}