《喵了个喵》代码,时间复杂度
#include <bits/stdc++.h>
using namespace std;
struct Node {
int op, x, y;
};
int main() {
int _;
scanf("%d", &_);
while (_--) {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
vector<int> a(m + 1);
vector<Node> ans;
vector<int> home(k + 1); //每个卡片所属的栈编号
vector<deque<int>> s(n + 1); //栈
queue<int> q; //可以分配的栈的编号
int kong = n; //特殊栈编号
for (int i = 1; i < n; i++) q.push(i), q.push(i); //除了特殊栈 每个栈可以提供两个空位
for (int i = 1; i <= m; i++) {
scanf("%d", &a[i]);
}
auto cz1 = [&](int x, int t) {
ans.push_back({1, x, 0});
if (s[x].size() > 0 && s[x].back() == t) {
s[x].pop_back();
if (x != kong && s[x].size() < 2) q.push(x);
home[t] = 0;
} else {
s[x].push_back(t);
home[t] = x;
}
};
auto cz2 = [&](int x, int y) {
ans.push_back({2, x, y});
home[s[x][0]] = 0;
s[x].pop_front();
s[y].pop_front();
if (s[x].size() < 2) q.push(x);
};
for (int i = 1; i <= m; i++) {
int x = home[a[i]];
if (x) {
if (s[x].size() == 1)
cz1(x, a[i]);
else if (s[x].back() == a[i])
cz1(x, a[i]);
else {
cz1(kong, a[i]);
cz2(x, kong);
}
continue;
}
if (q.size() > 0) {
x = q.front();
q.pop();
cz1(x, a[i]);
continue;
}
// 此时除特殊栈外,其他栈都有两个元素
// 找到底部最早出来的栈x 暴力找不会有交叉 保证复杂度O(m)
for (int j = i + 1;; j++) {
if (a[j] == a[i]) {
break;
}
if (s[home[a[j]]][0] == a[j]) {
x = home[a[j]];
break;
}
}
if (x == 0) { //把a[i]放入特殊栈不影响
cz1(kong, a[i]);
} else {
int u = s[x].front(), v = s[x].back();
for (int j = i + 1;; j++) {
if (a[j] == u) {
cz1(x, a[i]); //底部先出,放到x此时会有3个元素
break;
}
if (a[j] == v) {
// 顶部先出,把x作为特殊栈
cz1(kong, a[i]);
q.push(kong); //kong这个栈还能放一个元素
kong = x;
break;
}
}
}
}
printf("%d\n", ans.size());
for (auto [op, x, y] : ans) {
if (op == 1)
printf("1 %d\n", x);
else
printf("2 %d %d\n", x, y);
}
}
return 0;
}