Topic Link: Portal
Test instructions: To a target value goal, and then to a number num, the NUM decomposition, such as to the target value 50,num to 12346 num can be decomposed to 1 2 34 6 So 4 parts, requires part and as close as possible to the target value, but not greater than the target value, to find the optimal decomposition;
Ideas: Deep Search Each section of the starting point, update the optimal solution when updating the path, before is the path to the puzzle, in fact, and update the idea of the best value, you can set a ans_path[] array, update the optimal value when the way to update the best path on the line.
#include <algorithm> #include <iostream> #include <cstring> #include <cstdlib> #include < string> #include <cctype> #include <vector> #include <cstdio> #include <cmath> #include < queue> #include <time.h> #include <stack> #include <map> #include <set> #define MAXN 360# Define _LL __int64#define ll long long#define INF 0x3f3f3f3f#define Mod 1000000007#define pp pair<int,int> #define UL L unsigned long Long#define max (x, Y) ((() > (y))? (x): (y)) #define min (x, y) ((() > (y))? (y): (x)) using namespace Std;char s[100];int ok,ans,path[20],ans_path[20],len,goal,rej,ans_tot;int my_pow (int a,int N) {int p=1;for (int i=1;i<=n;i++) P*=a;return p;} void Dfs (int num,int sum,int tot) {if (sum>goal) return; if (Num>=len) {if (sum>ans&&sum<=goal) { memcpy (ans_path,path,sizeof (int) *tot); Ok=1;rej=1;ans=sum;ans_tot=tot;return;} else if (sum==ans&&sum<=goal) {Rej++;return;} return;} for (int i=1;num+i<=len;i++) {int j=num+i,tem=0,sb=0;while (j>num) tem+= (s[j--]-' 0 ') * (int) My_pow (10,sb++);p Ath[tot]=num+i;dfs ( num+i,sum+tem,tot+1);p ath[tot]=-1;}} void print () {if (rej>1) {puts ("rejected"); return;} if (OK) {printf ("%d", ans), for (int i=0;i<ans_tot;i++) {printf (""); for (int j= (i!=0?ans_path[i-1]+1:1); j<=ans_ path[i];j++) printf ("%c", S[j]);} Puts ("");} Elseputs ("Error");} int main () {while (scanf ("%d%s", &goal,s+1) && (goal!=0&&s[1]!= ' 0 ')) {memset (path,-1,sizeof (path) ); S[0]=2;len=strlen (s) -1;ans=-inf;ok=0;rej=0;dfs (0,0,0);p rint ();} return 0;}
POJ 1416-shredding Company (dfs+ update path)