链接:http://poj.org/problem?id=3187
Backward Digit Sums
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5215 | Accepted: 3018 |
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.
Source
大意——一个益智游戏:首先写下1到n(1<=n<=10)的一个排列,然后每相邻的两个数相加就能形成一个新的排列,此排列比原来排列的数目少了一个,重复此步骤,直至剩下一个数。例如下例:
思路——因为n很小,全排列为n!,10!=3,628,800,所以按字典序输出所有全排列,每输出一个全排列计算一次排列的三角形累加和,并且判断其是否为sum,如果是sum,输出这个排列即可,不必再找了;如果不是,则继续寻找,直至找到为止。全排列可以由next_permutation函数来实现。
复杂度分析——时间复杂度:O(n^3),空间复杂度:O(n)
3 1 2 4
4 3 6
7 9
16
现在游戏升级了,变成:给你最后那一个数sum,要你找出从1到n(1<=n<=10)的全排列中,按上面所述的那种方式累加,最后和为sum的字典序最小的一个排列。
思路——因为n很小,全排列为n!,10!=3,628,800,所以按字典序输出所有全排列,每输出一个全排列计算一次排列的三角形累加和,并且判断其是否为sum,如果是sum,输出这个排列即可,不必再找了;如果不是,则继续寻找,直至找到为止。全排列可以由next_permutation函数来实现。
复杂度分析——时间复杂度:O(n^3),空间复杂度:O(n)
附上AC代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <stack>
//#pragma comment(linker, "/STACK:102400000, 102400000")
using namespace std;
typedef long long ll;
const double pi = acos(-1.0);
const double e = exp(1.0);
const double eps = 1e-8;
const short maxn = 15;
short n, sum;
short a[maxn], b[maxn];
int main()
{
ios::sync_with_stdio(false);
while (~scanf("%hd%hd", &n, &sum))
{
for (int i=0; i<n; i++)
a[i] = i+1;
do{
for (int i=0; i<n; i++)
b[i] = a[i];
for (int i=0; i<n-1; i++)
for (int j=0; j<n-i-1; j++)
b[j] = b[j]+b[j+1]; // 累加求和
if (b[0] == sum)
{
for (int i=0; i<n-1; i++)
printf("%hd ", a[i]);
printf("%hd\n", a[n-1]);
break;
}
} while (next_permutation(a, a+n)); // STL,生成数组a的全排列数
}
return 0;
}