跳到正文

个人记录

CF1548C The Three Little Pigs

Believe_in_dreams约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年7月10日
更新
2026年7月10日
篇幅
约 5 分钟

版本

  1. v1当前

给定 nn,多次给定 tt 后求 ∑i=1nC3it\sum_{i=1}^n C_{3i}^t。

n≤106,q≤2×105n\le 10^6,q\le 2\times 10^5。

∑i=1nC3it=∑i=1n[xt](x+1)3i=[xt]∑i=1n(x3+3x2+3x+1)i=[xt](x3+3x2+3x+1)n+1−(x3+3x2+3x+1)(x3+3x2+3x+1)−1\begin{aligned} &\sum_{i=1}^n C_{3i}^t\\ =&\sum_{i=1}^n[x^t](x+1)^{3i}\\ =&[x^t]\sum_{i=1}^n(x^3+3x^2+3x+1)^i\\ =&[x^t]\frac{(x^3+3x^2+3x+1)^{n+1}-(x^3+3x^2+3x+1)}{(x^3+3x^2+3x+1)-1}\\ \end{aligned}

容易发现右边分式恒定,考虑预处理。

对于 (x3+3x2+3x+1)n+1(x^3+3x^2+3x+1)^{n+1},暴力乘法时间复杂度为 O(n2)\mathcal{O}(n^2),不可接受。考虑多项式快速幂,或者变形为 (x+1)3n+3(x+1)^{3n+3} 然后用组合数快速求。

注意到分子的指数是 O(n)\mathcal{O}(n) 量级的,分母的指数是 O(1)\mathcal{O}(1) 量级的,考虑直接模拟多项式竖式除法,时间复杂度 O(n)\mathcal{O}(n)。

本题略有卡常,考虑在 CodeForces 上提交时加上 pragma 并 O(n)\mathcal{O}(n) 预处理阶乘逆元:先暴力求 invninv_n 然后倒序 invn−1=invn×ninv_{n-1}=inv_n\times n。

展示代码:

C++
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize(3,"Ofast","inline")
#define int long long
int n, q;

constexpr int MAXSIZE = 3e5;
char buf[MAXSIZE], *p1, *p2;
#define gc()(p1==p2&&(p2=(p1=buf)+fread(buf,1,MAXSIZE,stdin),p1==p2)?EOF:*p1++)
inline int read() {
	int ans = 0;
	char c = gc();
	while (c > '9' or c < '0') c = gc();
	while (c >= '0' and c <= '9') ans = (ans << 3) + (ans << 1) + (c ^ 48), c = gc();
	return ans;
}
void write(int x) {
	if (x > 9) write(x / 10);
	putchar(48 + x % 10);
}


constexpr int mod = 1e9 + 7;
inline int ksm(int a, int b) {
	int ret = 1;
	while (b) {
		if (b & 1) ret = (ret * a) % mod;
		a = (a * a) % mod, b >>= 1;
	}
	return ret;
}

constexpr int N = 3e6 + 10;
int pre[N], inv[N];
inline int C(int a, int b) {
	return pre[a] * inv[b] % mod * inv[a - b] % mod;
}

vector<int>f1, f2, ret;
void div(vector<int>& a, vector<int>& b) {//返回 a/b,调用前需要保证整除
	int A = a.size(), B = b.size();
	for (int i = A - 1; i >= B - 1; --i) {
		//用 b[B-1] 对齐 a[i]
		int h = a[i] * ksm(b[B - 1], mod - 2) % mod;
		ret.push_back(h);
		for (int j = 0; j < B; ++j)
			a[i - j] = (a[i - j] - b[B - 1 - j] * h) % mod;
	}
	reverse(ret.begin(), ret.end());
}

signed main() {
	pre[0] = 1;
	for (int i = 1; i < N; ++i) pre[i] = (pre[i - 1] * i) % mod;
	inv[N - 1] = ksm(pre[N - 1], mod - 2);
	for (int i = N - 1; i >= 1; --i) inv[i - 1] = inv[i] * i % mod;
	n = read(), q = read();
	f1.push_back(1), f1.push_back(3), f1.push_back(3), f1.push_back(1);
	for (int i = 0; i <= 3 * n + 3; ++i) f2.push_back(C(3 * n + 3, i));
	f2[0] -= 1, f2[1] -= 3, f2[2] -= 3, f2[3] -= 1, --f1[0];
	div(f2, f1);
	for (int i = 1, t; i <= q; ++i)
		t = read(), write((ret[t] % mod + mod) % mod), putchar(10);
	return 0;
}
原文