【POJ - 3187】Backward Digit Sums(搜索)

-->Backward Digit Sums

直接写中文了

Descriptions:

FJ 和 他的奶牛们在玩一个心理游戏。他们以某种方式写下1至N的数字(1<=N<=10)。 然后把相邻的数相加的到新的一行数。重复这一操作直至只剩一个数字。比如下面是N=4时的一种例子 

    3   1   2   4

4 3 6
7 9
16
在FJ回来之前,奶牛们开始了一个更难的游戏:他们尝试根据最后结果找到开始的序列。这已超过了FJ的思考极限。 

写一个程序来帮助FJ吧

Input

N和最后的和

Output

满足要求的一行序列。若有多种情况,输出字典序最小的一种

Sample Input

4 16

Sample Output

3 1 2 4

Hint

样例解释 
这里还有其他可能的排列,若 3 2 1 4,但 3 1 2 4 是字典序最小的
 
题目链接:
 
直接对这n个数进行全排列,然后对其求和,比对答案即可
既然是全排列 这里有一个全排列函数,可以直接调用,而且排列顺序就是字典顺序,很方便  next_permutation 参考:https://www.cnblogs.com/sky-stars/p/10948384.html 讲的很细
 
AC代码:
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define MEM(x,y) memset(x,y,sizeof(x))
#define Maxn 1005
using namespace std;
int a[Maxn];
int n;
int ans,result;
void solve()
{
    do
    {
        int b[Maxn];//注意一定要设置一个新数组,不然a数组会混乱
        for(int i=0;i<n;i++)
            b[i]=a[i];
        for(int i=n; i>=2; i--)//求出这组数组的和
        {
            for(int j=0; j<i; j++)
            {
                b[j]=b[j]+b[j+1];
            }
        }
        result=b[0];//b[0]即是这组数字之和
        if(result==ans)//得到正确答案,输出数组即可
        {
            for(int i=0; i<n; i++)
            {
                cout<<a[i]<<" ";
            }
            cout<<endl;
            break;
        }
    }
    while(next_permutation(a,a+n));//全排列
}
int main()
{
    cin>>n>>ans;
    for(int i=0; i<n; i++)//输入数组
        a[i]=i+1;
    solve();
}

 

posted on 2019-07-15 22:18  Sky丨Star  阅读(426)  评论(0编辑  收藏  举报

导航