HDU 2048 2049 (错位排列)
错位排列递推式
f[0] = 0; f[1] = 0;
f[i] = (i - 1) * (f[i - 1] + f[i - 2]);
全错位排列
#include <bits/stdc++.h> #define LL long long #define ULL unsigned long long #define UI unsigned int #define mem(i, j) memset(i, j, sizeof(i)) #define rep(i, j, k) for(int i = j; i <= k; i++) #define dep(i, j, k) for(int i = k; i >= j; i--) #define pb push_back #define make make_pair #define INF 0x3f3f3f3f #define inf LLONG_MAX #define PI acos(-1) #define fir first #define sec second #define lb(x) ((x) & (-(x))) #define dbg(x) cout<<#x<<" = "<<x<<endl; using namespace std; const int N = 255; LL f[30], fac[30]; void init() { f[0] = 0; f[1] = 0; f[2] = 1; rep(i, 3, 20) f[i] = (i - 1) * (f[i - 1] + f[i - 2]); fac[0] = 1; rep(i, 1, 20) fac[i] = 1LL * i * fac[i - 1]; } void solve() { int n; scanf("%d", &n); printf("%.2f%%\n", (double)((1.0 * f[n]) / (1.0 * fac[n])) * 100.0); } int main() { init(); int _; scanf("%d", &_); while(_--) solve(); // solve(); return 0; }
n对中,恰好有 m 对选错的方案数:C(n, m) * f[n]
#include <bits/stdc++.h> #define LL long long #define ULL unsigned long long #define UI unsigned int #define mem(i, j) memset(i, j, sizeof(i)) #define rep(i, j, k) for(int i = j; i <= k; i++) #define dep(i, j, k) for(int i = k; i >= j; i--) #define pb push_back #define make make_pair #define INF 0x3f3f3f3f #define inf LLONG_MAX #define PI acos(-1) #define fir first #define sec second #define lb(x) ((x) & (-(x))) #define dbg(x) cout<<#x<<" = "<<x<<endl; using namespace std; const int N = 255; LL f[30], fac[30]; void init() { f[0] = 0; f[1] = 0; f[2] = 1; rep(i, 3, 20) f[i] = (i - 1) * (f[i - 1] + f[i - 2]); fac[0] = 1; rep(i, 1, 20) fac[i] = 1LL * i * fac[i - 1]; } void solve() { int n, m; scanf("%d %d", &n, &m); LL ans = fac[n] / (fac[m] * fac[n - m]); ans *= f[m]; printf("%lld\n", ans); } int main() { init(); int _; scanf("%d", &_); while(_--) solve(); // solve(); return 0; }
一步一步,永不停息