错排公式大家都会,不解释,主要是高中学的杨辉三角好用,不然会越界
#include <iostream>
#include <algorithm>
using namespace std;
unsigned long long c[26][26] = {0};
unsigned long long offset[20] = {0};
int main(void)
{
c[1][1] = 1;
c[2][1] = 2;
c[2][2] = 1;
for (int i = 0; i != 26; ++i)
c[i][0] = 1;
for (int i = 3; i != 26; ++i)
{
for (int j = 1; j <= i; ++j)
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
offset[0] = offset[2] = 1;
offset[1] = 0;
for (int i = 3; i != 26; ++i)
offset[i] = (i - 1) * (offset[i - 1] + offset[i - 2]);
int n;
while (cin >> n)
{
if (n == 0)
return 0;
int m = (n + 1) / 2;
unsigned long long ans = 0;
for (int i = m; i <= n; ++i)
ans += c[n][i] * offset[n - i];
cout << ans << endl;
}
}