Algorithm Analysis - optimal decomposition problem

Question:
Let n be a positive integer, n is now required to decompose into a number of mutually different natural numbers and the maximum product of these natural number.
Input 10
Output 30

Analysis and answers: note, if a + b = const, then | ab & | smaller, a * b increases.
Greedy strategy: The decomposed into n successive natural numbers from the beginning and 2, if a last remaining number, this number in a uniform manner under the item of priority given to the foregoing.

code show as below:

#include <iostream>
#include <bits/stdc++.h>
#define M 100


using namespace std;


int main(){
    int k,n,a[M];
    int product=1; //最大积
    cin>>n;


    k=1;
    if(n<3){ a[k]=0;return 0;} //当<3时,即为1、2,只能分解为0和本身,所以积为0
    if(n<5){ a[k]=1;n--;return 0;} //当n为3或4时,分解为1和 n-1;


    //当n>5时,将n分成从2开始的连续自然数的和,
    //如果最后剩下一个数,将此数在后项优先的方式下均匀分给前面各项
    a[k]=2;n-=2;
    while(n>a[k]){
        k++;a[k]=a[k-1]+1;n-=a[k];
    }
    if(n==a[k]){ a[k]++;n--;} //例如13,分解为2、3、4、4,在4分解给前项时最后的4加的是2,前面加1,为3、4、6
                            //所以如果n=a[k],先给a[k]分一个1,然后后面再均加1
    for(int i=0;i<n;i++){
        a[k-i]++;
    }


    for(int i=1;i<=k;i++){
        product*=a[i];
    }


    cout<<product;


return 0;
}


Guess you like

Origin blog.csdn.net/qq_34851243/article/details/78651295