Backward Digit Sums
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6463 | Accepted: 3750 |
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:
Write a program to help FJ play the game and keep up with the cows.
3 1 2 4 4 3 6 7 9 16Behind 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.
There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.
大意说的是给你1-N个连续的整数,按不一样的顺序,依照图上三角形的运算方法最终可以求得一个 final 的值
现在给你 N 个数和 final 的结果,让你来求这N个数的排列顺序,如果有多种情况,则输出最小的一个
**思路:1-N个数字的排列组合,暴力搜索
这里有一个最简单的方法就是调用STL库函数 next_permutation求排列组合,我就没那么偷懒,用的递归和回溯
#include <iostream>
#include <algorithm>
using namespace std;
int N,final;
bool num[13];
int map[12][12];
bool isfind;
int algo()//计算我们的到的排列组合的值
{
for(int i=2;i<=N;i++)
{
for(int j=1;j<=N-i+1;j++)
{
map[i][j] = map[i-1][j] + map[i-1][j+1];
}
}
return map[N][1];//返回最后一个数字的结果
}
void dfs(int n)//选择第n个数字的结果
{
if(isfind==true)//枝剪,我门重小开始找的,所以找到一个以后就没必要继续找了
return;
if(n==N+1)
{
if(algo()==final)
{
for(int i=1;i<=N;i++)
{
cout<<map[1][i];
if(i!=N)
cout<<" ";
}
cout<<endl;
isfind = true;
}
return;
}
for(int i=1;i<=N;i++)
{
if(num[i]==false)
{
num[i]=true;
map[1][n] = i;//把数字放在我们的计算数组的第一行的相应位置
dfs(n+1);
num[i] = false;
map[1][n] = 0;
}
}
}
int main()
{
while(cin>>N>>final)
{
fill(num,num+13,false);
fill(map[0],map[0]+12*12,0);
isfind = false;
dfs(1);
}
return 0;
}