1. 程式人生 > >hdu5698瞬間移動(楊輝三角+快速冪+逆元)

hdu5698瞬間移動(楊輝三角+快速冪+逆元)

tle tom tro int 公式 ios put jpg left

瞬間移動

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2121 Accepted Submission(s): 949


Problem Description 有一個無限大的矩形,初始時你在左上角(即第一行第一列),每次你都可以選擇一個右下方格子,並瞬移過去(如從下圖中的紅色格子能直接瞬移到藍色格子),求到第n行第m列的格子有幾種方案,答案對1000000007取模。

技術分享圖片

Input 多組測試數據。

兩個整數n,m(2n,m100000)

Output 一個整數表示答案

Sample Input 4 5

Sample Output 10

題意:從左上角開始走,每次只能走到右下任意位置,找規律後發現他是一個斜著的楊輝三角。引用一下別人的

技術分享圖片

題目中的n,m是第n行第m列,所以可以得到組合數c(m+n-4,m-2)這個就是答案,用快速冪加逆元計算結果

 1 #include <iostream>
 2 using namespace std;
 3 typedef long long ll;
 4 const int mod = 1e9 + 7
; 5 ll quick_pow(ll a, ll b) { ///快速冪求逆元 6 ll ans = 1; 7 while(b) { 8 if(b % 2) { 9 ans *= a; 10 ans %= mod; 11 } 12 a *= a; 13 a %= mod; 14 b /= 2; 15 } 16 return ans; 17 } 18 ll C(int m, int n) { ///
組合數公式:C(m, n) =m!/(n!(m-n)!) 19 if(n > m) 20 return 0; 21 ll ans = 1; 22 for(int i = 1; i <= n; i++) { 23 ll a, b; 24 a = (m - n + i) % mod; 25 b = i % mod; 26 ans = ans * (a * quick_pow(b, mod - 2) % mod) % mod; 27 } 28 return ans; 29 } 30 int main() { 31 ll m, n; 32 while(~scanf("%lld %lld",&n,&m)) { 33 printf("%lld\n",C(m+n-4,m-2)); 34 } 35 return 0; 36 }

hdu5698瞬間移動(楊輝三角+快速冪+逆元)