您的位置:首页 > 其它

Codeforces 559C Gerald and Giant Chess 组合数学 DP

2015-08-14 13:10 519 查看
题目大意:

就是现在对于一个H*W的棋盘从点(1, 1)走到(H, W), 每次只能x++或者y++地走, 其中棋盘上有n个点是坏点, 也就是不能走的点, 那么从(1, 1)到(H, W)不经过这n个坏点的路径有多少种, H, W <= 100000, n <= 2000

大致思路:

首先在不考虑坏点的情况下, 从(x1, y1)走到(x2, y2), x2 >= x1, y2 >= y1一共有C(x2 - x1 + y2 - y1, x2 - x1)种方案

那么考虑坏点的情况要去除掉

先将所有坏点坐标按照x第一关键字, y第二关键字排序

用dp[i]表示当前从起点到达第i个坏点没有经过任何其他坏点的路径数

那么对于第i个坏点 dp[i] = C(xi - 1 + yi - 1, xi - 1) - sigma(dp[j]*C(xi - xj + yi - yj, xi - xj))

其中j < i且满足xj <= xi, yj <= yi, 由于dp[j]表示的是直到到达j点前面都没有经过坏点的路径, 对于j < i的所有j, dp[k]*C(xi - xj + yi - yj, xi - xj)表示的路径之间是没有重复的

于是时间复杂度为O(nlogn + n*n), 注意组合数可以预处理阶乘, 当然由于这题时限卡的不是很紧, 不用预处理阶乘的逆元, 每次直接求逆元也可以过....

代码如下:

Result  :  Accepted     Memory  :  1608 KB     Time  :  1170 ms

/*
* Author: Gatevin
* Created Time: 2015/8/14 12:49:15
* File Name: Sakura_Chiyo.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;

const lint mod = 1e9 + 7;

struct point
{
int x, y;
point(){}
};

bool cmp(point p1, point p2)
{
return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y);
}

point p[2020];
int H, W, n;
lint dp[2020];
lint fac[200010];

lint quick(lint base, lint pow)
{
lint ret = 1;
while(pow)
{
if(pow & 1) ret = ret*base % mod;
pow >>= 1;
base = base*base % mod;
}
return ret;
}

lint C(lint x, lint y)
{
return fac[x]*quick(fac[y]*fac[x - y] % mod, mod - 2) % mod;
}

int main()
{
fac[0] = 1;
for(int i = 1; i < 200010; i++)
fac[i] = fac[i - 1]*i % mod;
scanf("%d %d %d", &H, &W, &n);
for(int i = 1; i <= n; i++)
scanf("%d %d", &p[i].x, &p[i].y);
p[0].x = p[0].y = 1;
p[n + 1].x = H, p[n + 1].y = W;
sort(p, p + n + 2, cmp);
dp[0] = 1;
for(int i = 1; i <= n + 1; i++)
{
dp[i] = C(p[i].x - p[0].x + p[i].y - p[0].y, p[i].x - p[0].x);
for(int j = 1; j < i; j++)
if(p[j].y <= p[i].y)
dp[i] = (dp[i] - dp[j]*C(p[i].x - p[j].x + p[i].y - p[j].y, p[i].x - p[j].x) % mod + mod) % mod;
}
printf("%I64d\n", dp[n + 1]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Codeforces 559C DP