This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define MAXN 500005
int n;
int arr[2*MAXN], brr[2*MAXN];
array<int, 2> dp[2*MAXN][2]; //a = 0, b = 1
vector<char> ans;
array<int, 2> comb(array<int, 2> a, array<int, 2> b){
if(a[0] == -1) return b;
if(b[0] == -1) return a;
return {min(a[0], b[0]), max(a[1], b[1])};
}
array<int, 2> add1(array<int, 2> a){
if(a[0] == -1) return a;
return {a[0]+1, a[1]+1};
}
bool contain(array<int, 2> a, int val){
return val >= a[0] && a[1] >= val;
}
void trace(int i, int j, int val){
if(i == 0){
if(j == 0) ans.push_back('A');
else ans.push_back('B');
return;
}
if(j == 0){
if(arr[i] >= arr[i-1]){
if(contain(dp[i-1][0], val)){
ans.push_back('A');
trace(i-1, 0, val);
return;
}
}
if(arr[i] >= brr[i-1]){
if(contain(dp[i-1][1], val)){
ans.push_back('A');
trace(i-1, 1, val);
return;
}
}
}
else{
if(brr[i] >= arr[i-1]){
if(contain(add1(dp[i-1][0]), val)){
ans.push_back('B');
trace(i-1, 0, val-1);
return;
}
}
if(brr[i] >= brr[i-1]){
if(contain(add1(dp[i-1][1]), val)){
ans.push_back('B');
trace(i-1, 1, val-1);
return;
}
}
}
}
int main(){
// freopen("a.in", "r", stdin);
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for(int i = 0; i<2*n; i++) cin >> arr[i];
for(int i = 0; i<2*n; i++) cin >> brr[i];
for(int i = 0; i<2*n; i++) dp[i][0] = dp[i][1] = {-1, -1};
dp[0][0] = {0, 0};
dp[0][1] = {1, 1};
for(int i = 1; i<2*n; i++){
if(arr[i] >= arr[i-1]) dp[i][0] = comb(dp[i][0], dp[i-1][0]);
if(arr[i] >= brr[i-1]) dp[i][0] = comb(dp[i][0], dp[i-1][1]);
if(brr[i] >= arr[i-1]) dp[i][1] = comb(dp[i][1], add1(dp[i-1][0]));
if(brr[i] >= brr[i-1]) dp[i][1] = comb(dp[i][1], add1(dp[i-1][1]));
}
if(!(contain(dp[2*n-1][0], n) || contain(dp[2*n-1][1], n))){
cout << -1 << endl;
return 0;
}
if(contain(dp[2*n-1][0], n)) trace(2*n-1, 0, n);
else trace(2*n-1, 1, n);
reverse(ans.begin(), ans.end());
for(auto x : ans) cout << x;
cout << endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |