山东省第八届acm省赛D题 HEX

题目来戳呀

Problem Description

On a plain of hexagonal grid, we define a step as one move from the current grid to the lower/lower-left/lower-right grid. For example, we can move from (1,1) to (2,1), (2,2) or (3,2).
In the following graph we give a demonstrate of how this coordinate system works.
Your task is to calculate how many possible ways can you get to grid(A,B) from gird(1,1), where A and B represent the grid is on the B-th position of the A-th line.
这里写图片描述

Input

For each test case, two integers A (1<=A<=100000) and B (1<=B<=A) are given in a line, process till the end of file, the number of test cases is around 1200.

Output

For each case output one integer in a line, the number of ways to get to the destination MOD 1000000007.

Example Input

1 1
3 2
100000 100000

Example Output

1
3
1

题意:

菱形的区域里,每个位置可以从上面向左、向右或向下得到(即↙↓↘),
问从(1,1)到(a,b)共有多少种走法。

想法:

在高中学过,假设矩形的长为len,宽度为wid,从左上到右下(对角位置)的方法共有(len+wid)!/len!*wid!种。

记从左边得到的为len,从右边得到的为wid,从中间得到的为c。

1.我们讨论只从两边得到的: ans=(len+wid)!/len!*wid!;
2.一次↓ 相当于 一次↙+一次↘(就是说 对角一步走 相当于 走两次直角边 ):ans=(len+wid+c)!/len!*wid!*c!。所以当c++时,len-–,wid—,直到减到其中一个为0时,结束。

因为最后结果要取模数很大,所以要用乘法逆元,这里选择用线性求逆元。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int adj[5000];
const int mod=1e9+7;
typedef long long ll;
ll inv(ll b)//线性求b的逆元
{
    if(b<=1)return 1;
    return (mod-mod/b)*inv(mod%b)%mod;
 }
int main()
{
    int x,y;
    ll fac[101010]={1};
    ll Inv[101010]={1,1};
    for(int i=1;i<100101;i++)
    {
        fac[i]=(fac[i-1]*i)%mod;//i的阶乘
        Inv[i]=inv(fac[i]);//i的阶乘的逆元
    }
    while(~scanf("%d%d",&x,&y))
    {
        int right=x-y;
        int left=x-1-right;
        int c=0;//中路
        ll ans=0;
        while(right>=0&&left>=0)//所有组合方式
        {
            ll sum=(((fac[left+right+c]*Inv[left])%mod*Inv[right])%mod*Inv[c])%mod;
            ans=(ans+sum)%mod;
            left--;
            right--;
            c++;//一条中路相当于是一条左路加一条右路
        }
        printf("%lld\n",ans);
    }
    return 0;
}

ps:那个对角公式真的学过吗+_+麻麻请告诉我我的高中真的存在过吗QAQ

发布了87 篇原创文章 · 获赞 8 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章