这是一道数据结构题。
每次的操作为移动龙头或查询位置:首先是移动龙头,朴素做法是用一个数组每次遍历一遍修改数据,时间复杂度为 O ( N Q ) O(NQ) O(NQ),会超时;这里我们能发现的是:整个数据只有头和尾改变了,即前面加一个数,后面去掉一个数,这时,我们自然就想到使用队列或双端队列;其次是查询位置,由于队列不能直接用下标的方式查询,所以我们只能用双端队列。
总的时间复杂度为 O ( N + Q ) O(N+Q) O(N+Q)。
Code:
#include <bits/stdc++.h>
#define int long long
#define x first
#define y second
#define PII pair<int, int>
using namespace std;
const int N = 1e6 + 10;
int n, q;
deque<PII > a;
signed main() {
cin >> n >> q;
for (int i = n; i >= 1; i -- ) a.push_back(make_pair(i, 0));
while (q -- ) {
int op;
cin >> op;
if (op == 1) {
char c;
PII s;
cin >> c;
if (c == 'U') {
s.x = a[n - 1].x;
s.y = a[n - 1].y + 1;
} else if (c == 'D') {
s.x = a[n - 1].x;
s.y = a[n - 1].y - 1;
} else if (c == 'R') {
s.x = a[n - 1].x + 1;
s.y = a[n - 1].y;
} else {
s.x = a[n - 1].x - 1;
s.y = a[n - 1].y;
}
a.push_back(s);
a.pop_front();
} else {
int p;
cin >> p;
cout << a[n - p].x << ' ' << a[n - p].y << '\n';
}
}
}