题意:
一个n*m的棋盘,初始时刻一枚棋子在(1,1)位置,每次他只能从(x,y)移动到(x+1,y+2)或者(x+2,y+1)的位置,棋盘上还有一些障碍点,这些点不能到达,问最后旗子能到达(n,m)的方案数。
思路:
首先画几个例子,观察旗子能到达的点的规律,统计出规律后发现,能到达的点组成了一个杨辉三角,这时候为了方便处理,进行坐标转换,以杨辉三角最左边的一条边和最右边的一条边作为坐标轴,重新计算能到达的点的坐标,很显然,障碍点只有是能到达的点时才会对最终结果产生影响。
坐标转化完成后,(x1,y1)到(x2,y2)的方案数就是C(x2-x1+y2-y1,x2-x1),这时候定义dp[i]表示的是第i个点到终点且不经过任何障碍点的方案数,每次计算的时候只要先算出该点到终点总的方案数,然后枚举经过最后一个障碍点,减掉这部分的路径的方案数,就是不经过障碍点的方案数。
dp要记得清零。
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
const int MAXN = 200;
const ll MOD = 110119;
struct Point {
ll x, y;
} p[MAXN];
Point change(Point a) { // 坐标转换,不能到达的点标记为(-1, -1)
Point res = (Point) {-1, -1};
ll sum = a.x + a.y;
if ((sum - 2) % 3 != 0) return res;
ll L = (sum - 2) / 3 + 1, R = (sum - 2) / 3 * 2 + 1;
if (a.x < L || a.x > R || a.y < L || a.y > R) return res;
res.x = a.x - L + 1;
res.y = R - a.x + 1;
return res;
}
ll mod_pow(ll a, ll n, ll p) {
ll ret = 1, A = a;
while (n) {
if (n & 1) ret = (ret * A) % p;
A = (A * A) % p;
n >>= 1;
}
return ret;
}
ll fact[MOD + 10];
void init(ll p) {
fact[0] = 1;
for (int i = 1; i <= p; i++)
fact[i] = fact[i - 1] * i % p;
}
ll Lucas(ll a, ll k, ll p) {
ll re = 1;
while (a && k) {
ll aa = a % p, bb = k % p;
if (aa < bb) return 0;
re = re * fact[aa] * mod_pow(fact[bb] * fact[aa-bb] % p, p - 2, p) % p;
a /= p;
k /= p;
}
return re;
}
bool cmp(const Point a, const Point b) {
return a.x + a.y > b.x + b.y;
}
ll calpath(Point a, Point b) { // 计算a到b的方案数
if (a.x <= b.x && a.y <= b.y) {
return Lucas(b.x - a.x + b.y - a.y, b.x - a.x, MOD);
}
return 0;
}
ll dp[MAXN]; // dp[i]表示的是第i个点到终点且不经过任何障碍点的方案数。
int main() {
init(MOD);
ll n, m;
int r, cs = 0;
while (scanf("%lld%lld%d", &n, &m, &r) == 3) {
vector <Point> pt;
bool flag = true;
for (int i = 1; i <= r; i++) {
scanf("%lld%lld", &p[i].x, &p[i].y);
if (p[i].x == n && p[i].y == m) flag = false;
p[i] = change(p[i]);
if (p[i].x != -1 && p[i].y != -1)
pt.push_back(p[i]);
}
Point ed = change ((Point) {n, m});
if (ed.x == -1 || ed.y == -1 || !flag) {
printf("Case #%d: 0\n", ++cs);
continue;
}
pt.push_back((Point) {1, 1});
sort(pt.begin(), pt.end(), cmp);
int cnt = pt.size();
for (int i = 0; i < cnt; i++) {
dp[i] = calpath(pt[i], ed); // i点到终点的所有方案数
for (int j = 0; j < i; j++) { // 枚举经过的最后一个障碍点,保证不存在重复遗漏情况
dp[i] = (dp[i] - (calpath(pt[i], pt[j]) * dp[j]) % MOD + MOD) % MOD; //所有方案减去经过障碍点的方案
}
}
printf("Case #%d: %lld\n", ++cs, dp[cnt - 1]);
}
return 0;
}