题目大意
从((0,0,0))走到((n,n,n)),每一步可以从((x,y,z))走到((x+1,y,z))或((x,y+1,z))或((x,y,z+1)),给出(m)个不允许经过的点,求这样走的方案数。
(nleq 100000,mleq 5000)
Solution
很经典的题目。
枚举(i)个点必定经过然后容斥,复杂度(O(m!))。
考虑把这个过程放到递推上,设(f_i)表示从((0,0,0))走到第(i)个点,且不经过其他点的方案数;记(j o i)表示(j)能到达(i),(g(a,b,c))表示从((0,0,0))以任意方式走到((a,b,c))的方案数,有:
[f_i=sum_{j o i}-f_j*g(x_i-x_j,y_i-y_j,z_i-z_j)
]
怎么推的?(f_j)里的所有路径经过(i)后都多了一个点,所以容斥系数都要乘以(-1)。
这样就做到了(O(m^2))。
Code
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 300017, M = 5017;
const ll P = 1000000007;
int n, m, tot;
ll fac[N], inv[N], f[M];
struct note {
int x, y, z;
} a[M];
int cmp(note p, note q) {
return p.x == q.x ? (p.y == q.y ? p.z < q.z : p.y < q.y) : p.x < q.x;
}
int operator==(note p, note q) { return p.x == q.x && p.y == q.y && p.z == q.z; }
void pre() {
fac[0] = 1;
for (int i = 1; i <= 300000; ++i) fac[i] = fac[i - 1] * i % P;
inv[0] = inv[1] = 1;
for (int i = 2; i <= 300000; ++i) inv[i] = inv[P % i] * (P - P / i) % P;
for (int i = 2; i <= 300000; ++i) inv[i] = inv[i] * inv[i - 1] % P;
}
ll C(int n, int m) {
return fac[n] * inv[m] % P * inv[n - m] % P;
}
ll calc(int dx, int dy, int dz) {
return C(dx + dy + dz, dx) * C(dy + dz, dy) % P;
}
int main() {
//freopen("a.in", "r", stdin);
//freopen("a.out", "w", stdout);
pre();
scanf("%d%d", &n, &m);
a[++tot] = (note){0, 0, 0};
for (int i = 1; i <= m; ++i) ++tot, scanf("%d%d%d", &a[tot].x, &a[tot].y, &a[tot].z);
a[++tot] = (note){n, n, n};
sort(a + 1, a + tot + 1, cmp);
tot = unique(a + 1, a + tot + 1) - a - 1;
f[1] = P - 1;
for (int i = 2; i <= tot; ++i)
for (int j = 1; j < i; ++j)
if (a[j].x <= a[i].x && a[j].y <= a[i].y && a[j].z <= a[i].z)
f[i] = (f[i] - calc(a[i].x - a[j].x, a[i].y - a[j].y, a[i].z - a[j].z) * f[j] % P + P) % P;
printf("%lld
", f[tot]);
return 0;
}