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

Description

FJ and his cows enjoy playing a mental game. They write down the numbers from  to N ( <= N <= ) 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=) might go like this:              

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 : Two space-separated integers: N and the final sum.

Output

Line : An ordering of the integers ..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

 

Sample Output

   

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

 
注意杨辉三角的求法,要用二维来求,其它的就没什么了。。。
 
 #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 16
int n,sum;
int vis[N];
int a[N][N];
int flag;
bool check(){
for(int i=;i<n;i++){
for(int j=;j<n-i;j++){
a[i][j]=a[i-][j]+a[i-][j+];
}
}
return a[n-][]==sum;
}
void dfs(int num){ if(num==n){
if(check())
flag=;
return;
}
for(int i=;i<=n;i++){
if(!vis[i]){
vis[i]=;
a[][num]=i;
dfs(num+);
if(flag==)
return;
vis[i]=;
}
}
}
int main()
{
while(scanf("%d%d",&n,&sum)==){ if(n==)
{
printf("%d\n",sum);
continue;
} memset(vis,,sizeof(vis));
flag=;
dfs();
for(int i=;i<n;i++){
printf("%d",a[][i]);
if(i!=n-)
printf(" ");
}
printf("\n");
}
return ;
}
上一篇:Xamarin.Forms入门学习路线


下一篇:如何在Google上下载高清原图