给出一个Max 和一串数字。将这一串数字分割成若干个数,其和为sum。求最接近但不超过Max的sum。。。
将这个sum及这若干个数输出来。
DFS + 打印路径
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cstdio> 6 7 using namespace std; 8 9 char SNum[10]; 10 11 struct N 12 { 13 int data,ans,pre; 14 N *l,*r; 15 }*root; 16 17 N *creat() 18 { 19 N *p = (N *)malloc(sizeof(N)); 20 p->l = p->r = NULL; 21 return p; 22 } 23 24 struct P 25 { 26 int site,pre; 27 }path[100000]; 28 29 int top; 30 31 void insert(N *&root,int data,int pre) 32 { 33 if(root == NULL) 34 { 35 root = creat(); 36 root->ans = 1; 37 root->pre = pre; 38 root->data = data; 39 return ; 40 } 41 if(data < root->data) 42 insert(root->l,data,pre); 43 else if(data > root->data) 44 insert(root->r,data,pre); 45 else root->ans++; 46 } 47 48 void dfs(int sum,int Max,char *s,int site,int pre) 49 { 50 if(sum > Max) 51 return ; 52 53 if(strlen(s) == 0) 54 { 55 if(sum <= Max) 56 { 57 insert(root,sum,pre); 58 } 59 return ; 60 } 61 62 int i,dec,j,temp,len; 63 64 for(i = 0,len = strlen(s);i < len; ++i) 65 { 66 for(j = i,temp = 0,dec = 1;j >= 0; --j,dec *= 10) 67 temp += (s[j]-'0')*dec; 68 69 path[top].pre = pre; 70 path[top].site = site; 71 top++; 72 73 dfs(sum+temp,Max,s+i+1,site+i+1,top-1); 74 } 75 } 76 77 void PrintPath(int pre) 78 { 79 int s[100],top = 0; 80 while(pre != -1) 81 { 82 s[top++] = path[pre].site; 83 pre = path[pre].pre; 84 } 85 86 for(int i = top-1;i >= 0; --i) 87 { 88 printf(" "); 89 if(i != 0) 90 { 91 for(int j = s[i];j < s[i-1]; ++j) 92 printf("%c",SNum[j+1]); 93 } 94 else 95 { 96 for(int j = s[i]+1; SNum[j] != '