We'd like to thank you all for participating in the contest, and hope you enjoyed it. Hope to see you again soon!
Author: Utkarsh59
Only the count of odd numbers matters as XOR with an even number will be even only.
Say there are $$$k$$$ odd numbers. So the XOR of them will be even only when $$$k$$$ is even.
Can you even change the parity of numbers when $$$x$$$ is even?
The XOR of all numbers is even if and only if the number of odd elements in the array is even.
Let $$$c$$$ = count of odd elements.
- If $$$c$$$ is even $$$\Rightarrow$$$ XOR is even
- If $$$c$$$ is odd $$$\Rightarrow$$$ XOR is odd
Thus, the problem reduces to checking if Alice can make the number of odd elements even after exactly $$$k$$$ additions of $$$x$$$.
Case 1: $$$x$$$ is even
If $$$x$$$ is even, the parity of elements never changes.So the count of odd elements $$$c$$$ remains fixed.
Hence:
- If $$$c$$$ is even $$$\Rightarrow$$$ XOR already even $$$\Rightarrow$$$ YES
- Otherwise $$$\Rightarrow$$$ NO
Case 2: $$$x$$$ is odd
Each addition flips the parity of the chosen element:
So, the parity of the number of odd elements changes exactly $$$k$$$ times:
- If $$$k$$$ is even $$$\Rightarrow$$$ parity of $$$c$$$ stays the same
- If $$$k$$$ is odd $$$\Rightarrow$$$ parity of $$$c$$$ flips
We want the final number of odd elements to be even,
so the condition becomes:
Time Complexity: $$$O(n)$$$ per test case.
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k, x;
cin >> n >> k >> x;
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
int c = 0;
for (int i = 0; i < n; i++)
if (v[i] & 1) c++;
if (x % 2 == 0) {
cout << ((c % 2 == 0) ? "YES\n" : "NO\n");
} else {
cout << ((c % 2 == k % 2) ? "YES\n" : "NO\n");
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) solve();
}
Author: MadhavCoding
If a permutation $$$a$$$ can be transformed into $$$b$$$, there exists a single integer $$$k$$$ that works for the entire array, even though multiple operations are allowed.
The correct value of $$$k$$$ can be uniquely determined by checking where the element $$$1$$$ in permutation $$$a$$$ maps in permutation $$$b$$$.
Problem Setup
Let us restate the setting precisely.
We are working under modulo
and both
are permutations of the integers from $$$1$$$ to $$$n$$$.
The allowed operation is:
for some integer $$$k \ge 1$$$.
The question is: can we choose some sequence of $$$k$$$'s (possibly more than one operation) to make $$$a$$$ exactly equal to $$$b$$$?
Key Facts
- Fact 1: All operations combine into one effective multiplier $$$K$$$
- Fact 2: If a valid $$$K$$$ exists, it is unique modulo $$$m = n + 1$$$
- Fact 3: A valid $$$K$$$ must be co-prime with $$$m = n + 1$$$
Using Fact 1, the question becomes simpler: Does there exist an integer
such that
Approach 1: Using the position of 1
This is the simplest and most elegant approach.
- Find the index $$$p$$$ such that $$$a_p = 1$$$.
- The corresponding element in $$$b$$$ (i.e., $$$b_p$$$) must be the multiplier $$$K$$$.
- Verify for every $$$i$$$ that
$$$ (a_i \cdot K) \bmod (n+1) = b_i. $$$ - If all positions match, output "YES", else "NO".
Why does this work?
From $$$a_p = 1$$$, we immediately get:
By uniqueness (Fact 2), this is the only possible candidate for $$$K$$$.
Hence, if this $$$K$$$ works for all indices, it is valid; otherwise, no such $$$K$$$ exists.
Finding the index of $$$1$$$ and verifying the mapping both take $$$O(n)$$$ time.
Time Complexity: $$$O(n)$$$
Approach 2: Modular Inverse Approach
From the transformation condition:
if $$$a_i$$$ is invertible modulo $$$m$$$ (that is, $$$\gcd(a_i, m) = 1$$$),
we can multiply both sides by $$$a_i^{-1}$$$ to obtain:
This gives us a direct formula for $$$K$$$.
Moreover, if multiple indices $$$i, j$$$ have invertible $$$a_i, a_j$$$,
they will all yield the same value of $$$K$$$.
Hence, the steps are as follows:
- Find any $$$a_i$$$ such that $$$\gcd(a_i, n+1) = 1$$$.
- Compute its modular inverse $$$a_i^{-1} \bmod (n+1)$$$.
- Calculate
$$$ K = (b_i \cdot a_i^{-1}) \bmod (n+1). $$$ - Verify for all indices $$$j$$$ that
$$$ (a_j \cdot K) \bmod (n+1) = b_j. $$$ - If all positions match, output "YES", else "NO".
Why we only use coprime elements:
If $$$\gcd(a_i, n+1) \gt 1$$$, then $$$a_i$$$ does not have a modular inverse.
In such cases, the congruence
may have no solution or multiple solutions for $$$K$$$.
Hence, we must pick an element $$$a_i$$$ that is relatively prime to $$$(n+1)$$$ to compute $$$K$$$ safely and uniquely.
Finding one invertible element and its modular inverse takes $$$O(\log n)$$$ time.
Verifying the transformation for all indices takes $$$O(n)$$$ time.
Hence, the overall complexity is: $$$O(n)$$$.
Time Complexity: $$$O(n)$$$
Fact 1: All operations combine into one effective multiplier $$$K$$$
Suppose we perform the operation multiple times with multipliers
Then the transformations on any element $$$a_i$$$ are:
By continuing this process for all $$$r$$$ multipliers, we obtain:
where
Hence, performing any number of operations is equivalent to performing one single operation with multiplier $$$K$$$.
Fact 2: If a valid $$$K$$$ exists, it is unique modulo $$$m = n + 1$$$
Suppose two values $$$K$$$ and $$$K'$$$ both satisfy the transformation condition, i.e.,
for all $$$i$$$.
Subtracting the two congruences, we obtain:
for all $$$i$$$.
Now, since $$$a$$$ is a permutation of $$${1, 2, \ldots, n}$$$,
there exists an index $$$p$$$ such that $$$a_p = 1$$$.
Substituting $$$i = p$$$ gives:
Hence, if a valid $$$K$$$ exists, it is unique modulo $$$m$$$.
Additionally, note that
since this would map every element $$$a_i$$$ to $$$0$$$, violating the permutation property.
Therefore, we always restrict $$$K$$$ to the range
Fact 3: A valid $$$K$$$ must be coprime with $$$m = n + 1$$$.
Let’s analyze the mapping:
We want $$$f$$$ to map the set $$${1, 2, \ldots, n}$$$ bijectively onto itself.
(⇐) If $$$\gcd(K, m) = 1$$$, the map is bijective.
If $$$\gcd(K, m) = 1$$$, then there exists an integer $$$K^{-1}$$$ such that
Now suppose $$$f(x_1) = f(x_2)$$$. Then:
Multiplying both sides by $$$K^{-1}$$$ gives
Hence $$$f$$$ is injective, and since we are in a finite set, it is also bijective.
This means multiplication by $$$K$$$ permutes the numbers $$$1, 2, \ldots, n$$$.
(⇒) If $$$\gcd(K, m) \gt 1$$$, the map is not injective.
Let $$$d = \gcd(K, m) \gt 1$$$.
Then we can write
for some integer $$$r$$$.
Consider
Notice that both $$$x_1, x_2 \in [1, n]$$$ because $$$r = \frac{m}{d} \lt n$$$. Here, we consider $$$n \gt 1$$$. (For $$$n = 1$$$, any function $$$f(x) = (Kx) \bmod m$$$ is trivially injective because there is only one input.)
Now,
and
But since
is divisible by $$$m$$$, we have
Thus,
That means two distinct inputs map to the same output -; the function is not injective.
Therefore, for the transformation to preserve the permutation property, we must have
/*
Author : MadhavCoding
*/
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define pi pair<int, int>
#define pll pair<ll, ll>
#define endl "\n"
const ll MOD = 1e9 + 7;
const ll N = 1e5;
using namespace std;
void solve()
{
int n; cin>>n;
vector<int> a(n), b(n);
int x = -1, k = -1;
for(int i = 0; i < n; i++)
{
cin>>a[i];
if(a[i] == 1) x = i;
}
for(int i = 0; i < n; i++)
{
cin>>b[i];
}
k = b[x];
bool ans = 1;
for(int i = 0; i < n; i++)
{
int need = (1LL * a[i] * k) % (n + 1);
if(b[i] != need)
{
ans = 0;
break;
}
}
if(ans) cout<<"YES\n";
else cout<<"NO\n";
}
int main(int argc, char const *argv[])
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr); std::cout.tie(nullptr);
int t = 1;
cin>>t;
while(t--)
{
solve();
}
return 0;
}
/*
Author : MadhavCoding
*/
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define pi pair<int, int>
#define pll pair<ll, ll>
#define endl "\n"
const ll MOD = 1e9 + 7;
const ll N = 1e5;
using namespace std;
void solve()
{
int n; cin>>n;
vector<int> a(n), b(n);
int x = -1, k = -1;
for(int i = 0; i < n; i++)
{
cin>>a[i];
if(x == -1 && gcd(a[i], n+1) == 1) x = i;
}
for(int i = 0; i < n; i++)
{
cin>>b[i];
}
for(int i = 1; i <= n; i++)
{
int num = (1LL * a[x] * i) % (n + 1);
if(num == 1) // i is inverse of a[x] modulo (n+1)
{
k = (1LL * b[x] * i) % (n + 1);
break;
}
}
bool ans = 1;
for(int i = 0; i < n; i++)
{
int need = (1LL * a[i] * k) % (n + 1);
if(b[i] != need)
{
ans = 0;
break;
}
}
if(ans) cout<<"YES\n";
else cout<<"NO\n";
}
int main(int argc, char const *argv[])
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr); std::cout.tie(nullptr);
int t = 1;
cin>>t;
while(t--)
{
solve();
}
return 0;
}
Author: wolgwang
Try to build the optimal path by considering the towers one by one, from left to right.
When you consider adding a new tower, how does it affect the last tower you decided to include in your path? When can a tower be skipped?
Think about the line of sight from your previous position to your next target. If an intermediate tower is below this line of sight, is it necessary to include it in your path?
Consider the $$$n+2$$$ points which are the top of the towers, the initial Spider-Man position, and Gwen's position.
Iterate over the last $$$n+1$$$ points and maintain a vector of $$$x$$$ coordinates of points that Spider-Man will visit.
For each new point, $$$C$$$ (at index $$$i$$$), look at the last two points added to the vector, let's call them $$$A$$$ (at second last) and $$$B$$$ (at last). Check if it is possible to reach point $$$C$$$ from $$$A$$$ without brushing by point $$$B$$$, i.e. point $$$B$$$ lies below the line segment $$$AC$$$. This is done by comparing the slope of line $$$AC$$$ with the slope of line $$$AB$$$.
If $$$\text{Slope}_{AC} \gt \text{Slope}_{AB}$$$, then point $$$B$$$ is redundant for the optimal path, and it can be removed from the vector. This process is repeated until point $$$C$$$ can be added to the vector without any point being redundant.
Also, make sure to avoid floating-point precision issues when dividing to compare slopes.
The final answer is the number of points in the vector minus two extremes (to exclude the start and end positions).
Time Complexity: $$$O(n)$$$ per test case.
#include <bits/stdc++.h>
using namespace std;
void solve()
{
long long n;
cin>>n;
vector<long long> heights;
heights.push_back(0);
for (int i = 0; i < n; i++)
{
long long x;
cin >> x;
heights.push_back(x);
}
heights.push_back(0);
vector<int> res;
res.push_back(0);
for (int i = 1; i < n + 2; i++) {
while (res.size() >= 2) {
int last = res.back();
int second_last = res[res.size() - 2];
if ((heights[i] - heights[second_last]) * (last - second_last) > (i - second_last) * (heights[last] - heights[second_last])) {
res.pop_back();
}
else {
break;
}
}
res.push_back(i);
}
cout << res.size() - 2 << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) solve();
}
Relation to Convex Hull
You can think of this problem as given a side (line segment from the Spider-Man to Gwen) of a polygon, find the smallest convex polygon that can be formed, including this side. Convexity means that a line segment between any two vertices of the polygon is completely inside the polygon. This ensures that the Spider-Man is not crashing into any building. The vector we were maintaining in the above solution is actually the upper hull of this convex polygon.
The convex hull can be found using Andrew's algorithm in $$$O(n \log n)$$$ time, but as the points are already sorted according to their $$$x$$$ coordinates in the problem, we can find the upper hull in $$$O(n)$$$ time.
So if you were able to come up with the stack-based solution on your own, congrats! You have discovered a well-known computational geometry algorithm on your own! :-)
Author: neal27
Try dynamic programming.
This is a standard dynamic programming problem, where $$$dp_{i, 0}$$$ $$$=$$$ minimum cost of buying first $$$i$$$ items, when last item is chosen from array $$$a$$$, similarly $$$dp_{i, 1}$$$ $$$=$$$ minimum cost of buying first $$$i$$$ items, when last item is chosen from array $$$b$$$. Now for the transition, iterate over the number of consecutive elements that you are picking from one array in the end of prefix from $$$1$$$ to $$$i$$$:
$$$dp_{i, 0} = min(dp_{j, 1} + a_{j + 1} + a_{j + 2} + … + a_{i})$$$, for $$$max(i – k, 1) \le j \le i – 1$$$ $$$dp_{i, 1} = min(dp_{j, 0} + b_{j + 1} + b_{j + 2} + … + b_{i})$$$, for $$$max(i – k, 1) \le j \le i – 1$$$
Time Complexity: $$$\mathcal{O}(n * k)$$$ per each test case
#include <bits/stdc++.h>
using namespace std;
# define ll long long
# define vi vector<int>
# define vl vector<ll>
# define vvl vector<vector<ll>>
# define endl "\n"
template<class n> inline bool chmin(n& base, n b) {
if (base > b) { base = b; return true;}
return false;
}
template<class n> inline bool chmax(n& base, n b) {
if (base < b) { base = b; return true;}
return false;
}
ll INF = 1e18;
void solve() {
int n, k; cin>>n>>k;
vi a(n + 1, 0), b(n + 1, 0);
for(int i = 1; i <= n; i++) cin>>a[i];
for(int i = 1; i <= n; i++) cin>>b[i];
vvl dp(n + 1, vl(2, INF)); dp[0][0] = 0; dp[0][1] = 0;
for(int i = 1; i <= n; i++){
ll asum = a[i], bsum = b[i];
for(int j = i — 1; j >= max(i — k, 0); j--){
chmin(dp[i][0], dp[j][1] + asum);
chmin(dp[i][1], dp[j][0] + bsum);
asum += a[j]; bsum += b[j];
}
}
ll ans = min(dp[n][0], dp[n][1]);
cout<<ans<<endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin.exceptions(cin.failbit);
int t = 1;
cin >> t;
while(t--){
solve();
}
}
Author: neal27
For the DP state used in D1, you handled the transitions for each $$$dp_{i, 0}$$$ and $$$dp_{i, 1}$$$ states in $$$\mathcal{O}(k)$$$ . Can you optimise this to $$$\mathcal{O}(log(k))$$$ per state?
At each index $$$i$$$, you only needed the $$$dp + sum$$$ values for last $$$k$$$ indices, and you required the minimum value among those at most $$$k$$$ values. Can you try sliding window?
For the sliding window, you could use some data structure.
Let’s focus on calculating $$$dp_{i, 0}$$$. We required the minimum of the following values $$$dp_{i - 1, 1} + asum[i: i]$$$, $$$dp_{i - 2, 1} + asum[i - 1: i]$$$, $$$dp_{i - 3, 1} + asum[i - 2: i]$$$, $$$\cdot$$$ , $$$dp_{i - k, 1} + asum[i - k + 1: i]$$$.
For this, we will maintain $$$k$$$ size window (which will be maintained and slided as circular queue). Before processing $$$dp_{i, 0}$$$, we will add $$$a_i$$$ to all the values in the window, and then the minimum value in this window will be $$$dp_{i, 0}$$$. As we move forward, we will need to remove the oldest value in the window, say this is pointed to by pointer $$$l$$$, in the circular queue window. We will replace the old value at $$$l$$$, with current $$$dp_{i, 0}$$$ value, and then increment the pointer $$$l$$$ to point to the now-oldest value in window.
Similarly, a separate circular queue window will be created for handling $$$dp_{i, 1}$$$, and will hold $$$k$$$ recent $$$dp_{j, 0} + bsum[j + 1: i]$$$ values in it.
Now, we need range-add function to add $$$a_i$$$ or $$$b_i$$$ to all values in the circular queue window and a range-min function to get the min value from those $$$k$$$ values, and a point-set function to replace the oldest value, with current $$$dp$$$ value. This can be done using a Lazy Segment Tree easily. And finally, we have brought down the time complexity for transitions to $$$\mathcal{O}(log(k))$$$ per state.
Time Complexity: $$$\mathcal{O}(n * log(k))$$$ per each test case
#include <bits/stdc++.h>
using namespace std;
# define ll long long
# define vi vector<int>
# define vl vector<ll>
# define vvi vector<vector<int>>
# define vvl vector<vector<ll>>
# define endl "\n"
template<class n> inline bool chmin(n& base, n b) {
if (base > b) { base = b; return true;}
return false;
}
template<class n> inline bool chmax(n& base, n b) {
if (base < b) { base = b; return true;}
return false;
}
ll MOD = 1e9 + 7;
ll MOD2 = 998244353;
ll INF = 1e18;
const int MAX_N = 2e6 + 5;
template<typename T>
class SegTree{
int leftmost, rightmost;
SegTree *leftChild, *rightChild;
T mn = INF; T lazySet = INF; T lazyAdd = 0;
public:
SegTree(int leftmost, int rightmost): leftmost(leftmost), rightmost(rightmost) {}
SegTree(int leftmost, int rightmost, vector<T> &a):
leftmost(leftmost), rightmost(rightmost){
if(leftmost == rightmost){
mn = a[leftmost]; // leaf node
leftChild = rightChild = NULL;
}
else{
int mid = leftmost + (rightmost - leftmost)/2; // two children
leftChild = new SegTree(leftmost, mid, a);
rightChild = new SegTree(mid + 1, rightmost, a);
reCalc();
}
}
void reCalc(){
if(leftmost == rightmost) return;
mn = min(leftChild->mn, rightChild->mn);
}
void pushDown(){
if(!leftChild){
int mid = leftmost + (rightmost - leftmost)/2;
leftChild = new SegTree(leftmost, mid);
rightChild = new SegTree(mid + 1, rightmost);
}
if(lazySet != INF){
leftChild->rangeSet(leftmost, rightmost, lazySet);
rightChild->rangeSet(leftmost, rightmost, lazySet);
lazySet = INF;
}
else if(lazyAdd > 0){
leftChild->rangeAdd(leftmost, rightmost, lazyAdd);
rightChild->rangeAdd(leftmost, rightmost, lazyAdd);
lazyAdd = 0;
}
}
void rangeSet(int l, int r, T x){
if(r < leftmost || rightmost < l) return;
if(l <= leftmost && rightmost <= r){
lazySet = x; mn = x; lazyAdd = 0;
}
else{
pushDown(); leftChild->rangeSet(l, r, x); rightChild->rangeSet(l, r, x);
reCalc();
}
}
void rangeAdd(int l, int r, T x){
if(r < leftmost || rightmost < l) return;
if(l <= leftmost && rightmost <= r){
if(lazySet != INF) lazySet += x;
else lazyAdd += x;
mn += x;
}
else{
pushDown(); leftChild->rangeAdd(l, r, x); rightChild->rangeAdd(l, r, x);
reCalc();
}
}
T rangeMin(int l, int r){
if(rightmost < l || leftmost > r) return INF; // entirely disjoint
if(l <= leftmost && rightmost <= r) return mn; // fully covered
pushDown();
return min(leftChild->rangeMin(l, r), rightChild->rangeMin(l, r)); // we don't know
}
};
void solve() {
int n, k; cin>>n>>k;
vi a(n), b(n);
for(int i = 0; i < n; i++) cin>>a[i];
for(int i = 0; i < n; i++) cin>>b[i];
vl c(k, INF); c[k - 1] = 0;
SegTree<ll> dp0(0, k - 1, c);
SegTree<ll> dp1(0, k - 1, c);
ll ans = INF; int l = 0;
for(int i = 0; i < n; i++){
dp0.rangeAdd(0, k - 1, a[i]);
dp1.rangeAdd(0, k - 1, b[i]);
ll dp0i = dp1.rangeMin(0, k - 1);
ll dp1i = dp0.rangeMin(0, k - 1);
dp0.rangeSet(l, l, dp0i);
dp1.rangeSet(l, l, dp1i);
l = (l + 1) % k;
ans = min(dp0i, dp1i);
}
cout<<ans<<endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin.exceptions(cin.failbit);
int t = 1;
cin >> t;
while(t--){
solve();
}
}
Handling the $$$dp_{j, 1} + asum[j + 1: i]$$$ values, could be simplified a little, if you write this range sum $$$asum[j + 1: i]$$$ as $$$prefixSumA_i - prefixSumA_j$$$. Now $$$prefixSumA_i$$$ will be constant for current $$$i$$$, so in current window, you will require only to find minimum among values $$$dp_{j, 1} - prefixSum_j$$$. For this, you won’t require as advanced a data structure as Lazy Segment Tree. As each value is only dependent on one index, you could easily remove and add these values in a multiset, and get the minimum value.
#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<pll, null_type,less<pll>, rb_tree_tag,tree_order_statistics_node_update>
# define ll long long
# define vi vector<int>
# define vl vector<ll>
# define vvi vector<vector<int>>
# define vvl vector<vector<ll>>
# define endl "\n"
template<class n> inline bool chmin(n& base, n b) {
if (base > b) { base = b; return true;}
return false;
}
template<class n> inline bool chmax(n& base, n b) {
if (base < b) { base = b; return true;}
return false;
}
ll MOD = 1e9 + 7;
ll MOD2 = 998244353;
ll INF = 1e18;
const int MAX_N = 2e6 + 5;
void solve() {
int n, k; cin>>n>>k;
vi a(n + 1, 0), b(n + 1, 0);
for(int i = 1; i <= n; i++) cin>>a[i];
for(int i = 1; i <= n; i++) cin>>b[i];
vl prefa(n + 1, 0), prefb(n + 1, 0);
for(int i = 1; i <= n; i++) prefa[i] = prefa[i - 1] + a[i];
for(int i = 1; i <= n; i++) prefb[i] = prefb[i - 1] + b[i];
vl dp0(n + 1, INF), dp1(n + 1, INF);
dp0[0] = 0; dp1[0] = 0;
multiset<ll> st0, st1; st0.insert(0); st1.insert(0);
for(int i = 1; i <= n; i++){
dp0[i] = prefa[i] + (*st0.begin());
dp1[i] = prefb[i] + (*st1.begin());
if(i >= k){
st0.erase(st0.find(dp1[i - k] - prefa[i - k]));
st1.erase(st1.find(dp0[i - k] - prefb[i - k]));
}
st0.insert(dp1[i] - prefa[i]);
st1.insert(dp0[i] - prefb[i]);
}
cout<<min(dp0[n], dp1[n])<<endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin.exceptions(cin.failbit);
int t = 1;
cin >> t;
while(t--){
solve();
}
}
Try implementing this sliding window logic using a minimum queue. You can take a look at this
Preparation: Lazy_Seg_Tree
Solution By: neal27
Let $$$cnt$$$ be the number of distinct values in range $$$[l, r]$$$. Is the answer for the query $$$[l, r]$$$ related to $$$cnt$$$?
The answer will either be $$$cnt$$$ or $$$cnt + 1$$$.
$$$ans = cnt$$$, when there exists at least one value $$$x$$$, whose all indices in the given range $$$[l, r] $$$ form an AP. In first operation, we can choose all occurrences of this $$$x$$$, and after that we can sort the remaining values of the range so that all others have each occurrence in AP.
$$$ans = cnt + 1$$$, when there exists no such x.
Now a set of indices of some value $$$x$$$, are not in AP, if there’s at least one bad triple $$$(i, j, k)$$$ in this set, such that they are not in AP, i.e. $$$j – i \neq k – j$$$.
If we count only distinct values $$$x$$$, whose rightmost bad triple occurs in the range $$$[l, r]$$$, say $$$cnt1$$$, and this $$$cnt1 == cnt$$$, then we have no element in range $$$[l, r]$$$ which has all its occurrences in AP, so $$$ans$$$ will be $$$cnt + 1$$$, else it will be $$$cnt$$$.
So, we solve queries offline by sorting them according to their R values, and then iterate from left to right.
We maintain a Segment Tree, say $$$tr1$$$ over $$$n$$$ size array, where for each distinct value, the rightmost index will have value $$$1$$$, and rest of its occurrences will have value $$$0$$$. Then range sum query on $$$[l, r]$$$ will give the count of distinct values in the range.
Similarly, we will maintain another Segment Tree, say $$$tr2$$$ over $$$n$$$ size array, where for each distinct value, the left index of the rightmost bad triple will have value $$$1$$$, and rest of the occurrences of that value will have value $$$0$$$. Then range sum query on $$$[l, r]$$$ will give the count of distinct values in the range whose all occurrences are not in AP.
Time Complexity: $$$\mathcal{O}((n + q) * log(n))$$$ per each test case
#include <bits/stdc++.h>
using namespace std;
# define ll long long
# define vi vector<int>
# define vl vector<ll>
# define vvi vector<vector<int>>
# define vvl vector<vector<ll>>
# define pii pair<int,int>
# define pll pair<ll,ll>
# define vpii vector<pii>
# define endl "\n"
template<class n> inline bool chmin(n& base, n b) {
if (base > b) { base = b; return true;}
return false;
}
template<class n> inline bool chmax(n& base, n b) {
if (base < b) { base = b; return true;}
return false;
}
ll MOD = 1e9 + 7;
ll MOD2 = 998244353;
ll INF = 1e18;
const int MAX_N = 2e6 + 5;
template<typename T>
class SegTree{
int leftmost, rightmost;
SegTree *leftChild, *rightChild;
T sum;
public:
void recalc(){
if(leftmost == rightmost) return;
sum = leftChild->sum + rightChild->sum;
}
SegTree() : leftmost(-1), rightmost(-1), leftChild(NULL), rightChild(NULL), sum(0) {}
SegTree(int leftmost, int rightmost, vector<T> &a){
this->leftmost = leftmost; this->rightmost = rightmost;
if(leftmost == rightmost){
sum = a[leftmost]; // leaf node
leftChild = rightChild = NULL;
}
else{
int mid = leftmost + (rightmost - leftmost)/2; // two children
leftChild = new SegTree(leftmost, mid, a);
rightChild = new SegTree(mid + 1, rightmost, a);
recalc();
}
}
void pointUpdate(int index, T newVal){
if(leftmost == rightmost) sum += newVal; // leaf node
else{
// two children
if(index <= leftChild->rightmost) leftChild->pointUpdate(index, newVal); // index in left child
else rightChild->pointUpdate(index, newVal); // index in right child
recalc();
}
}
T rangeSum(int l, int r){
if(rightmost < l || leftmost > r) return 0; // entirely disjoint
if(l <= leftmost && rightmost <= r) return sum; // fully covered
return leftChild->rangeSum(l, r) + rightChild->rangeSum(l, r); // we don't know
}
};
int normalize(vi &b){
map<int, int> mpp; int x = 0, n = b.size();
for(int i = 0; i < n; i++){
if(mpp.find(b[i]) == mpp.end()) mpp[b[i]] = x++;
b[i] = mpp[b[i]];
}
return x;
}
void solve() {
int n, q, z; cin>>n;
vi a(n);
for(int i = 0; i < n; i++) cin>>a[i];
z = normalize(a);
cin>>q;
vpii queries[n];
for(int i = 0; i < q; i++){
int l, r; cin>>l>>r; l--; r--;
queries[r].push_back({l, i});
}
vi ind[z];
for(int i = 0; i < n; i++) ind[a[i]].push_back(i);
vi k(z, 0);
vi last(z, -1), lastk(z, -1);
vi b(n, 0), ans(q, 0);
SegTree<int> tr(0, n - 1, b);
SegTree<int> trk(0, n - 1, b);
for(int r = 0; r < n; r++){
if(k[a[r]] >= 2){
int pos = k[a[r]], val = a[r];
if(ind[val][pos] - ind[val][pos - 1] != ind[val][pos - 1] - ind[val][pos - 2]){
if(lastk[val] != -1) trk.pointUpdate(lastk[val], -1);
trk.pointUpdate(ind[val][pos - 2], 1);
lastk[val] = ind[val][pos - 2];
}
}
k[a[r]]++;
tr.pointUpdate(r, 1);
if(last[a[r]] != -1) tr.pointUpdate(last[a[r]], -1);
last[a[r]] = r;
for(auto [l, i]: queries[r]){
ans[i] = tr.rangeSum(l, r);
if(trk.rangeSum(l, r) == ans[i]) ans[i]++;
}
}
for(int i: ans) cout<<i<<endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin.exceptions(cin.failbit);
int t = 1;
//cin >> t;
while(t--){
solve();
}
}







