Backward Digit Sums(全排列+dfs())

poj3187-Backward Digit Sums

    FJ 和 他的奶牛们在玩一个心理游戏。他们以某种方式写下1至N的数字(1<=N<=10)。 然后把相邻的数相加的到新的一行数。重复这一操作直至只剩一个数字。比如下面是N=4时的一种例子
3   1   2   4
  4    3   6
     7    9
       16
    在FJ回来之前,奶牛们开始了一个更难的游戏:他们尝试根据最后结果找到开始的序列。这已超过了FJ的思考极限。 写一个程序来帮助FJ吧

Input

Line 1: Two space-separated integers: N and the final sum.

output

Line 1: An ordering of the integers 1…N that leads to the given sum. If there are multiple solutions, choose the one that is lexicographically least, i.e., that puts smaller numbers first.

样例输入

4 6

样例输出

3 1 2 4
答案有多个,输出字典序最小

#include<iostream>
#include<algorithm>
using namespace std;
int n,a[15],c[15],m;
void DFS(int k,int b[]){
	if(k==0){
		if(b[1]==m){
			for(int i=1;i<=n;i++)
				cout<<a[i]<<" ";
			cout<<endl;
			exit(0);
		}
		return;
	}
	for(int i=1;i<k;i++)
		b[i]=b[i]+b[i+1];
	DFS(k-1,b);
}
int main(){

	cin>>n>>m;
	for(int i=1;i<=n;i++)
		a[i]=i;
	do{
		for(int i=1;i<=n;i++)
			c[i]=a[i];
		DFS(n,c);
	}while (next_permutation(a+1,a+1+n));
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值