FJ and his cows enjoy playing a mental game. They write down the numbers from 1 to N (1 <= N <= 10) in a certain order and then sum adjacent numbers to produce a new list with one fewer number. They repeat this until only a single number is left. For example, one instance of the game (when N=4) might go like this:
Write a program to help FJ play the game and keep up with the cows.
3 1 2 4
4 3 6
7 9
16
Behind FJ's back, the cows have started playing a more difficult game, in which they try to determine the starting sequence from only the final total and the number N. Unfortunately, the game is a bit above FJ's mental arithmetic capabilities. Write a program to help FJ play the game and keep up with the cows.
Line 1: Two space-separated integers: N and the final sum.
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 16
3 1 2 4
Explanation of the sample:
There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.
There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
int times;
int check(int a[],int res,int n){//检测函数
// printf("No.%d\n",++times);
int i;
int aa[15];
for(i = 1; i <= n; i++)aa[i] = a[i];//注意!!这里必须用一个数组代替a否则会改变a,导致没办法继续求全排列
while(n>1){
int cnt = 0;
int t[15];
for(i = 2; i <= n; i++){
t[++cnt] = aa[i-1]+aa[i];//相邻数相加赋值给新的临时数组
}
for(i = 1; i <= cnt; i++){//更新a数组
aa[i] = t[i];
}
// for(i = 1; i <= n; i++){
// if(i==1)printf("%d",a[i]);
// else printf(" %d",a[i]);
// }
// puts("");
// puts("");
n = cnt;//更新n的值
}
if(aa[1]==res)return 1;
else return 0;
}
int main(){
int n;
int res;
scanf("%d%d",&n,&res);
int a[15];
int i;
for(i = 1; i <= n; i++){
a[i] = i;//从最小序列赋值
}
do{//对于每一个排列顺序,检验结果是否是所给的res
//printf("???????????\n");
int k = check(a,res,n);
if(k){//如果检测成功,输出结束循环
for(i = 1; i <= n; i++){
if(i==1)printf("%d",a[i]);
else printf(" %d",a[i]);
}
puts("");
break;
}
}while(next_permutation(a+1,a+1+n));
return 0;
}