洛谷 P4931 [MtOI2018] 情侣?给我烧了!(加强版)

洛谷传送门

\(f_i\)\(i\) 对情侣完全错位的方案数,那么答案为:

\[\binom{n}{k} \frac{n!}{(n - k)!} 2^k f_{n - k} \]

分别代表选择 \(k\) 对情侣,选择它们的位置,情侣可以换位。

\(f_i\) 有递推公式:

\[f_i = 4i(i - 1) (f_{i - 1} + 2(i - 1) f_{i - 2}) \]

考虑选出两个人,另外对应的两个人的方案即可。

code
// Problem: P4931 [MtOI2018] 情侣?给我烧了!(加强版)
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P4931
// Memory Limit: 500 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mems(a, x) memset((a), (x), sizeof(a))

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef pair<ll, ll> pii;

const int maxn = 5000100, N = 5000000;
const ll mod = 998244353;

inline ll qpow(ll b, ll p) {
	ll res = 1;
	while (p) {
		if (p & 1) {
			res = res * b % mod;
		}
		b = b * b % mod;
		p >>= 1;
	}
	return res;
}

ll n, m, fac[maxn], ifac[maxn], pw[maxn], f[maxn];

inline void init() {
	pw[0] = 1;
	for (int i = 1; i <= N; ++i) {
		pw[i] = pw[i - 1] * 2 % mod;
	}
	fac[0] = 1;
	for (int i = 1; i <= N; ++i) {
		fac[i] = fac[i - 1] * i % mod;
	}
	ifac[N] = qpow(fac[N], mod - 2);
	for (int i = N - 1; ~i; --i) {
		ifac[i] = ifac[i + 1] * (i + 1) % mod;
	}
	f[0] = 1;
	for (int i = 2; i <= N; ++i) {
		f[i] = 1LL * i * (i - 1) % mod * 4 % mod * (f[i - 1] + (i - 1) * 2 % mod * f[i - 2] % mod) % mod;
	}
}

inline ll C(ll n, ll m) {
	if (n < m || n < 0 || m < 0) {
		return 0;
	} else {
		return fac[n] * ifac[m] % mod * ifac[n - m] % mod;
	}
}

void solve() {
	scanf("%lld%lld", &n, &m);
	printf("%lld\n", C(n, m) * C(n, m) % mod * fac[m] % mod * pw[m] % mod * f[n - m] % mod);
}

int main() {
	init();
	int T = 1;
	scanf("%d", &T);
	while (T--) {
		solve();
	}
	return 0;
}
posted @ 2023-07-15 12:47  zltzlt  阅读(30)  评论(0编辑  收藏  举报