[BZOJ1653]&&[Usaco2006 Feb]Backward Digit Sums

描述 Description

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.

输入格式 InputFormat

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

输出格式 OutputFormat

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.

样例输入 SampleInput

10 2196

样例输出 SampleOutput

1 6 9 4 2 3 5 10 7 8

来源 Source

Silver


BZOJ 1653


代码 Code

枚举全排列判断。

STL 中的 next_permutation 函数可以用来产生下一个字典序的全排列。返回值为 bool 表示是否成功生成全排列。C++ Reference 中原文如下:

#include <algorithm>
bool next_permutation( iterator start, iterator end );

The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.

类似的函数还有 pre_permutation,产生上一个字典序的全排列。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int inf=0x7fffffff;
int a[11],f[11];
int i,j,t,n,m,l,r,k,z,y,x;
int main()
{
    scanf("%d%d",&n,&m);
    for (i=1;i<=n;i++) a[i]=i;
    do
    {
        for (i=1;i<=n;i++) f[i]=a[i];
        for (i=1;i<n;i++) for (j=1;j<=n-i;j++) f[j]+=f[j+1];
        if (f[1]==m)
        {
            for (i=1;i<n;i++) printf("%d",a[i]);
            printf("%d\n",a[n]);
            return 0;
        }
    }while (next_permutation(a+1,a+n+1));
    return 0;
}