poj 3187

来源:互联网 发布:关键词怎么优化 编辑:程序博客网 时间:2024/05/16 09:00
Backward Digit Sums
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 3330 Accepted: 1908

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.

Input

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

Output

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.

Sample Input

4 16

Sample Output

3 1 2 4
这道题是被放在搜索里的,但是看了poj上的disucuss,无数的人都在说next_permutation,是个好玩意,然后就试了一下,不禁泪奔,stl果然是好玩意啊。
下面是代码;
#include<cstdio>#include<cstdlib>#include<iostream>#include<cstring>#include<iostream>#include<cmath>#include<queue>#include<algorithm>using namespace std;int n,sum;int a[100],b[100];int main(){    int i,j;    cin>>n>>sum;    for(i=0;i<n;i++)        a[i]=i+1;//构造序列    while(next_permutation(a,a+n)){//生成多种排列        memcpy(b,a,sizeof(a));        j=n;        while(j--){//从后向前相加            for(i=0;i<j;i++)                b[i]+=b[i+1];        }        if(b[0]==sum) break;//达到目的    }    for(i=0;i<n;i++)        printf("%d ",a[i]);    printf("\n");    return 0;}


原创粉丝点击