Backward Digit Sums
| Time limit:1000ms |
|
Memory Limit: 65536K |
| Total Submissions: 6350 |
|
Accepted: 3673 |
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 The number of numbers in a full arrangement contributes to sum is Yang Hui triangle n-1 columnYang Hui Triangle is starting from 0Combinatorial number formula recursiondfs+ Pruning
////main.cpp//poj3187////Created by Candy on 9/12/16.//copyright©2016 Candy. All rights reserved.//#include<iostream>#include<cstdio>using namespacestd;Const intn= the;intn,sum,c[n],vis[n],ans[n],flag=0;voidDfsintDintNow ) { if(flag)return; if(d==n&&now==sum) {flag=1; for(intI=0; i<n;i++) printf ("%d", Ans[i]);return;} if(d==n)return; for(intI=1; i<=n;i++){ if(Vis[i])Continue; if(now+i*c[d]<=sum) {Ans[d]=i; vis[i]=1; DFS (d+1, now+i*C[d]); Vis[i]=0; } }}intMainintargcConst Char*argv[]) {scanf ("%d%d",&n,&sum); N--; c[0]=1; for(intI=1; i<=n;i++) c[i]=c[i-1]* (n-i+1)/i; N++; DFS (0,0); return 0;}
Poj3187backward Digit sums[Yang Hui Triangle]