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 4Behind 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.
4 3 6
7 9
16
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
给定一个n,枚举1-n的全排列,然后用杨辉三角的公式求三角顶端的和,如果有满足的就返回。
杨辉三角第a行,第b列的值是value = c(a-1,b-1) = (a - 1)! / ((b - 1)! * (a - b)!),然后这个题是倒三角,需要知道最后一样的数汇聚到顶端的和被加了多少次,
也就是第n行,第i个元素,被加了c(n - 1,i - 1)次。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #define MAX 0 #define inf 0x3f3f3f3f using namespace std; int n,d,flag; int s[10],vis[10],mul[10]; void dfs(int k) { if(flag)return; if(k >= n) { int sum = 0; for(int i = 0;i < n;i ++) { sum += mul[i] * s[i]; } if(sum == d)flag = 1; return; } for(int i = 1;i <= n;i ++) { if(flag)return; if(!vis[i]) { vis[i] = 1; s[k] = i; dfs(k + 1); vis[i] = 0; } } } int C(int a,int b) { int aa = 1,bb = 1; for(int i = 0;i < b;i ++) aa *= a - i,bb *= i + 1; return aa / bb; } int main() { while(~scanf("%d%d",&n,&d)) { for(int i = 1;i <= n;i ++) { mul[i - 1] = C(n - 1,i - 1);///计算第i个元素被加多少次 也就是总和里包括几个第i个元素 后面直接用 } flag = 0; dfs(0);///枚举 for(int i = 0;i < n;i ++) { if(i)putchar(' '); printf("%d",s[i]); } putchar(' '); } return 0; }