题目
P1249 最大乘积
分析
一道高精+贪心
一个数拆的越多乘积会越大,但不要拆出1,这样浪费了
所以就2, 3, 4, 5, ~
但也不能连续的一直拆, 因为可能不够拆了
所以就可以跳出那个数 把那个数拆给前面的
大概就这样
上代码
#include<bits/stdc++.h>
using namespace std;
const int N = 500;
string f(int x) {
char c[10], temp;
int i = 0, j;
do {
c[i] = x%10+'0';
x /= 10;
i++;
} while(x != 0);
c[i] = '\0';
for (i--, j = 0; j <= i/2; j++, i--) {
temp = c[j];
c[j] = c[i];
c[i] = temp;
}
return c;
}
string mul(string a, string b) {
string s;
int A[N], B[N], C[N];
int la = a.size(), lb = b.size();
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
memset(C, 0, sizeof(C));
for (int i = 0; i < la; i++) A[la-i] = a[i]-'0';
for (int i = 0; i < lb; i++) B[lb-i] = b[i]-'0';
for (int i = 1; i <= la; i++) {
for (int j = 1; j <= lb; j++) {
C[i+j-1] += A[i]*B[j];
C[i+j] += C[i+j-1]/10;
C[i+j-1] %= 10;
}
}
if (C[la+lb]) s += C[la+lb]+'0';
for (int i = la+lb-1; i >= 1; i--) {
s += C[i]+'0';
}
return s;
}
int n, c = 1, ans[1001];
string s[1001], m = "1";
int main() {
scanf("%d", &n);
if ( n <= 4 ){
printf ( "%d\n%d\n", n, n );
return 0;
}//特判,如果n小于5,自己本身就是最优解
for (int i = 2; i <= n; i++) {
if (n >= i) {
ans[c++] = i;
s[c-1] = f(i);
n -= i;
} else break;
}
for (int i = c-1; i >= 1; i++) {
if (n > 0) {
ans[i]++;
s[i] = f(ans[i]);
n--;
}
}
if (n > 0) {
ans[c-1]++;
s[c-1] = f(ans[c-1]);
}
for (int i = 1; i < c; i++) {
cout << ans[i] << " ";
m = mul(s[i], m);
}
cout << endl << m;
return 0;
}
chapter 章节