ZOJ 4536 ZOJ Monthly, October 2011 I

 
How Many Sets II

Time Limit: 2 Seconds      Memory Limit: 65536 KB

Given a set S = {1, 2, ..., n}, number m and p, your job is to count how many set T satisfies the following condition:

  • T is a subset of S
  • |T| = m
  • T does not contain continuous numbers, that is to say x and x+1 can not both in T

Input

There are multiple cases, each contains 3 integers n ( 1 <= n <= 109 ), m ( 0 <= m <= 104, m <= n ) and p ( p is prime, 1 <= p <= 109 ) in one line seperated by a single space, proceed to the end of file.

Output

Output the total number mod p.

Sample Input
5 1 11
5 2 11
Sample Output
5
6
这个题也是找规律。
规律其实很简单,就是一个组合数:C(n-m+1,m)
但是注意一下当n-m+1<m的时候输出0。
当然,组合数取余,自然要用到lucas定理咯~
 
代码:
#include<stdio.h>
#include<string.h>
#include<iostream>

using namespace std;

typedef long long ll;

ll power(ll p,ll n,ll m)
{
	ll sq=1;
	while(n)
	{
		if(n%2==1)
			sq=(sq%m)*(p%m)%m;
		p=(p%m)*(p%m)%m;
		n=n/2;
	}
	return sq%m;
}

ll C(ll n,ll r,ll p)
{
	ll i,res=1,t;
	for(i=1;i<=r;i++)
	{
		res=(res%p)*((n-i+1)%p)%p;
		t=power(i,p-2,p);
		res=(res%p)*(t%p)%p;
	}
	return res;
}

ll lucas(ll n,ll r,ll p)
{
	if(n<r)
		return 0;
	return C(n,r,p);
}

int main()
{
	ll n,m,p,res,x,y;
	while(cin>>n>>m>>p)
	{
		if(n==0&&m==0&&p==0)
			break;
		res=1;
		x=n-m+1;
		y=m;
		if(x<y)
		{
			cout<<0<<endl;
			continue;
		}
		while(x&&y)
		{
			res=res*lucas(x%p,y%p,p)%p;
			if(res==0)
				break;
			x=x/p;
			y=y/p;
		}
		cout<<res<<endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值