Backward Digit Sums
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7854 Accepted: 4518
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 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
Thinking: 思路还是很简单吧,乘胜追击,就是计算杨辉三角,我是用了副本数组,用来计算结果,就是计算循环的时候注意到底要计算哪几项就好,还是暴力
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
int N, sum;
int line[11]; //原数组
int lineCopy[11]; //副本数组
void solve() {
fill(line, line + N, 0);
int maxNum = sum / N, index = 0; //n个数字,和为sum, 显然最大值不能超过sum/n
for (int i = 1; i <= N; i++) {
if (i <= maxNum) {
lineCopy[index] = line[index] = i;
index++;
}
}
do {
int k = 0;
int indexCopy = index;
//将排列后的数组付给副本数组
while (line[k] != 0) {
lineCopy[k] = line[k];
k++;
}
//计算副本数组的杨辉三角
for (int i = 0; i < index-1; i++) {
for (int j = 0; j < indexCopy-1; j++) {
lineCopy[j] = lineCopy[j] + lineCopy[j + 1];
}
indexCopy--;
if (indexCopy == 1)
break;
}
//符合结果输出
if (lineCopy[0] == sum) {
for (int i = 0; i < index; i++) {
printf("%d ", line[i]);
}
break;
}
} while (next_permutation(line, line + index));
}
int main() {
while (scanf("%d%d", &N, &sum) == 2) {
solve();
}
return 0;
}
本文介绍了一款名为BackwardDigitSums的数学游戏,玩家需从最终总和逆推原始数字序列。通过实现一个程序帮助理解游戏规则并找到满足条件的起始序列。使用了杨辉三角的计算原理,通过不断尝试排列组合来找出正确的数字顺序。
465

被折叠的 条评论
为什么被折叠?



