**Hint**

Any array can be sorted using no more than $$$\frac{n(n-1)}2$$$ operations. Think or guess when we need exactly $$$\frac{n(n-1)}2$$$ operations.

**Solution**

**Code in C++ (Wind_Eagle)**

```
#include<iostream>
using namespace std;
int a[1000000+5];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while (t--)
{
int n;
cin>>n;
for (int i=0; i<n; i++)
{
cin>>a[i];
}
bool can=false;
for (int i=1; i<n; i++)
{
if (a[i]>=a[i-1])
{
can=true;
break;
}
}
if (can) cout<<"YES"<<'\n';
else cout<<"NO"<<'\n';
}
}
```

**Hint**

Think of a simple criteria when `a_i & a_j >= a_i ^ a_j`

by considering the bits from highest to lowest. Apply your observations to calculate the answer fast.

**Solution**

**Code in C++ (Wind_Eagle)**

```
#include<iostream>
#include<vector>
#include<algorithm>
#include<ctime>
#include<random>
using namespace std;
mt19937 rnd(time(NULL));
int a[1000000+5];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while (t--)
{
int n;
cin>>n;
for (int i=0; i<n; i++)
{
cin>>a[i];
}
int64_t ans=0;
for (int j=29; j>=0; j--)
{
int64_t cnt=0;
for (int i=0; i<n; i++)
{
if (a[i]>=(1<<j)&&a[i]<(1<<(j+1)))
{
cnt++;
}
}
ans+=cnt*(cnt-1)/2;
}
cout<<ans<<'\n';
}
}
```

1420C1 - Pokémon Army (easy version)

**Hint**

Use dynamic programming.

**Solution**

**Code in C++ (gepardo)**

```
#include <iostream>
#include <vector>
using namespace std;
inline int64_t calc(const vector<int> &a) {
int n = a.size();
vector<int64_t> d1(n+1), d2(n+1);
d1[0] = -static_cast<int64_t>(1e18);
d2[0] = 0;
for (int i = 0; i < n; ++i) {
d1[i+1] = max(d1[i], d2[i] + a[i]);
d2[i+1] = max(d2[i], d1[i] - a[i]);
}
return max(d1.back(), d2.back());
}
int main() {
ios_base::sync_with_stdio(false);
int t; cin >> t;
while (t--) {
int n, q; cin >> n >> q;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
cout << calc(a) << "\n";
for (int i = 0; i < q; ++i) {
int l, r; cin >> l >> r; --l; --r;
swap(a[l], a[r]);
cout << calc(a) << "\n";
}
}
return 0;
}
```

1420C2 - Pokémon Army (hard version)

**Hint**

The dynamic programming doesn't work here. Consider taking only local minima and maxima and think whether we need to take something else.

**Solution**

**Code in Java (gepardo)**

```
import java.io.*;
import java.util.*;
public class C2_Java {
int[] a;
int n;
long ans;
void add(int i, int sign) {
if (i == 0 || i == n+1) return;
if (a[i-1] < a[i] && a[i] > a[i+1]) ans += sign * a[i];
if (a[i-1] > a[i] && a[i] < a[i+1]) ans -= sign * a[i];
}
void addTwo(int l, int r, int sign) {
if (l == r) return;
if (l+1 == r) {
add(l-1, sign);
add(l, sign);
add(r, sign);
add(r+1, sign);
return;
}
add(l-1, sign);
add(l, sign);
add(l+1, sign);
if (l+2 != r) add(r-1, sign);
add(r, sign);
add(r+1, sign);
}
public void run() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer tok = new StringTokenizer(in.readLine());
int t = Integer.parseInt(tok.nextToken());
while (t --> 0) {
tok = new StringTokenizer(in.readLine());
n = Integer.parseInt(tok.nextToken());
int q = Integer.parseInt(tok.nextToken());
a = new int[n + 2];
tok = new StringTokenizer(in.readLine());
for (int i = 1; i <= n; ++i) {
a[i] = Integer.parseInt(tok.nextToken());
}
a[0] = -1;
a[n+1] = -1;
ans = 0;
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= n; ++i) {
if (a[i-1] < a[i] && a[i] > a[i+1]) ans += a[i];
if (a[i-1] > a[i] && a[i] < a[i+1]) ans -= a[i];
}
builder.append(ans).append("\n");
while (q --> 0) {
tok = new StringTokenizer(in.readLine());
int l = Integer.parseInt(tok.nextToken());
int r = Integer.parseInt(tok.nextToken());
if (l == r) {
builder.append(ans).append("\n");
continue;
}
addTwo(l, r, -1);
int tmp = a[l];
a[l] = a[r];
a[r] = tmp;
addTwo(l, r, +1);
builder.append(ans).append("\n");
}
out.write(builder.toString());
}
in.close();
out.close();
}
public static void main(String[] args) throws IOException {
(new C2_Java()).run();
}
}
```

**Code in C++ (Wind_Eagle)**

```
#include<iostream>
using namespace std;
#define int long long
int a[1000000+5];
int n;
int ans=0;
inline void insert(int i)
{
if (i==0||i==n+1) return;
if (a[i-1]<a[i]&&a[i]>a[i+1]) ans+=a[i];
if (a[i-1]>a[i]&&a[i]<a[i+1]) ans-=a[i];
}
inline void erase(int i)
{
if (i==0||i==n+1) return;
if (a[i-1]<a[i]&&a[i]>a[i+1]) ans-=a[i];
if (a[i-1]>a[i]&&a[i]<a[i+1]) ans+=a[i];
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while (t--)
{
int q;
cin>>n>>q;
for (int i=1; i<=n; i++)
{
cin>>a[i];
}
a[0]=-1;
a[n+1]=-1;
ans=0;
for (int i=1; i<=n; i++)
{
if (a[i-1]<a[i]&&a[i]>a[i+1]) ans+=a[i];
if (a[i-1]>a[i]&&a[i]<a[i+1]) ans-=a[i];
}
cout<<ans<<'\n';
while (q--)
{
int l,r;
cin>>l>>r;
erase(l-1);
erase(l);
erase(l+1);
if (l!=r)
{
if (r-1!=l+1&&r-1!=l) erase(r-1);
if (r!=l+1) erase(r);
erase(r+1);
}
swap(a[l],a[r]);
insert(l-1);
insert(l);
insert(l+1);
if (l!=r)
{
if (r-1!=l+1&&r-1!=l) insert(r-1);
if (r!=l+1) insert(r);
insert(r+1);
}
cout<<ans<<'\n';
}
}
}
```

**Hint**

The intersection of any $$$k$$$ segments is either empty or is a segment. Let's fix the left bound of the intersection and calculate the number of sets of $$$k$$$ segments such that their intersection starts in this left bound.

**Solution**

**Code in Java (gepardo)**

```
import java.io.*;
import java.util.*;
public class D_Java {
public static final int MOD = 998244353;
public static int mul(int a, int b) {
return (int)((long)a * (long)b % MOD);
}
int[] f;
int[] rf;
public int C(int n, int k) {
return (k < 0 || k > n) ? 0 : mul(f[n], mul(rf[n-k], rf[k]));
}
public static int pow(int a, int n) {
int res = 1;
while (n != 0) {
if ((n & 1) == 1) {
res = mul(res, a);
}
a = mul(a, a);
n >>= 1;
}
return res;
}
static void shuffleArray(int[] a) {
Random rnd = new Random();
for (int i = a.length-1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int tmp = a[index];
a[index] = a[i];
a[i] = tmp;
}
}
public static int inv(int a) {
return pow(a, MOD-2);
}
public void doIt() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tok.nextToken());
int k = Integer.parseInt(tok.nextToken());
f = new int[n+42];
rf = new int[n+42];
f[0] = rf[0] = 1;
for (int i = 1; i < f.length; ++i) {
f[i] = mul(f[i-1], i);
rf[i] = mul(rf[i-1], inv(i));
}
int[] events = new int[2*n];
for (int i = 0; i < n; ++i) {
tok = new StringTokenizer(in.readLine());
int le = Integer.parseInt(tok.nextToken());
int ri = Integer.parseInt(tok.nextToken());
events[i] = le*2;
events[i + n] = ri*2 + 1;
}
shuffleArray(events);
Arrays.sort(events);
int ans = 0;
int balance = 0;
for (int r = 0; r < 2*n;) {
int l = r;
while (r < 2*n && events[l] == events[r]) {
++r;
}
int added = r - l;
if (events[l] % 2 == 0) {
// Open event
ans += C(balance + added, k);
if (ans >= MOD) ans -= MOD;
ans += MOD - C(balance, k);
if (ans >= MOD) ans -= MOD;
balance += added;
} else {
// Close event
balance -= added;
}
}
in.close();
System.out.println(ans);
}
public static void main(String[] args) throws IOException {
(new D_Java()).doIt();
}
}
```

**Hint 1**

Let's keep the number of zeroes between any pair consecutive ones instead of the original array of zeroes and ones. How will the swap operation look in this case. How to calculate the protection?

**Hint 2**

Suppose we have the initial array and the final array. Think of the number of operations you need to make the first one equal to the second one.

**Hint 3**

Join all your observations together and use DP.

**Solution**

**Code in C++ (gepardo)**

```
#include <cassert>
#include <climits>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
template<typename T>
inline void umin(T &a, const T &b) {
a = min(a, b);
}
template<typename T>
inline void umax(T &a, const T &b) {
a = max(a, b);
}
int main() {
ios_base::sync_with_stdio(false);
int n; cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
a.push_back(1);
vector<int> gg;
for (int i = 0; i <= n; ++i) {
int s = i;
while (a[i] == 0) ++i;
gg.push_back(i - s);
}
vector<int> p = gg;
partial_sum(begin(p), end(p), begin(p));
constexpr int mx = 103;
constexpr int dx = mx + 1, dy = mx + 1, dz = mx * (mx + 1) / 2 + 1;
static int dp[dx][dy][dz] = {};
for (int i = 0; i < dx; ++i) {
for (int j = 0; j < dy; ++j) {
for (int k = 0; k < dz; ++k) {
dp[i][j][k] = INT_MAX;
}
}
}
dp[0][0][0] = 0;
int k = gg.size(), l = p.back();
for (int i = 0; i < k; ++i) {
for (int j = 0; j <= l; ++j) {
for (int s = 0; s <= n * (n-1) / 2; ++s) {
if (dp[i][j][s] == INT_MAX) continue;
for (int q = j; q <= l; ++q) {
umin(dp[i+1][q][s + abs(q - p[i])], dp[i][j][s] + (q-j)*(q-j));
}
}
}
}
int mn = INT_MAX;
for (int s = 0; s <= n * (n-1) / 2; ++s) {
umin(mn, dp[k][l][s]);
int val = l*l - mn;
assert(val % 2 == 0);
cout << val/2 << " ";
}
cout << endl;
return 0;
}
```

Auto comment: topic has been translated by gepardo (original revision, translated revision, compare)Video Solution B — https://youtu.be/4U9WZVi4gdY Video Solution C(easy)- https://youtu.be/IWpnF3oUdR8

Actually, many people say that now there are practically no data structure or DP tasks, only ad-hoc and constructive. Well, this contest disproves this. There were no constructive tasks, but there were Segment Tree in C2 (there is a solution using it) and DP in E.

One contest doesn't disprove a trend.

I am actually better at ad-hoc and constructive currently and loved the trend :sobs:, But I do like these rounds where I learn a lot.

Please could you explain/hint about the Segment tree solution of C2. How will we merge answer of left and right for getting answer of current node ? Thanks in advance!

You can maintain four quantities in the segment tree node i.e maximum strength given that

1. first element has $$$plus$$$ sign before it and last one also has $$$plus$$$ sign

2. first element has $$$plus$$$ sign and last has $$$minus$$$

3. first element has $$$minus$$$ sign and last has $$$plus$$$ sign

4. first element has $$$minus$$$ sign and last has $$$minus$$$ sign

You can easily implement merge and update operations.

Here is my implementation https://codeforces.com/contest/1420/submission/93716090. There may be easier solutions but this one was more obvious and intutive

Got it bro. Thanks a lot fenwick123.

Tch tch, "fenwick123" had to use segment tree. xD

Hey, I'm trying to implement your approach, but I'm getting TLE

Link to my code: https://codeforces.com/contest/1420/submission/95420456

Hi Sir, I wanted to know is there any site that focusses more on data structures and less on ad-hoc?

I think atcoder contests are better in this matter.

Leetcode problems and its contests.

I implemented segtree and received tle in C2. someone willing to help? https://codeforces.com/contest/1420/submission/93731337

Massive output, use \n instead of endl.

Also, if you exepected segtree, the constraints could've been relaxed (:

@Wind_Eagle can you give the solution of problem c2 using segment Tree.

For E, if we accept solution in O(n^5), I think it may be better to choose a smaller n. For me, I was too afraid that an O(n^5) solution will TL and just tried to think of a better solution.

We initially thought of making $$$n \le 100$$$ in this problem, because my solution in $$$O(n^5)$$$ passes with such constraints. Anyway, the DP solution is pretty fast and $$$n^5$$$ can be easily divided by some constant factor, so the constraints may seem too big for $$$O(n^5)$$$.

I can understand your choosing n<=80. Maybe I just need to accept the fact that computers are much faster nowadays.

BTW, my solution at https://paste.storage.boleyn.su/cfr672d2e.cpp should have a better time complexity. I have not analyzed its TC yet so this is just my guess.

Can you explain your approach? Is it true that you use a DP similar to the one described in the editorial, but you optimized the code by skipping invalid DP states?

For the last dimension, it is non-decreasing, so we can express it using a vector<pair<int,int>> and reduce some useless states.

My guess is that there may be a bound better than O(n^2) for it. It would be nice to prove or disprove my guess.

UPD: I tested it with larger constraints. It turns out that my guess is wrong. The size of vector<pair<int,int>> is still O(n^2).

I felt like D had hard time limits. But, later realized after contest with precomputation of inverse of each factorial it could have been made faster.

Can you(someone) explain how to do that? Cause I got a TLE on pretest-11.

precompute fact 1 to n and mod inverse of those instead of computing them every time.

Actually, I did that but still got a TLE(UPDATED: NEVER MIND I PASSED IT)

you can calculate the mod inverse at run time also, pre-computing the factorials is enough

Precompute factorials from 0 to N (here $$$3*10^{5}) $$$ initially in an array, say $$$fact$$$.

Then calculate inverse factorial of N using formula $$$inv_f(N) = fact(N)^{MOD-2} \% MOD $$$

which takes $$$ O(\log_2 (MOD))$$$ time. Using this value, now fill the remaing values from N-1 to 0 using recurrence : $$$inv_f(i) = (i+1)*inv_f(i+1)$$$.

Thus we can precompute inverse factorials in $$$ O(N) $$$ complexity.

Solution for reference : 93729779

Hey, I precomputed the factorials and inverse factorials similar to your solution but I am getting TLE.

Use binary exponentiation in your

powmodfunction to calculate $$$a^b$$$ in log(b) complexity, you are calculating it in O(b) time. You can read it here : cp-algoThanks, didn't know about binary exponentiation.

Can you tell is problem D is some standard type based because getting that intution was tough at first tym as mentioned in solution

Note that precalculateing the inverse factorial does not give a better runtime. We never need to calculate more than $$$3*10^5$$$ inverses. So precalculating them just uses more memory, but not less time.

But to calculate $$$3*10^5$$$ inverse factorials you'd have to calculate them in $$$O(log_2(Mod))$$$ individually resulting in $$$O(N*log(Mod)$$$ time. But here I am precalculating them in $$$O(N)$$$, so I am unable to understand your logic behind why this won't give better runtime? Can you please elaborate.

You are right. I was irritated by the long runtime of your solution. But that is caused by the use of the map instead of sorting an array once.

I encountered this for the first time, tried to dig around but can't figure out why this works-

Can u help or tell me where to look.

Does this makes sense?

$$$(n+1)!^{−1} = (n!*(n+1))^{-1}$$$

$$$(n+1)!^{−1} = n!^{−1}*(n+1)^{−1}$$$

$$$(n+1)!^{−1}*(n+1) = n!^{−1}$$$

Watch from 16:00 onwards Lecture on Combinatorics By Kevin Charles Atienza

Hi there. Please, tell me about inverse factorial of N. What is it?

the inverse of any number n is just 1/n

I precomputed the factorials and the inverses, thus my solution was linear, though I think $$$O(n\log mod)$$$ should fit in time.

Great problemset, like it . waiting for your next contest,thanks

For some problem editorial is in english and for others it's in russian . Pls Fix.

The English versions will be loaded in several minutes.

Can you tell if the elements of array in C1 are not distinct what will happen??

I don't understand your question. The elements $$$a_i$$$

aredistinct by problem statement. Or do you want to know if the intended solution works if equal elements are allowed?Yess if we go by approach for maxima and minima approach for C1 problem then will it work??

It is unclear how we will treat an element if its neighbor is equal to it. Or even worse, when both neighbors are equal to our element. Will it be a local maximum or local minimum? Also it's important that local minima and local maxima must alternate (this property is used actively in the proof).

Anyway, it's an interesting question on how to fix the solution when equal elements are allowed.

If you solve C1 using dynamic programming, you should not be affected by equal elements.

Yess C1 by dp will work.. And is there any specific reason for giving ai values from 1 to n??

One may assume that out of equal neighboring elements, the left one is smaller. This is equivalent to adding $$$i \cdot \varepsilon$$$ to $$$a_i$$$, which makes all elements distinct while keeping the answer the same if $$$\varepsilon \rightarrow 0$$$.

A trivial fix is to break ties by index, so that if $$$a_i = a_{i+1}$$$, we can simply pretend $$$a_i < a_{i+1}$$$. This is safe because the value of the optimal solution is continuous in the values of $$$a_i$$$ and we can imagine taking $$$a_i = \lim_{\varepsilon \to 0^+} a_i + i \cdot \varepsilon$$$ simultaneously at all indices. Alternatively, the solutions based on the $$$\sum_{i = 1}^n \max (0, a_i - a_{i-1})$$$ formula or on segment trees are completely unchanged, since they do not make use of the distinctness constraint in any way.

EDIT: I was beaten to the punch! So it goes.

what is "Разбор"???? is it rated??

It is a Russian word for "parsing".

It's better to translate "разбор" as "analysis" :)

thank you!!1!

Round was great. Kudos to author!!

My editorial is in Russian :(

Everything is OK now, except problem E.

UPD: Problem E is also OK now.Does "except problem E" mean this?

Yes.

I could not solve a single problem in this contest, should I die? Why am I even alive.

Don't feel demotivated you have given just few contest.just keep practicing and keep motivated :)

Same bro, not able to solve a single question. But after see the first questions editorial, i think that i thought too much for that question. Can anyone suggest how to approach a question when your attempts are wrong ( means when your pretests doesn't pass ).

@shivam_0105, first decide which one of the following is going wrong

your logic your approach or is it some specific test case? is your datatype overflowing somewhere? (I did not get a warning of overflow in contest this time that is why I could not submit my correct B solution during contest)

if you are confident that 2 out of 3 are 100% correct then try to think what might be wrong with the 3rd one... if still you are not able to get it, just move on, read the next question

try solving that unsolved question one more time during upsolving, still no? now its your choice to look at the editorial or solve more... (I would look at the editorial because sometimes you just need some specific maths formula/observation/trick that you don't know. But not this time though, all you had to know how bubble sort works to solve A and for B you had to know how the most significant bit is larger than sum of all bits before than it for ex. how 2^4 is greater than 2^3 + 2^2 + 2^1 + 2^0, if you knew this, question B was cake walk...)

change ur dp then u will solve questions

just take your meds : one tourist stream every day ! starting with : https://www.youtube.com/watch?v=97tieEKfvBs

I don't understand the solution for problem D. This is my understanding so far :-

For example: if there is a starting point on 42 and our count of segments excluding this is 10 and the value of k is 3. then I found out the solution is to add

`ncr(10,k-1)`

.Now the count is 11 and if we again reach to another starting position on 45 so again we will add`ncr(11,k-1)`

.Now count is 12.So if I understood it correctly, then we will choose one out of k to be the current one and choose rest k-1 from the previous segments right?

If we fixed a starting point, we may pick any $$$k$$$ segments that contain it. But there must be

at least onesegment that start in this point (note that more than one one segment may start in the same point).Actually, I was talking something like this solution.

I tried this concept after the contest.

I understood your solution. It's mostly the same as in the tutorial, but it considers the segments that start in the same point in a shorter and nicer way.

How to solve C2 using segment tree?

I used an ad-hoc segment tree with 4 values for each range:

The value (max/even) of a node is the max from these values:

The rest of the values are obtained similarly. Updating the tree is the same as a regular segment tree.

Here is my code.

I am still a bit surprised to see the no. of submissions on the Problem D, Is it some sort of a standard algo or question? Because some were able to this in a matter of just few minutes, if it is then please do tell me

I don't know weather it's standard or not but many interval related questions have similar approach.

What is the approach?

My approach for D. Rescue Nibel : I will tell you the method i used to solve, i don't know weather its similar to tutorial's but mine one is easy.I will create a array and put inside

`L`

and`R + 1`

for all intervals. So array will have size =`2 * N`

. Then sort the array. We keep a variable`cnt`

which will tell the number of lamps which are currently ON. Initially`cnt = 0`

. Now we will iterate over all element of array (in chronological order). Let the current element be`x`

. Now`x`

will either be starting time or (ending time + 1) of some interval. If it is starting time and`cnt >= k - 1`

then we add`NCR(cnt, k - 1)`

to the answer. We take`k - 1`

because the`kth`

element will be the lamp whose starting time is`x`

and remaining`k - 1`

we take from our`cnt`

(lamps which are already in ON state). Then we increment our`cnt`

by 1. If x is (ending time + 1) of some lamp then we just decrement our`cnt`

. This is my code --->Can you please share the code for NCR(cnt, k, MOD)

I did follow the same approach but end up having a run time error which was certainly "Arithmetic Exception" while computing this Combination

It fails over 11th test case....could you please share some insights

My Submission

Please read this https://www.geeksforgeeks.org/compute-ncr-p-set-3-using-fermat-little-theorem/

Thank you for that bro, is your code working vese?

Nice Code man

For anyone looking for his submission.

Is D problem has to be solved in that way how to get that intution someone should have solved 1 question at least of that type I think

I agree. People did it quickly because I think the intuition was quick for someone who has solved similar stuff or questions based on such counting. I too thought it resembled something but couldn't put it into code :(

I think you should try ** Min Stations for trains ** problem on GFG.

https://www.geeksforgeeks.org/number-of-ways-to-choose-k-intersecting-line-segments-on-x-axis/ I found it on geeks for geeks after the contest.

Have you converted it yet or not?

I had a Java solution TLE on D which I fixed by just using a hashmap to cache the results of modular inverse :/

w/o cache: https://codeforces.com/contest/1420/submission/93688984

w/ cache: https://codeforces.com/contest/1420/submission/93691811

Solution for Problem C2

`Suddenly it turns out that a single request will change the state of no more than six elements`

Didn't get intuition for this statement! Someone Please elaborate

Only the neighbour elements affect local maximum and local minimum. So, if you swap $$$l$$$ and $$$r$$$, you will need to recalculate only $$$l$$$, $$$r$$$ and their neighbours (in the worst case, it will be $$$l-1$$$, $$$l$$$, $$$l+1$$$, $$$r-1$$$, $$$r$$$ and $$$r+1$$$, thus six elements).

Amazing explanation...

Awesome explanation mate

Whether an element is a local maximum (or minimum) or not solely depends on its relation to the neighbors, as the required condition for a local maximum is a_i > a_{i-1} and a_i > a_{i+1} (reverse signs for a minimum). Now when swapping elements at given positions l and r, this will affect the status of the elements at positions l-1, l, l+1, and r-1, r, r+1 (note that these triplets may partly overlap).

https://medium.com/@harryjobz/pok%C3%A9mon-army-3f4348d57143

can't we solve problem b using tries

Why cut a apple using sword?

Always try to think of simplest logic. Don't think too hard. Obviously there might be a solution using different logic also.

Yes, we can. https://codeforces.com/contest/1420/submission/93721816

Can you please explain your logic?

thanks

I am looking details description of solution D or a video tutorial

Isn't the solution of problem D detailed enough?

may be..but i can't understand this..

You can try looking at secondthread's youtube channel , I guess it may help.Youtube channel name is "SecondThread".

Also tourist explained it on his youtube channel.

This is the implementation. Hope it helps.

I've succesfully uphacked myself. Turns out I forgot to check if all ai are different and still passed systests :D

Never knew that we can hack our own answers!

Can anyone please explain why my code for Problem D got Accepted when I used fastI/O but was getting TLE without using fastI/O even after that fact that the question had just one testcase per testfile?

fast I/O is so powerful that it can even reduce your acceptance time to half. Even I was amazed when I first observed it, few days back.

It is because of the large input file, you have to read 6 * 10^5 numbers

Thanx a lot buddy!

Your welcome my friend.

I'm a bit new...please mind my silly question

But what is fast I/O anyways

I did get Runtime error while computing nCr

C1 was already on internet.Make this contest unratedhttps://tkramesh.wordpress.com/2009/10/08/maximum-alternating-sum-subsequence/C1 is a standard dp problem, you can't argue on that basis to make the contest unrated. It is difficult to make new problems and very easy to make new accounts.

I agree making a new problem is a difficult task but at least we shouldn't use the same language as has been used on other sources. Just googling "maximum alternating sum subsequence" gives you the solution (I googled after seeing this).

Can C1 be solved w/o dynamic programming i.e greedy?

See solution for C2.

yes you just need to select each local maxima and minima, and remove the last minima.

I did the similar thing, first calculated the local maxima then if difference of subsequent minima and maxima is greater then zero then add it to answer and got AC, But still I can't get the intuition of why it worked. Here is my solution. Can I get help with this.

Update-Understood after reading the editorial again :).

Yes,it can be solved using greedy

My C1 solution without DP 93696961

Is there a typo in the summation of $$$p(A)$$$ for E? Isn't it

Yes, this is a typo. Thanks for finding it out.

Segment tree solution for C2We assign 4 values to each node (corresponding to a segment of the array) in the segment tree, which are the maximum value obtained if: 1/ The sequence begins with a (+) sign (addition) and ends with a (+) sign. 2/ The sequence begins with a (+) sign and ends with a (-) sign (substraction). 3/ The sequence begins with a (-) sign and ends with a (+) sign. 4/ The sequence begins with a (-) sign and ends with a (-) sign. For each node, these values can be deduced from its two children. My submission for more details: 93687329

i think the time limit for D is really bad, i made this submission in the contest and i got a TLE after it ,i don't know why my code gets TLE is the problem with factor 2? https://codeforces.com/contest/1420/submission/93716363

Same happend with me bro see this, can you help why its happening in my code?

I really like this kind of editorial where hints are provided rather than directly displaying the solution approach completely. I wish more than more authors adopt this strategy. Also, the problem statements were quite nice. Thank you for the good round and helpful editorials.

You are welcome :)

Can A be solved with ordered_set. What is the problem here 93823197

One thing you can do is check if array is strictly decreasing, then answer will be NO in all other cases answer will be YES

thanks for giving hints before solutions, would expect the same for future contests

I heard that D was copied from gfg. I was surprised at number of submissions of D

I too first thought that only C1 was standard and hence had a lot of subs. After seeing a few solutions for D, I realized it was standard as well. Two pretty standard problems in a single contest is definitely a bit sad.

An observation free solution for C1 and C2:

First let's try to solve this problem using divide and conquer. On every divide stage, we need the following information for each halve:

For the state where $$$R - L = 0$$$,

In the conquer stage, we need to merge these properties. We can easily do this as follows:

Our final answer will be $$$max(1, 2)$$$ over the entire array. This divide and conquer can solve C1. The question is, how do we keep updating this?

Well, in this 'divide and conquer', the conquer part is only $$$O(1)$$$. Therefore, this is a decomposable search problem which can be handled fast by segment trees.

Therefore to AC C2 we can create a segment tree where each node in the segment tree stores the 4 properties mentioned above and the merge function performs the max operations as described above. After this, it's standard.

Time Complexity: $$$O(N + Q \cdot LogN)$$$

You can view my submission for clarity:

https://codeforces.com/contest/1420/submission/93674507

Note: There was a much easier solution using some problem specific observations, but it's always better to have a solution that works on a wider range of cases. I hope this helped :)

To make it cleaner change 2 and 3 to "Maximum sum subsequence of even size starting with a positive element" and "Maximum sum subsequence of even size starting with a negative element", this removes isolated 1L 1R 2L 2R from the max, because the base case turns into 0 (empty subsequence has even size) instead of -10^16.

Yeah GG

Solution Video :

Problem A : https://www.youtube.com/watch?v=hFTC6ED6opg

Problem B : https://www.youtube.com/watch?v=Zp0be0LmLs8

Problem C : https://www.youtube.com/watch?v=KD4DN5KN74U

I liked the fact that hints are provided before the full solution. Thank you so much!

What is event method mentioned in D's solution?

We intend to keep track of the number of lamps which are switched ON at a particular instance of time,let's call that variable x. Now consider turning ON and turning OFF of each lamps as seperate events.It's intuitive that the numbers of lamps switched ON (variable x) only changes at the time of an event(switching ON or switching OFF of some lamp). Hence we sort all the events in non-decreasing order of their occurence and process them one by one. (Note that for some time T if there are multiple events occuring ,we place the switching ON events before the switching OFF events because the question mentions that lamps are switched ON from li to ri inclusive).

As we process the events 1by1, if we encounter a switching ON event, x is incremented, otherwise x is decremented.(quite intuitive). Whenever there is a switching on event and x>=k-1 , there are X choose K-1 ways of selecting k-1 lamps ,which cobmined with the current lamp being switched on gives us a new solution of k lamps.(My Submission)

If you are new to this technique, https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/ is a good introductory problem.

Thanks for your explanation. I had this thought first but hesitated in doing it.

Thank you for the explanation. For anyone who did not get it, an alternate explanation could be that we just have to chronologically sort all that happens and iterate over it while maintaining a counter of the number of bulbs still switched on. Just keep in mind to switch off a bulb after switching on all the bulbs at that instant.

nice editorial

I found an AC submission to problem B in my room:

https://codeforces.com/contest/1420/submission/93659129

It has O (n^2) complexity but runs surprisingly fast due to the use of intel vectorization.

Is this possible on AMD processors?

AMD processors have the same instruction set as Intel and support vectorization, so I think it's possible.

Does this mean that we can just pass simple n2 loops like these with this vectorization technique?

Sometimes it helps to fit into time limits, but these cases are not so often. Vectorization improves speed only in constant time, so if I make $$$200'000$$$ instead of $$$100'000$$$, then the $$$O(n)$$$ solution will be two times slower, but vectorized $$$O(n^2)$$$ will become four times slower, because it's still $$$O(n^2)$$$. Additionally, not every solution is good to vectorize.

What is intel vectorization and why this O(n^2) solution passing??

In short, it allow the core perform multiple instructions simutanenously.

OMG!! I tried my luck with the exact same approach but got tle.....Can you plz explain what is Intel vectorization?

You need a new generation of intel cpu e.g. 9th or 10th gen. Older cpus do not support this feature.

So it means who has high processor laptop dont need to worry about time complexity??

No, having a better algorithm is always better.

Indeed

Vectorization is available for long time. According to Wiki, AVX2 is supported in Intel CPUs since 2013, and SSE is used for even longer period. Why do you think that only 9th or 10th generations are supported?

I guess so because this code runs on my computer in 6 seconds (intel xeon 6th gen).

1) What compiler are you using?

2) Did you see the generated assembly?

If your CPU doesn't support AVX2 instructions and the compiled binary has them, the program will simply crash.

I am using GCC 8.2 Windows, C++14. The compiler bypass all directives and generate the output exe as the same as normal

Then your compiler didn't produce such instructions. It doesn't mean that CPU is not capable of executing AVX2.

If you try to compile https://codeforces.com/contest/1420/submission/93659129 with

`-O2`

, everything should be optimized and AVX2 will be used.So does this mean that someone with 9th/10th gen processor can get AC easily by doing 10^10 operations in like 1 second?

It's not true for every program. Vectorization improves the speed much only in the specific parts, like short loops which iterate over the array. You cannot just write

`#pragma GCC target("avx,avx2")`

and make any program two times faster. But there are some problems on Codeforces where solutions in $$$O(n^2)$$$ with vectorization passed with $$$n \le 100'000$$$.Clean solution to C1 using maxima minima approach

CODEhttps://medium.com/@harryjobz/pok%C3%A9mon-army-3f4348d57143

Nicely written keep making these type of blogs for upcoming contests also

For C2, the answer can be written as $$$\sum_{i=0}^{n}{max(0, a_i-a_{i+1})}$$$, where, $$$a_0 = a_{n+1} = 0$$$. Viewed this way, updates become very easy.

Actually , problem E has a solution in only $$$O(N^4)$$$ with simple convex hull trick . You can check my solution here .

Fantastic!

Can anyone explain to me the problem b's code? why j from 29 to 0?

It is because 1<= Ai <=10^9. So Ai can have maximum length of 29 in binary form.

ok thx!

For 1420C2 - Армия покемонов (сложная версия), instead of storing the local maxima/minima, we actually only need to store the current value of each element.

Why?

Because the best answer we can get can also be represented in

If we add an extra $$$0$$$ to the end of the array.

So for each query, we need to check at most 4 pairs: $$$(l-1,l)$$$, $$$(l,l+1)$$$, $$$(r-1,r)$$$, $$$(r,r+1)$$$. Note that there might be duplicates, so we need to use a set to deduplicate.

If the original pair is counted in the current sum, then we subtract it from the sum.

Then we do the swap and check the pairs again. If the new pair should be counted, we just add it to the sum.

I think this solution is clearer than the official one.

AC submission: 93743846

i am getting wrong answer for test case 44 in problem D. please help me out. i have done the same thing as mentioned in editorial most probably. submission : 93742154

Please help lucifer1004

This solution is really nice :) Do you have an AC submission?

I have added my submission.

I think it should be $$$\sum max(0, a_{i+1} - a_{i})$$$, $$$i = 0$$$ to $$$n$$$, $$$a_0 = 0$$$ and $$$a_{n+1} = 0$$$

The two forms are equivalent.

Note that I only add one $$$0$$$ at the end, while you add $$$0$$$ at both front and end.

i am getting wrong answer for test case 44 in problem D. please help me out. i have done the same thing as mentioned in editorial most probably. submission : 93742154

I really like this editorial providing hints not only solutions.

Can someone help me to find a corner case for my solution to Problem A.My logic is similar to the editorials.I tried creating a generator for the problem but I am still not able to find the test case on which the solution fails.Here the link to the solution 93669466 .

Actually DP solution with $$$O(n + q\sqrt{n})$$$ is also conceivable for C2 although because of hard constraints it gets a TLE. My approach, drawing inspiration from Mo's algorithm, was basically to split the pokemons into $$$\sqrt{n}$$$ segments of size $$$\sqrt{n}$$$ each. For each segment we can calculate following 4 things in $$$O(\sqrt{n})$$$ time (using the approach in C1). 1. Max +- sequence with even number of terms. 2. Max -+ sequence with even number of terms. 3. Max +- sequence with odd number of terms 4. Max -+ sequence with odd number of terms.

Finally we can run the dp on these $$$\sqrt{n}$$$ segments to get the answer in $$$O(\sqrt{n})$$$ time. Now, for every query just swap the pokemons and then recompute the (atmost) 2 segments in which the swapped pokemon lie and finally recompute the DP. For each query this can be done in $$$O(\sqrt{n})$$$ time.

My solution, TLE ofcourse - 93717594

Can someone Please explain how to do c2 with segment trees?

https://codeforces.com/blog/entry/82978?#comment-701497

Read the comments above before posting yours.

Why is my code getting runtime error on test 5 of problem c1. I have applied DP using 2d array where dp[i][j] tells answer when i elements are considered with j elements included in subsequence. https://codeforces.com/contest/1420/submission/93757697

I will be obliged if someone helps.

It can happen that $$$n = 3\cdot10^5$$$ in this task. And $$$3\cdot10^5\times3\cdot10^5$$$ is too large to fit into memory on stack, so the program crashes.

Can you also look at my code and tell me why i am getting WA on Problem A? I tried generating different test cases and testing but i am not able to find any test case where my solution fails.Link to my submission. 93762133.

When will ratings update?

Whats the reason behind the delay?

For C2, we can use

setto avoid categorical discussions.Can anyone tell me about the "event metho" which author is referring in solution of D? "It should be noted that p(x) and s(x) can be easily supported using the event method. Then, the total runtime will be O(nlogn)."

The idea is as follows. You have segments $$$[l_i; r_i]$$$ and want to calculate (for example) the number of segments that contain specified points $$$x_i$$$. To do this, you create an array of events:

Then, sort such events by time and process them in sorted order. Now it's easy to keep track of number of open segments in the specified points $$$x_i$$$.

I still don't understand the logic behind A Cube Sorting

`It is not difficult to see that the answer «NO» in this task is possible when and only when all ai are different and sorted in descending order.`

How can one derive such logic

PS — newbie here, want to learn :D

If you know something about

bubble sorting, you can think of theworsttime complexity of bubble sorting ($$$\frac{n-1 \cdot n}{2}$$$) and its reasonsYet to learn , thanks for info

In 1420B- Rock and lever can you explain what this part of the code is doing?

for (int j=29; j>=0; j--) { int64_t cnt=0; for (int i=0; i<n; i++) { if (a[i]>=(1<<j)&&a[i]<(1<<(j+1))) { cnt++; } } ans+=cnt*(cnt-1)/2; }

PS-Newbie Here

`if (a[i]>=(1<<j)&&a[i]<(1<<(j+1))) { cnt++; }`

stores the no of ( numbers having their rightmost set bit e.g: 4(binary representation : 001) ,in 4 the rightmost set bit is at index 2(0 indexed) ) .

`cnt*(cnt-1)/2`

part counts the nos satisfying the condition mention in the question for that count.Is there anyone else who is reading the name of this editorial's author as jeopardy?? xD

Why so many downvotes??? I didn't said that he is really in a jeopardy ¯_(ツ)_/¯

Hello everyone !! I hope you are having a good day!

i tried to make editorial for this round :- https://www.youtube.com/watch?v=uc6mN7BZVbI&list=PLrT256hfFv5WH3U33DuKUzL9fYnVsTGAj

problem solved. -> A , B , C1 , C2 , D

language of communication -> Hindi

programming language -> C++

I have tried to solve A by counting inversions. Can someone please tell why it is giving wrong answer. submission

in problem c2 let y be the total number of local maximum and minimum we have now, can we change the parity of the y with an update(swapping two element)?

Can someone explain the dp which we have done in ques E. Thanks

Can anyone help me with the problem D. I got WA in test 11. Here is my code:93779028

If I am not wrong you have compressed the values but you cannot compress the values in this question. You have to keep them as it is.

Can you explain why I cannot compress the values? I think the values are not important in this problem.

For example, two segments [1,4] and [2,6] after being compressed will become [1,3] and [2,4], which will not affect the result.

I liked A question it was a good implementation of bubble sort if you know it's worst case.

Here are video solutions for all problems, including a description of the weird segtree sol for C2

Very nice Editorial for problem E. Thanks :). Has anyone solved it using flows?

problem D is a nice educational problem thanks :)

Why is my code for B failing on 2nd pretest? I have stored the count of occurrences of each MSBs in a map and then have iterated over it to calculate the final count. Link to submission: https://codeforces.com/contest/1420/submission/93796185

Because when you are adding m(m-1)/2s, m can be up to 10^6, so if you set m as an int, it can overflow.

I today constucted a easy way to do the C2 problem or C1 problem. The ans is essentially the half of sum of absolute value of adjacent indices. (To work it, we have to add zero at start and end of the array). Now the update is really easy, we have to just remove the old absolute values and add the new ones. This can also handle updates like changing the strength of a indice. See the Ac code for implementation details- AC code

Can someone spot why I am getting WA on test 11 in Problem D. Here is my submission. 93837255

Lol, Missed the intended solution on problem A Did it using BIT .

I like this step by step style of the editorial. Thanks.

In the tutorial of problem E, should $$$z_i$$$ be $$$\sum^i_{j=1}{f_j}$$$? And could you please explain why it takes $$$|z_i-(s+h)|$$$ steps from $$$dp_i$$$ to $$$dp_{i+1}$$$?

Yes, there is a typo in the editorial.

Remember the reasoning above on how many steps it takes to transform the array $$$a$$$ into $$$b$$$. It's $$$\sum\limits_{i=1}^n \left|z_i - \sum\limits_{j=1}^n b_j\right|$$$, as shown above. In our DP, we know the array $$$a$$$ and build an optimal array $$$b$$$ step by step. After deciding that the value of the $$$i$$$-th element of the array $$$b$$$ will be $$$h$$$, we say that $$$\sum\limits_{j=1}^i b_j = s + h$$$. So, we add $$$\left|z_i - \sum\limits_{j=1}^i b_j\right| = \left|z_i - (s + h)\right|$$$ to the number of steps.

Is it now clear for you?

Yes, thanks. I didn't realize $$$dp_i$$$ starts from 0 so I mistook $$$h$$$ as $$$b_{i+1}$$$.

I think there is some inconsistency in the editorial text. $$$s + h$$$ should be of the same "size" as $$$z_i$$$, so there I would rather write $$$z_{i+1}$$$.

Can someone please tell me why I am not getting TLE on my solution to problem E?

It seems like magic. I really don't understand how a not very well optimized code like this is working.

Here is the solution link: 93898124.

Isn't it just $$$O(n^5)$$$? You have very straightforward loops, so it should be pretty fast. Switching to plain arrays might speed it up, but otherwise this looks like an intended solution.

Yes, but $$$80^5 > 32 \times 10^8$$$ and therefore, should not work, unless it is optimized heavily.

There is a small constant in front, rep(i,1,cnt+1) rep(j,i,n+1) is $$$n^2/2$$$, rep(p,0,j) further gives $$$n^3/3$$$. $$$10^8$$$ is quite okay, it is also very simple operations inside the loops.

Can anyone help me with the reason for this solution getting TLE? Problem c2 https://codeforces.com/contest/1420/submission/93901635

Use '\n' instead of endl and use fast I/O.

In editorial of 1420C1 - Армия покемонов (простая версия) and 1420C2 - Армия покемонов (сложная версия).

The outputs of the editorial codes themselves do not match for the same input test cases. For example,

Input1

4 0

5 2 2 5

Output(C1 Editorial Code)8

Output(C2 Editorial Code)10

I know it's a bit late, but the editorial remains as is. So, this should be corrected.

Is the input correct? The numbers in the input must be distinct, according to the statement.

Oh, I'm really sorry for that. Thanks for correcting me.

Can anybody explain how this formula is deduced in solution of problem E?

$$$p(A) = \sum_{1 \le i < j \le k} f_i\cdot f_j = \frac 12 \left( \sum_{1 \le i, j \le k} f_i\cdot f_j - \sum_{i=1}^k f_i^2 \right) = \frac 12 \left( \left(\sum_{i=1}^k f_i \right)^2 - \sum_{i=1}^k f_i^2 \right)$$$

We can get this equation in an alternative way:

$$$\displaystyle\left(\sum\limits_{1 \le i \le k} f_i\right)^2 = \sum\limits_{1 \le i \le k,\ 1 \le j \le k} f_i f_j = \sum\limits_{1 \le i \le k,\ 1 \le j \le k,\ i < j} f_i f_j + \sum\limits_{1 \le i \le k,\ 1 \le j \le k,\ i > j} f_i f_j + \sum\limits_{1 \le i \le k,\ 1 \le j \le k,\ i = j} f_i f_j = $$$

$$$\displaystyle = 2\sum\limits_{1 \le i < j \le k} f_if_j + \sum\limits_{i=1}^k f_i^2 \implies 2\sum\limits_{1 \le i < j \le k} f_if_j = \left(\sum\limits_{1 \le i \le k} f_i\right)^2 - \sum\limits_{i=1}^k f_i^2$$$.

In simple words, we take $$$\left(\sum\limits_{1 \le i \le k} f_k\right)^2$$$, which is a sum of pairwise products. Split these pairwise products onto three parts: where $$$i < j$$$, where $$$i > j$$$ and where $$$i = j$$$. The first two parts are equal to $$$\sum\limits_{1 \le i < j \le k} f_if_j$$$, and the last part is a sum of squares. From this we get that $$$2\sum\limits_{1 \le i < j \le k} f_if_j = \left(\sum\limits_{1 \le i \le k} f_k\right)^2 - \sum\limits_{i=1}^k f_i^2$$$, therefore the original formula is also true.

I did not get this part: "$$$\left(\sum\limits_{1 \le i \le k} f_i\right)^2$$$ = sum of pairwise products". Can you explain how?

Okay, do you agree that

$$$(f_1 + f_2 + f_3)\cdot(f_1 + f_2 + f_3) = f_1(f_1 + f_2 + f_3) + f_2(f_1 + f_2 + f_3) + f_3(f_1 + f_2 + f_3) =$$$

$$$= f_1f_1 + f_1f_2 + f_1f_3 + f_2f_1 + f_2f_2 + f_2f_3 + f_3f_1 + f_3f_2 + f_3f_3$$$?

(So, we got that $$$(f_1 + f_2 + f_3)^2$$$ is a sum of pairwise products of $$$f_1$$$, $$$f_2$$$ and $$$f_3$$$.

You can do this for arbitrary number of elements in the same manner.

Yeah got it. Thanks.

I have an alternative DP solution to problem E. Observe that the answer is at most C(# zero , 2), in stead of counting the good pairs, I count the bad pairs. (The number of bad pairs is the sum of C(len[i] , 2) for each consecutive 0s with length len[i])

Firstly, I considered interval DP, however, we need also keep track with the number of orders, so we have a state at least DP[l <= 80][r <= 80][k <= 80 * 79 / 2], when merging interval, the time complexity is at least O(N^6), so this doesn't seem like a good approach. Then, I consider a left to right solution, let DP[i][j][k][l] = the minimal bad pairs for the first making length of i sequence such that, we have used j orders, and have a length k full of consecutive 0s suffix, and have used l ones. For transition, DP[i][j][k][l] -> DP[i + 1][j][k + 1][l] + k if we put 0 on the (i + 1) th position. DP[i][j][k][l] -> DP[i + 1][abs(pos[l + 1] — (i + 1))][0][l + 1]. where pos[i] is ith one's position in the initial sequence.

Time complexity O(N^5 / 8) Runtime is some thing like O(80 * 80 * 80 * 79 / 2 * 40 * 40) which should be ok for 2 seconds.

My code: https://codeforces.com/contest/1420/submission/95068002

thank you very much for again add the hints option in the editorial.Well Done, good Job

I'm using segment tree approach for C2, but I'm getting TLE. I think time complexity should be O(qlogn). Any help would be appreciated :)

Link to my code: https://codeforces.com/contest/1420/submission/95420456

I need help in debugging Div2 D. I'm getting runtime error on testcase 11.

Link to my code: https://codeforces.com/contest/1420/submission/95433102

can anybody please help me why i get tle in problem c1. i used a top down approach to do that.here it is