poj1942——组合数学
Paths on a Grid
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 22473 | Accepted: 5522 |
Description
Imagine you are attending your math lesson at school. Once again, you are bored because your teacher tells things that you already mastered years ago (this time he's explaining that (a+b)2=a2+2ab+b2). So you decide to waste your time with drawing modern art instead.
Fortunately you have a piece of squared paper and you choose a rectangle of size n*m on the paper. Let's call this rectangle together with the lines it contains a grid. Starting at the lower left corner of the grid, you move your pencil to the upper right corner, taking care that it stays on the lines and moves only to the right or up. The result is shown on the left:
Really a masterpiece, isn't it? Repeating the procedure one more time, you arrive with the picture shown on the right. Now you wonder: how many different works of art can you produce?
Fortunately you have a piece of squared paper and you choose a rectangle of size n*m on the paper. Let's call this rectangle together with the lines it contains a grid. Starting at the lower left corner of the grid, you move your pencil to the upper right corner, taking care that it stays on the lines and moves only to the right or up. The result is shown on the left:
Really a masterpiece, isn't it? Repeating the procedure one more time, you arrive with the picture shown on the right. Now you wonder: how many different works of art can you produce?
Input
The input contains several testcases. Each is specified by two unsigned 32-bit integers n and m, denoting the size of the rectangle. As you can observe, the number of lines of the corresponding grid is one more in each dimension. Input is terminated by n=m=0.
Output
For each test case output on a line the number of different art works that can be generated using the procedure described above. That is, how many paths are there on a grid where each step of the path consists of moving one unit to the right or one unit up? You may safely assume that this number fits into a 32-bit unsigned integer.
Sample Input
5 4 1 1 0 0
Sample Output
126 2
题意:从左下角到右上角的路径数目
思路:本来用的dp,后来发现dp方程正是杨辉三角的递推公式。。处理C(n,k)最重要的是防止阶乘越界,用递推式是个不错的选择,但难以防止MLE,下面这种“先除后乘”再强制类型转换以前在codeforces上用过,这次居然没想起来。。。看了题解后才AC了。。
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> using namespace std; const int maxn=10200; const int INF=(1<<28); typedef long long ll; ll n,m; ll C(ll n,ll k) { double res=1.0; if(k>n-k) k=n-k; ll a=n,b=k; while(b>0){ res*=a*1.0/b; a--; b--; } if(res-(ll)res>0.5) res++; return res; } int main() { while(cin>>n>>m,n||m){ cout<<C(n+m,n)<<endl; } return 0; }