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;
}