【题目描述】
FJ
and his cows enjoy playing a mental game. They write down the numbers from 1 toN(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.
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.
【翻译】
写出一个1至N的排列Ai,然后每次将相邻两个数相加,构成新的序列,再对新序列进行这样的操作,显然每次构成的序列都比上一次的序列长度少1,直到只剩下一个数字位置。现在想要倒着玩这样一个游戏,如果知道N,知道最后得到的数字的大小sumsum,请你求出最初序列Ai,为1至N的一个排列。若答案有多种可能,则输出字典序最小的那一个。
【数据范围】
n<=12
sum<=12345
【分析】
将样例给出的4个数用a,b,c,d表示,然后写出sum的表达式,易得a,b,c,d的系数就是杨辉三角形第4行的数。配出系数,暴力枚举a,b,c,d即可。注意剪枝!
#include
#include
#include
#include
using namespace std;
const int N=15;
int c[N][N],a[N],b[N]={0};
int n,m,flag=0;
void dfs(int step,int sum){
if (flag || sum>m) return;
//sum>m就return这个优化在洛谷上非常厉害,第2个点本来800ms+,加了这句话瞬间50ms-
//但是可以构造较大的sum,使这个优化无效
//这说明洛谷的数据太弱了
//但是这个代码在POJ只用0ms就过了,POJ是数据更弱还是评测机太好。。。
if (step>n){
if (sum==m){
flag=1;
for (int i=1;i<=n;i++) printf("%d ",a[i]);
}
return;
}
for (int i=1;i<=n;i++){
if (b[i]) continue;
b[i]=1;
a[step]=i;
dfs(step+1,sum+c[n][step]*i);
b[i]=0;
}
}
int main(){
scanf("%d%d",&n,&m);
c[1][1]=1;
for (int i=2;i<=n;i++){
c[i][1]=c[i][i]=1;
for (int j=2;j