题解 CF221A
题目意思:
有一个从 $1$ 到 $n$ 的升序序列,你要对他进行以下处理
请注意加粗的字,先进行交换,如果你没注意到,那就WA了
题目难度:
大致在 入门
难度左右
做法分析:
我们先进行一遍简单的模拟,代码如下:
#include <cmath>
#include <iostream>
#define re register
using namespace std;
int a[1002], n;
inline int f(int x){
if(x!=1){
swap(a[x-1],a[x]);
f(x-1);
}
}
int main(){
cin>>n;
for(re int i=1; i<=n; i++) a[i]=i;
f(n);
for(re int i=1; i<=n; i++) cout<<a[i]<<" ";
}
很多人到这里就不继续研究了,但是如果你用这个程序找找规律,你会发现:
- 输入:
5
输出: 5 1 2 3 4
- 输入:
6
输出: 6 1 2 3 4 5
- 输入:
7
输出: 7 1 2 3 4 5 6
- 输入:
8
输出: 8 1 2 3 4 5 6 7
- 输入:
9
输出: 9 1 2 3 4 5 6 7 8
你就可以发现,这就不需要递归了,先输出 $n$ 再输出 $1$ 到 $n-1$
代码如下:
#include <iostream>
#define re register
#define andy putchar(' ');
using namespace std;
int n;
int main(){
ios::sync_with_stdio(false); //cin优化
scanf("%d",&n);
printf("%d",n); //输出n
andy
for(re int i=1; i<n; i++){ //输出从1道n
printf("%d",i);
andy //别忘了空格
}
}
希望本题解对大家有帮助,也感谢管理员百忙之中帮我审核题解,谢谢!
End.