作业帮 > 英语 > 作业

A.Little Elephant and Function

来源:学生作业帮 编辑:作业帮 分类:英语作业 时间:2024/07/16 22:52:21
A.Little Elephant and Function
Time Limit :4000/2000ms (Java/Other) Memory Limit :524288/262144K (Java/Other)
Total Submission(s) :35 Accepted Submission(s) :31
Problem Description
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function.Let a is a permutation of an integers from 1 to n,inclusive,and ai denotes the i-th element of the permutation.The Little Elephant's recursive function f(x),that sorts the first x permutation's elements,works as follows:
· If x=1,exit the function.
· Otherwise,call f(x-1),and then make swap(ax-1,ax) (swap the x-th and (x-1)-th elements of a).
The Little Elephant's teacher believes that this function does not work correctly.But that-be do not get an F,the Little Elephant wants to show the performance of its function.Help him,find a permutation of numbers from 1 to n,such that after performing the Little Elephant's function (that is call f(n)),the permutation will be sorted in ascending order.
Input
A single line contains integer n (1≤n≤1000) the size of permutation.
Output
In a single line print n distinct integers from 1 to n the required permutation.Numbers in a line should be separated by spaces.
It is guaranteed that the answer exists.
Sample Input
1
2
Sample Output
1 2 1
Source
Codeforces
当x=1时返回,不然调用f(x-1),并且交换第x和x-1个元素
if(x==1) return
f(x-1);
swap(a[x-1],a[x]);
大概就这样了,然后最后输出整条数列
不过为嘛输出是1排就不知道了,难道不同输出之间不用空行······
/////////那这些排的数字是哪来的呢?不是1--n吧?它不是说最后要升序吗?交换能实现升序吗?
题意就是这样,你理解也对.
f(n)如果n=1就返回.否则调用f(n-1),再交换a[n-1]和a[n].
注意上述调用方式是先递归,再交换.那么f(n)其实就等价于先交换a[1]和a[2](即f(2)中的交换),再交换a[2]和a[3](即f(3)中的交换),...,最后交换a[n-1]和a[n](即f(n)中的交换).所以整个交换就等价于把序列中的第一个数一路移动到最后.因为最后的序列式一个升序的序列,所以开始的序列就是n,1,2,3,...,n-1就对了.
比如输入3,那么初始序列是3,1,2.
最后让你输出一排的要求是不需要纠结的.让怎么输出怎么输出就可以了.就是两个数字之间1个空格.所以输入1 2输出1 2 1.
再问: 那它的意思就是让我去找这一串数字的排列出来,不是让我去写这个递归函数罗?
再答: 对啊。其实非常简单,输入的任何一个数n,你只需要输出n,1,2,3,...,n-1就可以了。比如输入5,就输出5 1 2 3 4就对了。至于为什么,你应该懂了。
再问: 你能不能帮我看一下这道题http://zhidao.baidu.com/question/487780225.html?sort=6#reply-box-1224330616也是同个比赛的一道题目,而且是第一题,当时第一道就卡住了,导致后面时间不够……
再答: 我要先去洗个澡,回来再看吧。
再问: 行,我加你哈……
再答: ok