1653: [Usaco2006 Feb]Backward Digit Sums
1653: [Usaco2006 Feb]Backward Digit Sums
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 285 Solved: 215
[Submit][Status]
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
OUTPUT DETAILS:
There are other possible sequences, such as 3 2 1 4, but 3 1 2 4
is the lexicographically smallest.
HINT
Source
题解:这个嘛,本来还想什么高端洋气的算法的,可是再想想果断决定——弃疗——10!不过才3628800而已嘛,(具体说算法嘛,很显然对于原数列,每个数依次的最终累计次数即是杨辉三角形第N行的对应数字,别的没了),可是再一想,有点不对——你不是每次还要判断此组解是否合法么?这样子复杂度可还要再×10哦(36288000,3kW多了,这下子可危险啊,虽然事实上只要有解的话,由于杨辉三角形的对称性,那么最多理论上一半的时间即可找到解)。。。可是结果是——228kb 60ms Accept我也是醉了。。。
1 var 2 i,j,k,l,m,n:longint; 3 a:array[0..20] of longint; 4 b:array[0..20,0..20] of longint; 5 procedure swap(var x,Y:longint); 6 var z:longint; 7 begin 8 z:=x;x:=y;y:=z; 9 end; 10 procedure sort(l,r:longint); 11 var i,j,x,y:longint; 12 begin 13 i:=l;j:=r;x:=a[(l+r) div 2]; 14 repeat 15 while a[i]<x do inc(i); 16 while a[j]>x do dec(j); 17 if i<=j then 18 begin 19 swap(a[i],a[j]); 20 inc(i);dec(j); 21 end; 22 until i>j; 23 if l<j then sort(l,j); 24 if i<r then sort(i,r); 25 end; 26 begin 27 readln(n,m); 28 for i:=0 to n do a[i]:=i; 29 fillchar(b,sizeof(b),0); 30 b[1,1]:=1; 31 for i:=2 to n do 32 for j:=1 to i do b[i,j]:=b[i-1,j-1]+b[i-1,j]; 33 while a[0]=0 do //萌萌哒生成法全排列,小学时学的现在居然还记得*_* 34 begin 35 l:=0; 36 for i:=1 to n do l:=l+a[i]*b[n,i]; 37 if l=m then 38 begin 39 for i:=1 to n-1 do 40 write(a[i],' '); 41 writeln(a[n]); 42 halt; 43 end; 44 j:=n; 45 while a[j-1]>a[j] do dec(j); 46 k:=n; 47 while a[j-1]>a[k] do dec(k); 48 swap(a[j-1],a[k]); 49 sort(j,n); 50 end; 51 end. 52