HDOJ 5646 DZY Loves Partition(数学)

DZY Loves Partition

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 862    Accepted Submission(s): 317


Problem Description
DZY loves partitioning numbers. He wants to know whether it is possible to partition n into the sum of exactly k distinct positive integers.

After some thinking he finds this problem is Too Simple. So he decides to maximize the product of these k numbers. Can you help him?

The answer may be large. Please output it modulo 109+7 .
 

Input
First line contains t denoting the number of testcases.

t testcases follow. Each testcase contains two positive integers n,k in a line.

( 1t50,2n,k109 )
 

Output
For each testcase, if such partition does not exist, please output 1 . Otherwise output the maximum product mudulo 109+7 .
 

Sample Input
  
  
4 3 4 3 2 9 3 666666 2
 

Sample Output
  
  
-1 2 24 110888111
Hint
In 1st testcase, there is no valid partition. In 2nd testcase, the partition is $3=1+2$. Answer is $1\times 2 = 2$. In 3rd testcase, the partition is $9=2+3+4$. Answer is $2\times 3 \times 4 = 24$. Note that $9=3+3+3$ is not a valid partition, because it has repetition. In 4th testcase, the partition is $666666=333332+333334$. Answer is $333332\times 333334= 111110888888$. Remember to output it mudulo $10^9 + 7$, which is $110888111$.

 

题意:将n恰好拆分成k个整数之和,且要求输出这k个数的最大乘积,若不存在输出-1.


题解:一脸懵逼。见代码注释。


代码如下:


#include<cstdio>
#include<cstring>
#define LL long long 
#define mod 1000000007
int main()
{
	int t,i;
	LL n,k,ans;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld%lld",&n,&k);
		ans=1;
		if(n<(k*(k+1)/2))//没有解的情况 
		{
			printf("-1\n");
			continue;
		}
		if(n%k==0)//能整除的情况 
		{
			int average=n/k;
			if(k&1)//k为奇数的情况 
				ans=average;
			for(i=1;i<=k/2;++i)
				ans=ans*(average-i)*(average+i)%mod;
		} 
		else
		{
			int add=k*(k-1)/2;//先假设这k个数是连续的序列,且把第一个数叫做基数,这里的add是基数之后的k-1个数一共需要增加的值 
			int num=(n-add)%k;//按照上方假设,这里的num一定是0,但事实不一定如此,num为多出来的数,需要将这num加入序列。要想这k个数的乘积最大,那么一定要从序列中最大的数开始增加起,且每个数加1 
			int base=(n-add)/k;//base表示基数 
			for(i=1;i<=num;++i)
				ans=ans*(base+k-i+1)%mod;//需要增加1的数,从最后一个数加起 
			while(i<=k)
				ans=ans*(base+k-i++)%mod;//不需要加一的数 
		}
		printf("%I64d\n",ans);
	}
	return 0;
} 



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值