HDOJ 3944 DP?

尽量沿着边走距离最短,化减后 C(n+1,k)+ n - k,

预处理阶乘,Lucas定理组合数取模


DP?

Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 128000/128000 K (Java/Others)
Total Submission(s): 1899    Accepted Submission(s): 633


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
 


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long int LL;

LL n,k,p;

LL fact[1300][11000];

LL QuickPow(LL x,LL t,LL m)
{
	if(t==0) return 1LL;
	LL e=x,ret=1LL;
	while(t)
	{
		if(t&1LL) ret=(ret*e)%m;
		e=(e*e)%m;
		t>>=1LL;
	}
	return ret%m;
}

int prime[2000],pr;
bool vis[10100];

void get_prime()
{
	for(int i=2;i<10100;i++)
	{
		if(vis[i]==false)	
			prime[pr++]=i;
		for(int j=2*i;j<10100;j+=i)
			vis[j]=true;
	}
}

void get_fact()
{
	for(int i=0;i<1240;i++)
	{
		fact[i][0]=1LL;
		for(int j=1;j<=prime[i]+10;j++)	
		{
			fact[i][j]=(fact[i][j-1]*j)%prime[i];	
		}
	}
}

LL Lucas(LL n,LL m,LL p)
{
	LL ret=1LL;
	int id=lower_bound(prime,prime+pr,p)-prime;
	while(n&&m)
	{
		LL a=n%p,b=m%p;
		if(a<b) return 0;
		ret=(ret*fact[id][a]*QuickPow((fact[id][b]*fact[id][a-b])%p,p-2,p)%p)%p;
		n/=p; m/=p;
	}
	return ret%p;
}

int main()
{
	get_prime();
	get_fact();
	int cas=1;
	while(scanf("%I64d%I64d%I64d",&n,&k,&p)!=EOF)
	{
		if(k>n/2) k=n-k;
		LL ans=(Lucas(n+1,k,p)+n-k)%p;
		printf("Case #%d: %I64d\n",cas++,ans);
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值