HDU - 5646 DZY Loves Partition (二分 + 数学)

HDU - 5646 DZY Loves Partition (二分 + 数学)

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.

(1≤t≤50,2≤n,k≤109)
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 3=1+2 3=1+2. Answer is 1 × 2 = 2 1\times 2 = 2 1×2=2.
In 3rd testcase, the partition is 9 = 2 + 3 + 4 9=2+3+4 9=2+3+4. Answer is 2 × 3 × 4 = 24 2\times 3 \times 4 = 24 2×3×4=24. Note that 9 = 3 + 3 + 3 9=3+3+3 9=3+3+3 is not a valid partition, because it has repetition.
In 4th testcase, the partition is 666666 = 333332 + 333334 666666=333332+333334 666666=333332+333334. Answer is 333332 × 333334 = 111110888888 333332\times 333334= 111110888888 333332×333334=111110888888. Remember to output it mudulo 1 0 9 + 7 10^9 + 7 109+7, which is 110888111 110888111 110888111.

题目大意:

给你一个数n 和一个k
让你把这个n 分成k不同数的和,并让这k个数乘积最大,结果取模1e9+7;

解题思路:

几个不同数的和是n 那什么时候它们的乘积最大呢?
当它们的公差恰好为1时乘积最大。 这是个结论,记住即可。

所以可以二分等差数列的起始的一个数。
因为我们要分成k个数乘积,所以说它不一定恰好能分成k个公差为1的连续序列。
这时候怎么加才能让乘积最大呢?假设n是13 k是3 那么只能分成 3 4 5这时候和是12
那么最后那个1怎么加才能让乘积最大呢,那就是加到5上 变成3 4 6 。

AC代码:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e6+10;
const ll mod= 1e9+7;
ll a[maxn];
ll n,k;
ll solve(ll mid){
	return (mid+mid+k-1)*k/2;
}
int main(){
	int t;
	cin>>t;
	while(t--){
		scanf("%lld%lld",&n,&k);
		ll min_num = (1+k)*k/2;
		if(n<min_num){
			puts("-1");
			continue;
		}
	
		ll l = 1;
		ll r = n;
		ll st = 1;
		while(l<=r){
			int mid = (l+r)/2;
			if(solve(mid)<=n){
				st = mid;
				l = mid+1;
			}else{
				r = mid-1;
			}
		}
		ll last = n-(st+st+k-1)*k/2;
		for(int i=0;i<k;i++){
			a[i] = st+i;
		}
		for(int i=k-1;;i--){
			if(last<=0) break;
			a[i]++;
			last--;
		}
		ll ans =1;
		for(int i=0;i<k;i++){
			ans = (ans*a[i])%mod;
		}
		printf("%lld\n",ans);
	}
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值