USACO2006 Backward Digit Sums /// 全排列 oj24212

题目大意:

给出杨辉三角的顶点值M和底边数的个数 N (1 ≤ N ≤ 10) ,求出底边各个数的值,其中各个数范围都为1 ~ N 

当N=4,M=16时可能是这样的

  3   1   2   4
     4   3   6 
       7   9   
         16 

Input

Multiple test cases. For each case:

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

Output

For each case, output one line : 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.

Sample Input

4 16

Sample Output

3 1 2 4

Hint

Explanation of the sample:

There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.

3 1 2 4不是唯一解, 但是按字典序的最小解

 

N较小 直接暴力 用next_permutation()全排列函数 得出下一种排列 验证正确则跳出结束

#include <bits/stdc++.h>
using namespace std;
int a[15],b[15],n,m;
bool judge()
{
    for(int k=n;k>1;k--)
    {
        for(int i=1;i<k;i++)
            b[i]=b[i]+b[i+1];
    }
    if(b[1]==m) return 1;
    else return 0;
}
void per()
{
    do
    {
        for(int i=1;i<=n;i++)
            b[i]=a[i];
        if(judge()) return;
    }while(next_permutation(a+1,a+1+n));
}
int main()
{
        while(~scanf("%d%d",&n,&m))
        {
            for(int i=1;i<=n;i++)
                a[i]=i;
            per();
            for(int i=1;i<n;i++)
                printf("%d ",a[i]);
            printf("%d\n",a[n]);
        }

}
View Code

 

posted @ 2018-02-02 10:47  _Jessie  阅读(111)  评论(0编辑  收藏  举报