插入加号求最小值
#include <iostream> #include <string> using namespace std; int get(char *c,int a,int b); int main() { char b[11]; int f[11][11]; int c[11][11]; int n,i,j,k,r; int tmp,d; for(i = 0;i < 11;i++) for(j = 0;j < 11;j++) { f[i][j] = 0; c[i][j] = 0; } cout<<"请输入整数n:"; cin>>b; for(i = 0,n = 0;b[i] != '\0';i++) n++; cout<<"请输入插入加号的个数r:"; cin>>r; while(r >= n) { cout<<"无法在"<<n<<"个数中插入"<<r<<"个加号!"<<endl; cout<<"输入插入的加号个数:"; cin>>r; } for(i = 1;i <= n;i++) { f[0][i] = get(b,1,i); } for(i = 2;i <= n;i++) for(j = 1;j < i && j <= r;j++) { tmp = 999999999; for(k = i-1;k > j;k --) { d = get(b,k+1,i); if(f[j-1][k] + d < tmp) { tmp = f[j-1][k] + d; c[j][i] = c[j-1][k]; c[j][i] = c[j][i] | (0x01 << (k-1)); } } f[j][i] = tmp; } for(i = 0;i <= n;i++) { cout<<b[i]; if(c[r][n] & (0x01 << i)) cout<<"+"; } cout<<"="; cout<<f[r][n]<<endl; return 0; } int get(char *c,int a,int b) { int result = 0; for(int i = a-1;i < b;i++) { result = result*10 + c[i]- '0'; } return result; }