题目大意
从
(
0
,
0
,
0
)
(0,0,0)
(0,0,0)走到
(
n
,
n
,
n
)
(n,n,n)
(n,n,n),每一步可以从
(
x
,
y
,
z
)
(x,y,z)
(x,y,z)走到
(
x
+
1
,
y
,
z
)
(x+1,y,z)
(x+1,y,z)或
(
x
,
y
+
1
,
z
)
(x,y+1,z)
(x,y+1,z)或
(
x
,
y
,
z
+
1
)
(x,y,z+1)
(x,y,z+1),给出
m
m
m个不允许经过的点,求这样走的方案数。
n
≤
100000
,
m
≤
5000
n\leq 100000,m\leq 5000
n≤100000,m≤5000
Solution
很经典的题目。
枚举 i i i个点必定经过然后容斥,复杂度 O ( m ! ) O(m!) O(m!)。
考虑把这个过程放到递推上,设
f
i
f_i
fi表示从
(
0
,
0
,
0
)
(0,0,0)
(0,0,0)走到第
i
i
i个点,且不经过其他点的方案数;记
j
→
i
j \to i
j→i表示
j
j
j能到达
i
i
i,
g
(
a
,
b
,
c
)
g(a,b,c)
g(a,b,c)表示从
(
0
,
0
,
0
)
(0,0,0)
(0,0,0)以任意方式走到
(
a
,
b
,
c
)
(a,b,c)
(a,b,c)的方案数,有:
f
i
=
∑
j
→
i
−
f
j
∗
g
(
x
i
−
x
j
,
y
i
−
y
j
,
z
i
−
z
j
)
f_i=\sum_{j \to i}-f_j*g(x_i-x_j,y_i-y_j,z_i-z_j)
fi=j→i∑−fj∗g(xi−xj,yi−yj,zi−zj)
怎么推的?
f
j
f_j
fj里的所有路径经过
i
i
i后都多了一个点,所以容斥系数都要乘以
−
1
-1
−1。
这样就做到了 O ( m 2 ) O(m^2) O(m2)。
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\n", f[tot]);
return 0;
}