题目 | Grid Rotations
AtCoder Regular Contest 153
B - Grid Rotations
https://atcoder.jp/contests/arc153/tasks/arc153_b
Time Limit:
Score :
Problem Statement
We have a grid with
Let us perform
Let
, , , and be rectangular regions within the grid defined as follows: is the intersection of the top rows and leftmost columns; is the intersection of the top a_i rows and rightmost columns; is the intersection of the bottom H-a_i rows and leftmost columns; is the intersection of the bottom H-a_i rows and rightmost columns.
- Rotate
degrees each of , , , and .
Here, a -degree rotation of a rectangular region within the grid moves the character on the square at the -th from the top and -th column from the left in to the square at the -th from the bottom and -th column from the right in . See also the figures for the samples.
Print the grid after all
Constraints
, and . is a lowercase English letter.
Input
The input is given from Standard Input in the following format:
Output
Print the grid after the operations in the following format, where
Sample Input 1
4 5
abcde
fghij
klmno
pqrst
1
3 3
Sample Output 1
mlkon
hgfji
cbaed
rqpts
The grid will change as follows.
Sample Input 2
3 7
atcoder
regular
contest
2
1 1
2 5
Sample Output 2
testcon
oderatc
ularreg
The grid will change as follows.
Sample Input 3
2 2
ac
wa
3
1 1
1 1
1 1
Sample Output 3
ac
wa
The grid will change as follows.
题解
同一行/列元素操作后仍在同一行/列
通过观察可以发现,题目所述操作是对整行、整列进行的。因此同一行元素操作后仍在同一行、同一列元素操作后仍在同一列,只是顺序变化了。
由此,我们可以想到,无需维护每次操作整个矩阵的值,而只用维护行列前后对应关系即可,即第
如果使用暴力法,时间复杂度为:
行列对应关系的特点
我们通过一个例子来解释,我们先只考虑行,因为这个问题行列是独立的:
此时获取还看不出规律,我们加上一些辅助:
这样就很明显了,每次操作其实序列都是顺序的,只不过起始点发生了偏移。并且奇数次操作时为逆序,偶数次操作时为顺序。那么我们就不需要维护整个行列对应关系了,而只需要维护起始点
时间复杂度为:
代码
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int H, W;
cin >> H >> W;
vector<string> A(H);
for (int i = 0; i < H; i++)
cin >> A[i];
int Q;
cin >> Q;
int start_row = 0, start_col = 0;
for (int i = 0; i < Q; i++)
{
int a, b;
cin >> a >> b;
a--, b--;
start_row = (start_row <= a) ? (a - start_row) : (H - start_row + a);
start_col = (start_col <= b) ? (b - start_col) : (W - start_col + b);
}
vector<int> row(H), col(W);
if (Q & 1)
{
for (int i = 0; i < H; i++)
row[(start_row - i + H) % H] = i;
for (int i = 0; i < W; i++)
col[(start_col - i + W) % W] = i;
}
else
{
for (int i = 0; i < H; i++)
row[(start_row + i) % H] = i;
for (int i = 0; i < W; i++)
col[(start_col + i) % W] = i;
}
for (int i = 0; i < H; i++)
{
for (int j = 0; j < W; j++)
cout << A[row[i]][col[j]];
cout << endl;
}
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi