You are given an integer sequence of length n, a1,…,an. Let us consider performing the following n operations on an empty sequence b.
The i-th operation is as follows:
- Append ai to the end of b.
- Reverse the order of the elements in b.
Find the sequence b obtained after these n operations.
- 1≤n≤2×105
- 0≤ai≤109
- n and ai are integers.
Input is given from Standard Input in the following format:
n a1 a2 … an
Print n integers in a line with spaces in between. The i-th integer should be bi.
4 1 2 3 4
4 2 1 3
- After step 1 of the first operation, b becomes: 1.
- After step 2 of the first operation, b becomes: 1.
- After step 1 of the second operation, b becomes: 1,2.
- After step 2 of the second operation, b becomes: 2,1.
- After step 1 of the third operation, b becomes: 2,1,3.
- After step 2 of the third operation, b becomes: 3,1,2.
- After step 1 of the fourth operation, b becomes: 3,1,2,4.
- After step 2 of the fourth operation, b becomes: 4,2,1,3.
Thus, the answer is 4 2 1 3
.
3 1 2 3
3 1 2
As shown above in Sample Output 1, b becomes 3,1,2 after step 2 of the third operation. Thus, the answer is 3 1 2
.
1 1000000000
1000000000
这题开始的时候,发先规律每加入一个数,就把这个数的排列,首位依次交换位置,依次循环,每加入一个数就循环一次得到代码:
#include<iostream>
using namespace std;
int a[200050], b[200050];
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int j = 1; j <= n; j++)
{
b[j] = a[j];
if (j > 1)
{
int temp;
int m = (j + 1) / 2;
for (int i = 1; i <= m; i++)
{
temp = b[i];
b[i] = b[j - i + 1];
b[j - i + 1] = temp;
}
}
}
for (int i = 1; i < n; i++)
cout << b[i] << " ";
cout << b[n] << endl;
return 0;
}
当然结果肯定是超时了,因为你每加一个数都要循环一遍,当n非常大的时候,肯定就崩了。所以开始做题的时候不知道不能太天真,按着它说的一步步去做,去循环,那样很大可能做不出来。
后来仔细看下,发现1的位置对于连续的奇数和偶数(从一开始排序的那种),是相同的,但是1两边的值是不样的,但要么这一边都是偶数,另一边都是奇数,反正1是分界线,左右分别是奇数和偶数的集合。自己写几个的看一下,规律就出来了,这题算比较水的了,但是开始做,错了好几次。希望慢慢多做点,变得机智点。
#include<iostream>
#include<stdio.h>
using namespace std;
int a[200050], b[200050];
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
b[n / 2 + 1] = a[1];
if (n % 2)
{
for (int i = 1; i <= n / 2; i++)
{
b[n / 2 + 1 + i] = a[2 * i];
b[n / 2 + 1 - i] = a[2 * i + 1];
}
}
else
{
for (int i = 1; i <= n / 2; i++)
{
b[n / 2 + 1 - i] = a[2 * i];
}
for (int i = 1; i < (n / 2); i++)
{
b[n / 2 + 1 + i] = a[2 * i + 1];
}
}
for (int i = 1; i < n; i++)
printf("%d ", b[i]);
printf("%d\n", b[n]);
return 0;
}