题目描述:原题链接
Fairy is a very excentric mailman. Every now and then, he likes to change some correspondences that he is responsible for, swapping than to different addresses, as he enjoys the consequent turmoil. One day, Fairy was in his most inspired self and decided to swap all correspondences from their original addresses. No address should receive its intended correspondence. It will be Fairy’s ultimate masterpiece. Although he is keen to chaos, Fairy is also a very curious person, and he asked himself about how many ways he could swap the correspondences so none of the addresses receive the correct message. As he’s very lazy, he decided to ask your help to fulfill his objectives. You’ll receive an integer number N, that stands for the correspondences amount, to which you should generate another integer S that stands for the amount of ways he can swap the correspondences. Help Fairy in his mischievous plan, or he might change your correspondence as well.
Input
A unique integer N, (1≤N≤20) standing for the amount of correspondences.
Output
A unique integer S, representing the amount of ways Fairy can swap the correspondences. As the possibilities amount can be very big, the answer should be given as S mod 109+7.
Example
input
3
output
2
思路:
以n=4时为例,可以将4放入1,2,3,那么剩下的情况如果是两个对应的信对换就是 a[n-2] 的情况,否则时 a[n-1] 的情况。所以得出递推公式 a[n]=(n-1)*(a[n-1]+a[n-2]) 。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
ll a[26];
int main()
{
int n;
cin>>n;
a[2]=1,a[3]=2;
for(ll i=4;i<=22;i++)
{
a[i]=(i-1)*(a[i-1]+a[i-2])%mod;
}
printf("%lld\n",a[n]);
return 0;
}