POJ 1416 Shredding Company (dfs)
题意:给定一个目标数n1,一个操作数n2,需要对操作数进行切割,并且各个和要小于目标数,而且最大。
由于操作数n2不大,dfs就可以实现,就是小细节很多,需要注意,对0的判断要加上。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <memory.h>
#include <cmath>
#include <vector>
using namespace std;
const int BORDER = (1<<26)-1;
#define MAXN 1000000
#define INF 0x7ffffff
#define _clr(x,y) memset(x,y,sizeof(x))
#define _add(x) ((++x)&BORDER)
#define _in(x) scanf("%d",&x)
#define _out(x) printf("%d\n",x)
#define _min(m,v) (m)<(v)?(m):(v)
#define _max(m,v) (m)>(v)?(m):(v)
int n,target,arr[10],sum,mmax,tar_len,t_sum,n_index;
int pre[10],t_pre[10],cnt[MAXN],arr_sum[12];
int init()
{
_clr(pre,0);
_clr(cnt,0);
_clr(arr,0);
_clr(t_pre,0);
mmax = -1;
arr[0] = 0;
target = 0;
return 0;
}
int dfs(const int& ilen,const int& cur_pos,const int& index)
{
int i,j,len,tmp;
t_pre[index] = ilen;
t_sum = 0;
for(i = ilen-1; i >=0; --i)
t_sum = t_sum*10 + arr[cur_pos-i];
if(!index)
arr_sum[index] = t_sum;
else
arr_sum[index] = arr_sum[index-1] + t_sum;
tmp = arr_sum[index];
if( tmp > target)
return 0;
if(cur_pos == n)
{
if( tmp == mmax )
cnt[tmp] = 1;
else if(tmp > mmax)
{
mmax = tmp;
n_index = index;
memcpy(pre,t_pre,sizeof(pre));
}
}
len = n-cur_pos;
for(i = 1; i <= len; ++i)
dfs(i,cur_pos+i,index+1);
return 1;
}
int main()
{
char str1[10],str2[10];
int i,j,tmp;
while(scanf("%s %s",str1,str2))
{
init();
if(str1[0] == '0' && str2[0] == '0')
break;
tar_len = strlen(str1);
for(i = 1; i <= tar_len; ++i)
target = target*10 + str1[i-1]-'0';
n = strlen(str2);
for(i = 1; i <= n; ++i)
arr[i] = str2[i-1] - '0';
dfs(0,0,0);
if(mmax == -1)
printf("error\n");
else if(cnt[mmax])
printf("rejected\n");
else
{
printf("%d",mmax);
int cur = 1;
for(i = 1;i<=n_index; ++i)
{
tmp = pre[i];
printf(" ");
for(j = 0; j < tmp; ++j)
{
printf("%c",arr[cur]+'0');
++cur;
}
}
printf("\n");
}
}
return 0;
}