hdu-5646 DZY Loves Partition(贪心)

题目链接:

DZY Loves Partition

Time Limit: 4000/2000 MS (Java/Others)   

 Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 323    Accepted Submission(s): 127


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
 
题意:
 
把n拆成k个互不相同的正整数,并使其乘积最大,问这个乘积最大是多少;
思路:首先判断是否能拆分,能拆分的话把这些平分,并使其成递增的数组,再把n/k剩下的n%k分给剩下的数,k为odd是从最大的数往前n%k个数分别+1;k位even时先把k/2个小点数从大到小分别+1,还有多的话在把剩下的大的k/2个数从大到小+1;最后求得的积就是结果;
 
 
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const long long mod=1e9+7;
int t;
long long n,k,a[200000];
int main()
{

    scanf("%d",&t);
    while(t--)
    {
        cin>>n>>k;
        long long x=n/k;
        if(k*(k+1)/2>n)
        {
            printf("-1\n");
        }
        else
        {
            if(k%2)
            {
                for(int i=k/2;i>0;i--)
                {
                    a[i]=x-(k/2-i+1);
                }
                for(int i=k/2+1;i<=k;i++)
                {
                    a[i]=x+(i-k/2-1);
                }
                int m=n%k;
                for(int i=k;m>0;m--,i--)
                {
                    a[i]++;
                }
            }
            else
            {
                for(int i=k/2;i>0;i--)
                {
                    a[i]=x-(k/2-i+1);
                }
                for(int i=k/2+1;i<=k;i++)
                {
                    a[i]=x+(i-k/2);
                }
                int m=n%k;
                for(int i=k/2;i&&m;i--,m--)
                {
                    a[i]++;
                }
                if(m>0)
                {
                    for(int i=k;i>k/2&&m;i--,m--)
                    {
                        a[i]++;
                    }
                }
            }
            long long ans=a[1];
            for(int i=2;i<=k;i++)
            {
                ans*=a[i];
                ans%=mod;
            }
            cout<<ans<<"\n";
        }

    }
    return 0;
}

 

posted @ 2016-03-19 22:43  LittlePointer  阅读(496)  评论(0编辑  收藏  举报