首页 > 其他 > 详细

poj 3187 Backward Digit Sums(穷竭搜索dfs)

时间:2015-08-28 02:05:24      阅读:240      评论:0      收藏:0      [点我收藏+]

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 FJs 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 FJs 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.

Source

 
注意杨辉三角的求法,要用二维来求,其它的就没什么了。。。
 
技术分享
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 #define N 16
 6 int n,sum;
 7 int vis[N];
 8 int a[N][N];
 9 int flag;
10 bool check(){
11     for(int i=1;i<n;i++){
12         for(int j=0;j<n-i;j++){
13             a[i][j]=a[i-1][j]+a[i-1][j+1];
14         }
15     }
16     return a[n-1][0]==sum;
17 }
18 void dfs(int num){
19     
20     if(num==n){
21         if(check())
22           flag=1;
23         return;
24     }
25     for(int i=1;i<=n;i++){
26         if(!vis[i]){
27             vis[i]=1;
28             a[0][num]=i;
29             dfs(num+1);
30             if(flag==1)
31               return;
32             vis[i]=0;
33         }
34     }
35 }
36 int main()
37 {
38     while(scanf("%d%d",&n,&sum)==2){
39         
40         if(n==1)
41         {
42             printf("%d\n",sum);
43             continue;
44         }
45         
46         memset(vis,0,sizeof(vis));
47         flag=0;
48         dfs(0);
49         for(int i=0;i<n;i++){
50             printf("%d",a[0][i]);
51             if(i!=n-1)
52               printf(" ");
53         }
54         printf("\n");
55     }
56     return 0;
57 }
View Code

 

poj 3187 Backward Digit Sums(穷竭搜索dfs)

原文:http://www.cnblogs.com/UniqueColor/p/4765238.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!