这道题,用string过不了,需用char数组。但是我不知道为什么。
题意:把一串数字拆分成几部分,使得和不超过给定值。求和最大的情况。
用DFS搜索。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <stack>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#define FOR(i,s,t) for(int i = (s) ; i <= (t) ; ++i )
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e6+5;
char str[100];
bool update;
int path[100];
int ans_path[100];
int tag,target,ans,num,len;
void dfs(int pos,int sum,int step)
{
if( sum > target )
{
return;
}
if(pos==len)
{
if(sum == ans)
{
tag=2;
}
else if( sum > ans )
{
ans=sum;
num=step;
tag=1;
for(int i=0; i<step; ++i)
{
ans_path[i]=path[i];
}
}
return;
}
int tmp=0;
for(int i=pos; i<len; ++i)
{
tmp=tmp*10+str[i]-'0';
path[ step ]=tmp;
dfs(i+1,sum+tmp,step+1);
}
}
int main()
{
//freopen("in.txt","r",stdin);
while( ~scanf("%d%s",&target,str) )
{
if( target==0 && str[0]=='0' )break;
tag=0;
num=0;
ans=-1;
len=strlen(str);
dfs(0,0,0);
if(tag==0)
{
printf("error\n");
}
else if(tag==2)
{
printf("rejected\n");
}
else
{
printf("%d",ans);
for(int i=0; i<num; ++i)
{
printf(" %d",ans_path[i]);
}
printf("\n");
}
}
return 0;
}