Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 4946 |
|
Accepted: 2850 |
Description
FJ and his cows enjoy playing a mental game. They write down the numbers from 1 to n (1 <= n <=) 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 was 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 has started playing a more difficult game, in which they try to determine the starting Sequenc E 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 so leads to the given sum. If There is multiple solutions, choose the one that's 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 is and possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.
Source
Usaco 2006 February Gold & Silver
Problem Solving analysis + code:
The basic idea is to enumerate the combinations of all n numbers,//to output when encountering and equal to M. One of the processes here is to enumerate from the smallest start every time,//So the chosen is the smallest dictionary order, #include <iostream> #include <algorithm> #include < Cstdio>using namespace std;//handles the numbers that are read into the inline int read () {int x = 0, f = 1;char ch = getchar (), while (Ch < ' 0 ' | | Ch & Gt ' 9 ') {if (ch = = '-') F = -1;ch = GetChar ();} while (Ch >= ' 0 ' && ch <= ' 9 ') {x = x * + ch-' 0 '; ch = GetChar ();} return x * f;} int a[15], F[15];int N, m;int Main () {n = read (), M = read ();//initialize array, set size for (int i = 1; I <= n; i++) A[i] = i;//full arrangement do{//now The value is assigned to f[];for (int i = 1; I <= n; i++) F[i] = a[i];//Then the way of the Yang Hui Triangle, 22 add for (int i = 1; i < n; i++) for (int j = 1; J <= N I J + +) F[j] + = F[j + 1];//judgment equals the given result if (f[1] = = m) {for (int i = 1; i < n; i++) cout<<a[i]<< ""; Cout<<a[n] <<endl;return 0;}} while (Next_permutation (A + 1,a + N + 1)); return 0;}
Backward Digit Sums---dfs+ full arrangement