DP?
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 128000/128000 K (Java/Others)Total Submission(s): 2833 Accepted Submission(s): 880
Problem Description
Figure 1 shows the Yang Hui Triangle. We number the row from top to bottom 0,1,2,…and the column from left to right 0,1,2,….If using C(n,k) represents the number of row n, column k. The Yang Hui Triangle has a regular pattern as follows.
C(n,0)=C(n,n)=1 (n ≥ 0)
C(n,k)=C(n-1,k-1)+C(n-1,k) (0<k<n)
Write a program that calculates the minimum sum of numbers passed on a route that starts at the top and ends at row n, column k. Each step can go either straight down or diagonally down to the right like figure 2.
As the answer may be very large, you only need to output the answer mod p which is a prime.
Input
Input to the problem will consists of series of up to 100000 data sets. For each data there is a line contains three integers n, k(0<=k<=n<10^9) p(p<10^4 and p is a prime) . Input is terminated by end-of-file.
Output
For every test case, you should output "Case #C: " first, where C indicates the case number and starts at 1.Then output the minimum sum mod p.
Sample Input
1 1 2 4 2 7
Sample Output
Case #1: 0 Case #2: 5
Author
phyxnj@UESTC
Source
Recommend
xubiao
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
namespace prime_table{
const int MAX_N = 1e4;
const int MAX_M = sqrt(MAX_N+0.5);
int all=0;
int pr[MAX_N/10+300];
bool isp[MAX_N+10];
inline void init(){
memset(isp,0,sizeof(isp));
for(int i=2;i<=MAX_N;i++){
if(!isp[i]){pr[all++]=i;
if(i<=MAX_M)
for(int j=i*i;j<=MAX_N;j+=i){
isp[j]=true;
}
}
}
// printf("all=%d\n",all);
}
}
using namespace prime_table;
namespace Combinatorial{
const int N = 10005;/** n 的最大 值 **/
int fac[N+5][1300],ifac[N+5][1300];
/**快速幂**/
int q_pow(int a,int b,int mod){
int n=1;
while(b){
if(b&1){
n=(int)(1LL*n*a%mod);
}
a=(int)(1LL*a*a%mod);
b>>=1;
}
return n;
}
/**预处理逆元**/
inline void init_QP(){
for(int i=0;i<all;i++){
fac[0][i]=ifac[0][i]=1;
for(int j=1;j<=pr[i];j++){
fac[j][i]=(int)(1LL*fac[j-1][i]*j%pr[i]);
ifac[j][i]=q_pow(fac[j][i],pr[i]-2,pr[i]);
}
}
}
int C(int a,int b,int id){
if(b>a || b<0)return 0;
return (int)(1LL*fac[a][id]*ifac[b][id]%pr[id]*ifac[a-b][id]%pr[id]);
}
int lucas(int a,int b,int id){
if(!a||!b){
return 1;
}
return (int)(1LL*lucas(a/pr[id],b/pr[id],id)*C(a%pr[id],b%pr[id],id)%pr[id]);
}
}
using namespace Combinatorial;
int main(){
init();init_QP();
int n,k,p,t=0;
while(scanf("%d%d%d",&n,&k,&p)==3){
int *id = lower_bound(pr,pr+all,p);
k = max(k,n-k);
printf("Case #%d: %d\n",++t,(lucas(n+1,k+1,id-pr)+k)%p);
}return 0;
}