Algorithm/palin/main.cc

80 lines
2.0 KiB
C++
Raw Permalink Normal View History

2024-10-11 14:00:06 +00:00
#include <iostream>
#include <deque>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1000005;
int arr[N], brr[N], crr[N], n;
bool calc(char op) {
deque<int> a, b;
string out, append;
out.push_back(op);
append.push_back('L');
if (op == 'L') {
for (int i = 2; i < crr[1]; i++) a.push_back(i);
for (int i = n; i > crr[1]; i--) b.push_back(i);
} else {
for (int i = 1; i < crr[n]; i++) a.push_back(i);
for (int i = n - 1; i > crr[n]; i--) b.push_back(i);
}
while (!a.empty() || !b.empty()) {
int x1 = !a.empty() ? a.front() : 0;
int x2 = !b.empty() ? b.front() : 0;
int y1 = !a.empty() ? a.back() : 0;
int y2 = !b.empty() ? b.back() : 0;
if (crr[x1] == y1) {
out.push_back('L');
append.push_back('L');
a.pop_front();
a.pop_back();
} else if (crr[x1] == y2) {
out.push_back('L');
append.push_back('R');
a.pop_front();
b.pop_back();
} else if (crr[x2] == y1) {
out.push_back('R');
append.push_back('L');
b.pop_front();
a.pop_back();
} else if (crr[x2] == y2) {
out.push_back('R');
append.push_back('R');
b.pop_front();
b.pop_back();
} else {
return false;
}
}
reverse(append.begin(), append.end());
out += append;
cout << out << endl;
return true;
}
int main() {
int T;
cin >> T;
while (T--) {
cin >> n;
memset(brr, 0, sizeof brr);
n *= 2;
crr[0] = -1;
for (int i = 1; i <= n; i++) {
cin >> arr[i];
if (brr[arr[i]]) {
crr[brr[arr[i]]] = i;
crr[i] = brr[arr[i]];
} else {
brr[arr[i]] = i;
}
}
if (!calc('L') && !calc('R')) cout << -1 << endl;
}
}