Backward Digit Sums - POJ 3187 DFS

来源:互联网 发布:红苹果视频矩阵 编辑:程序博客网 时间:2024/06/05 00:09
Backward Digit Sums
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 4860 Accepted: 2808

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

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.


题意:某1~N的序列,相邻两个相加得到新的序列,一直加到最后只剩一个数,给出N和这种方法得到的最后一个数,求出字典序最小的原序列。

思路:水题,简单思考后每一项的系数为二项式系数,数据范围很小直接DFS即可


#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<cmath>#include<algorithm>#include<queue>#include<set>#define MAXN 20#define LL long longusing namespace std;int a[MAXN],len=0;bool used[20];int n,sum;int yh[20][20];bool dfs(int pos,int now){for(int i=1;i<=n;i++){if(used[i]) continue;if(pos==n){if(now+i*yh[n][pos]==sum){used[i]=1;a[len++]=i;return 1;}elsecontinue;}if(now+i*yh[n][pos]>=sum)continue;else{a[len++]=i;used[i]=1;if(dfs(pos+1,now+i*yh[n][pos]))return 1;else{len--;used[i]=0;}}}return 0;}int main(){//freopen("in.txt","r",stdin);yh[1][1]=1;for(int i=2;i<=11;i++){for(int j=1;j<=i;j++){yh[i][j]=yh[i-1][j]+yh[i-1][j-1];}}while(~scanf("%d%d",&n,&sum)){len=0;memset(used,0,sizeof(used));dfs(1,0);int temp;for(int i=0;i<len;i++){printf("%d",a[i]);if(i==len-1)printf("\n");else printf(" ");}}return 0;}


0 0
原创粉丝点击