Problem Author: | Andrii Kholod (Connect) |
Prepared by: | Andrii Kholod (Connect) |
Editorial: | Andrii Kholod (Connect) |
Solution
First, note that if we were able to make a_i = b_i for some position , then we can also make a_j = b_j for all j < i. Therefore, the task reduces to finding the largest for which we can make a_i = b_i.
Also, note that when applying operations of the first and second types to some index , the value of a_{i-1} - (i-1) becomes equal to a_i - i. The same applies to the array , since (a_i - 1) - (i - 1) = a_i - i. And when applying the third type of operation, for all greater than the deleted index , the values of a_j - j and b_j - j decrease by one.
Thus, the problem is reduced to determining, for each , whether on the suffix [i+1, |b|] of the array there exists an index such that a_i - i = b_j - j. Also, on the suffix [i+2, |b|] of the array , whether there exists an index such that a_i - i = b_j - j + 1. The same reasoning applies symmetrically with respect to the array .
This can be implemented using a set or map.
The time complexity of this solution is O(n \times \log n).
#include <bits/stdc++.h>
// fast_pragmas
//#pragma GCC optimize("O3")
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC target("avx,avx2,tune=native")
// fast_pragmas ended
//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4")
//#pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt")
using namespace std;
#define ull unsigned long long
#define ll long long
#define ld long double
#define speed ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define endl '\n'
#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
#define pb push_back
#define ln log
#define lg log10
#define log log2
#define here cout<<"HERE"<<endl
const ll clasik = 2e5+7;
const ll mln = 1e6+7;
const ll mod = 1e9+7;
//const ll mod = 998244353;
const ll block_size = 450;
const ll INF = 1e17;
ll df[clasik];
ll a[clasik], b[clasik];
void solve() {
ll n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
a[i] = a[i] - i;
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
b[i] = b[i] - i;
}
set<ll> st1, st2;
for (int i = n; i >= 1; i--) {
if (a[i] == b[i]) {
cout << i << endl;
return;
}
if (i == n) continue;
if (st2.count(a[i]) || a[i] == b[i+1]) {
cout << i << endl;
return;
}
if (st1.count(b[i]) || b[i] == a[i+1]) {
cout << i << endl;
return;
}
if (st2.count(a[i] - 1)) {
cout << i << endl;
return;
}
if (st1.count(b[i] - 1)) {
cout << i << endl;
return;
}
st1.insert(a[i+1]);
st2.insert(b[i+1]);
}
cout << 0 << endl;
}
signed main() {
speed;
int test = 1;
for (int tt = 1; tt <= test; tt++) {
solve();
}
return 0;
}