【题解】POJ 3187 Backward Digit Sums(搜索)

POJ 3187 Backward Digit Sums


原题

https://vjudge.net/problem/POJ-3187

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

题意

有一个序列由1 ~ n组成,然后相邻的两个数相加得到下一行,重复这个过程最后得到一个整数sum。现在告诉你n和m,求最初的序列。
输入:两个整数n,sum。输出:初始序列,整数间由空格分开。
思路:可以参考POJ2718,十分相似的两道题,可以从1~n的序列开始排,把所有的组合以及最终和都用map存下来,这里因为没有多个案例所以我就直接求了。具体看代码。

#include
#include

using namespace std;

void solve(int n, int sum) {
	int arr[10], pro[10];//arr用来存0~n,pro用来求sum
	for(int i = 0; i < n; i++)
		arr[i] = i + 1;
	do {
		for(int i = 0; i < n; i++)
			pro[i] = arr[i];
//		for(int i = 0; i < n; i++)
//			cout << pro[i] << " ";cout << endl;
		for(int i = n - 1; i > 0; i--)	//把两个相邻的数相加并且赋给前一个数,最终的pro[0]就是sum
			for(int j = 0; j < i; j++)	//如果不清楚可以在草稿纸上演算一下
				pro[j] = pro[j] + pro[j + 1];
//		for(int i = 0; i < n; i++)
//			cout << pro[i] << " ";cout << endl;
		if(sum == pro[0]) {
			for(int i = 0; i < n; i++) {
				if(i)cout << " ";//结尾没有空格
				cout << arr[i];
			}
			return;
		}
	}while(next_permutation(arr, arr + n));
		
}
int main() {
	int n, sum;
	cin >> n >> sum;
	solve(n, sum);
	return 0;
}

你可能感兴趣的:(挑战程序设计日常)