poj 1416 dfs 回溯

#include<iostream>
#include<cmath>
using namespace std;
long int path,p,temp,aim;   // path记录对应的一种划分,temp记录最大值个数   个人觉得temp的处理比较创新
long int sum,result;
int  he(char s[],int i)   //前i位的和
{
	int sum1=0,j;
	for(j=0;j<i;j++)
		sum1+=(s[j]-'0')*pow(10.0,i-1-j);           //妈蛋
	return sum1;
}
void DFS(char s[],int len)
{
	int i,j,a;
	char b[10];
	if(len==0)
	{
		if(sum>result)
		{
			result=sum;
			temp=1;
			p=path;
		}
		else
		{
		    if(sum==result)         //常犯的错误用两个if  第一个if后值已经改变了
			    temp++;
		}
		return;                    //忘记了
	}
	for(i=1;i<=len;i++)
	{
		a=he(s,i);                 // 必须新建一个数组,只有在栈中才会保存
		sum+=a;
		if(sum>aim)
		{
			sum-=a;            //忘记了
			continue; 
		}                    //剪枝
		path=path*10+i;
		for(j=0;j<len-i;j++)
			b[j]=s[i+j];
		DFS(b,len-i);
		sum-=a; 
		path=path/10;              //回溯,因为sum是全局变量,不会保存在栈中
	}
}
int main()
{
	int len,i,j,a[10],sum0,count,sum1,temp1;
	char s[50];
	while(cin>>aim>>s&&aim&&strcmp(s,"0"))
	{
		sum=0; temp=0;result=0;p=0;path=0;count=0;sum0=0;
		len=strlen(s);
		for(i=0;i<len;i++)
		{
			sum0+=s[i]-'0';
		}
		if(sum0>aim)
			cout<<"error"<<endl;
		else
		{
			DFS(s,len);
			temp1=p;
			if(temp==1)
			{
				cout<<result<<" ";
				while(p/10>0)
				{
					count++;
					p/=10;
				}
				for(i=count;i>=0;i--)
				{
					a[i]=temp1%10;
					temp1/=10;
				}
				for(i=0;i<count+1;i++)
				{
					sum1=0;
					for(j=0;j<i;j++)
						sum1+=a[j];
					for(j=sum1;j<sum1+a[i];j++)
						cout<<s[j];
					cout<<" ";
				}
				cout<<endl;
			}
			else
			{
				cout<<"rejected"<<endl;
			}
		}
	
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值