Backward Digit Sums -全排列找解

【题目】

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:
 

    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

输出:

扫描二维码关注公众号,回复: 2494383 查看本文章

3 1 2 4

题目大意:给出n,m两个数,从1到n的自然数的某种排序为第一行,经过杨辉三角类似的计算后得出m,求那种排序。。。。

思路:全排列函数,暴力就完事了。。。

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include <algorithm>
using namespace std;
int main()
{
    int n,m;
    while(cin>>n>>m&&n&&m)
    {
        int a[101],f[101];
        for(int i=1;i<=n;i++)
            a[i]=i;
        do
        {
            for(int i=1;i<=n;i++)
                f[i]=a[i];
            for(int i=1;i<=n-1;i++)
                for(int j=1;j<=n-i;j++)
                {
                    f[j]=f[j]+f[j+1];
                }
            if(f[1]==m)
            {
                for(int i=1;i<=n;i++)
                    cout<<a[i]<<" ";
                break;
            }
        }
        while(next_permutation(a+1,a+n+1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wentong_xu/article/details/81220049