1. 程式人生 > >最優分解(貪心演算法)

最優分解(貪心演算法)

#include<stdio.h>
#include<stdlib.h>

int main(){
	int n,i,sum=0;
	int diff,result,j=0;
	scanf("%d",&n);
	int *arr = (int*)malloc(n*sizeof(int));
	for(i=2;i<n;i++){
		if((sum+i)<=n){
			sum+=i;
			arr[j]=i;
			j++;
		}
		else
		   break;
	}
	diff = n-sum;
	i=j-1;
	while(diff){
		arr[i]++;
		i=(i-1+j)%j;
		diff--;
	}
	result =1;
	for(i=0;i<j;i++){
		result *= arr[i];
	}
	printf("%d",result);
	return 0;
	
}