Hello, everyone! It was a delight for us to have you participate in our contest. We hope you enjoyed the problems! Here, we present to you the solutions of the problems. I have also prepared some memes for you to enjoy — disclaimer: not all of them were created by me.

Tutorial is loading...

Author of this problem was Ashishgup.

**Relevant Meme**

**Code for A**

```
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
const int N = 2e5 + 5;
int n, x;
int a[N], f[2];
int32_t main()
{
IOS;
int t;
cin >> t;
while(t--)
{
f[0] = f[1] = 0;
cin >> n >> x;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
f[a[i] % 2]++;
}
bool flag = 0;
for(int i = 1; i <= f[1] && i <= x; i += 2) //Fix no of odd
{
int have = f[0], need = x - i;
if(need <= f[0])
flag = 1;
}
if(flag)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
```

Tutorial is loading...

Author of this problem was Ashishgup.

**Relevant Meme**

**Code for B**

```
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
const int N = 1e5 + 5;
int32_t main()
{
IOS;
int t;
cin >> t;
while(t--)
{
string s;
cin >> s;
int suf0 = 0, suf1 = 0;
for(auto &it:s)
{
suf0 += (it == '0');
suf1 += (it == '1');
}
int ans = min(suf0, suf1); //Make whole string 0/1
int pref0 = 0, pref1 = 0;
for(auto &it:s)
{
pref0 += (it == '0'), suf0 -= (it == '0');
pref1 += (it == '1'), suf1 -= (it == '1');
//Cost of making string 0*1*
ans = min(ans, pref1 + suf0);
//Cost of making string 1*0*
ans = min(ans, pref0 + suf1);
}
cout << ans << endl;
}
return 0;
}
```

Tutorial is loading...

Author of this problem was TheOneYouWant.

**Relevant Meme**

**Code for C**

```
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
const int N = 2e5 + 5;
int n, x;
int deg[N];
vector<int> g[N];
int32_t main()
{
IOS;
int t;
cin >> t;
while(t--)
{
memset(deg, 0, sizeof(deg));
cin >> n >> x;
for(int i = 1; i <= n - 1; i++)
{
int u, v;
cin >> u >> v;
deg[u]++, deg[v]++;
}
if(deg[x] <= 1)
cout << "Ayush" << endl;
else
{
if(n % 2)
cout << "Ashish" << endl;
else
cout << "Ayush" << endl;
}
}
return 0;
}
```

Tutorial is loading...

Author of this problem was FastestFinger.

**Relevant Meme**

**Code for D**

```
#include<bits/stdc++.h>
using namespace std;
#define vint vector<int>
int interact(vint S){
cout << "? " << S.size() << ' ';
for(int i : S)
cout << i << ' ';
cout << endl;
int x;
cin >> x;
return x;
}
vint get_complement(vint v, int n){
vint ask, occur(n + 1);
for(int i : v)
occur[i] = 1;
for(int i = 1; i <= n; i++)
if(!occur[i])
ask.push_back(i);
return ask;
}
int main(){
int tc;
cin >> tc;
while(tc--){
int n, k;
cin >> n >> k;
vector<vint> S(k);
vint ans(k);
for(int i = 0; i < k; i++){
int c;
cin >> c;
S[i].resize(c);
for(int j = 0; j < c; j++)
cin >> S[i][j];
}
vint ask;
for(int i = 1; i <= n; i++)
ask.push_back(i);
int max_element = interact(ask);
//find subset with max element
int st = 0, en = k - 1;
while(st < en){
int mid = (st + en) / 2;
ask.clear();
for(int i = 0; i <= mid; i++)
for(int j : S[i])
ask.push_back(j);
int x = interact(ask);
if(x == max_element)
en = mid;
else st = mid + 1;
}
ask = get_complement(S[st], n);
for(int i = 0; i < k; i++)
if(i == st)
ans[i] = interact(ask);
else ans[i] = max_element;
cout << "! ";
for(int i : ans)
cout << i << ' ';
cout << endl;
string correct;
cin >> correct;
}
}
```

Tutorial is loading...

Author of this problem was Ashishgup.

**Relevant Meme**

**Code for E**

```
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
const int N = 2e5 + 5;
int n, cost = 0;
int arr[N], b[N], c[N];
vector<int> g[N];
pair<int, int> dfs(int u, int par, int mn)
{
pair<int, int> a = {0, 0};
if(b[u] != c[u])
{
if(b[u])
a.first++;
else
a.second++;
}
for(auto &it:g[u])
{
if(it == par)
continue;
pair<int, int> p = dfs(it, u, min(mn, arr[u]));
a.first += p.first;
a.second += p.second;
}
if(arr[u] < mn)
{
int take = min(a.first, a.second);
cost += 2 * take * arr[u];
a.first -= take;
a.second -= take;
}
return a;
}
int32_t main()
{
IOS;
cin >> n;
for(int i = 1; i <= n; i++)
cin >> arr[i] >> b[i] >> c[i];
for(int i = 1; i <= n - 1; i++)
{
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
pair<int, int> ans = dfs(1, 0, 2e9);
if(ans.first || ans.second)
cout << -1;
else
cout << cost;
return 0;
}
```

Tutorial is loading...

Author of this problem was FastestFinger.

**Relevant Meme**

**Code for F**

```
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
const int N = 2005;
int n;
string s, t;
int suf[26][N], suf2[26][N];
int cache[N][N];
int dp(int i, int j)
{
if(j == 0)
return 0;
int &ans = cache[i][j];
if(ans != -1)
return ans;
ans = 2e9;
if(i > 0)
{
ans = 1 + dp(i - 1, j);
if(s[i - 1] == t[j - 1])
ans = min(ans, dp(i - 1, j - 1));
}
int ch = t[j - 1] - 'a';
if(suf[ch][i + 1] - suf2[ch][j + 1] > 0)
ans = min(ans, dp(i, j - 1));
return ans;
}
int32_t main()
{
IOS;
int tc;
cin >> tc;
while(tc--)
{
cin >> n >> s >> t;
for(int i = 0; i <= n; i++)
for(int j = 0; j <= n; j++)
cache[i][j] = -1;
for(int i = 0; i <= 25; i++)
for(int j = 0; j <= n + 1; j++)
suf[i][j] = suf2[i][j] = 0;
for(int i = n; i >= 1; i--)
{
for(int j = 0; j < 26; j++)
{
suf[j][i] = suf[j][i + 1];
suf2[j][i] = suf2[j][i + 1];
}
suf[s[i - 1] - 'a'][i]++;
suf2[t[i - 1] - 'a'][i]++;
}
int ans = dp(n, n);
if(ans > 1e9)
ans = -1;
cout << ans << endl;
}
return 0;
}
```

Auto comment: topic has been updated by TheOneYouWant (previous revision, new revision, compare).like D

I have another idea: because $$$ 1000 <2 ^ {10} $$$, we can perform the $$$ log_2 {k} $$$ query, and the $$$ i $$$ query the union of the sets which binary expression of the set number's $$$i-th$$$ bit equals to $$$1$$$ in the $$$ i $$$ th query. This can also find the position of the maximum value :-)

Doesn't it take $$$2\lceil\log_2k\rceil$$$ queries?I think you may need to query twice for each bit?

What you said is my initial idea, but it is not really necessary. In fact, this algorithm can pass this question! Maybe it’s because I’m a foreigner, and the English expressions I use are not good enough. You can look at my code and try to understand my method. https://codeforces.com/contest/1363/submission/82139983

Now I think I've understood it.Thank you so much.And,orz :-)

What if there are multiple positions with maximum value? Consider: N = 5 and Arr = {10, 10, 10, 10, 10} For bit position 0 (index = 0, 2, 4): Max = 10 For bit position 1 (index = 1, 3): Max = 10 For bit position 2 (index = 4): Max = 10 According to the queries, the index with max value is (111) in binary representation which is 7 and it is out of bound. Correct me if I am wrong.

In fact, the maximum value does exceed the range, but this does not affect the correctness of the algorithm! I did not directly access the position of the maximum value, I just made a judgment on the index of 1~n to determine whether it is equal to the position of the maximum value. You can look at my code and try to understand my method. Sorry for my poor English. https://codeforces.com/contest/1363/submission/82139983

Video Tutorial for C

1 8 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8

For this test case in C question, the answer should be Ashish but according to the editorial it is Ayush. Please correct me if I am making a mistake. Thanks in advance

no it is Ayush.Ayush will start removing leaf node and Ashish will be the last person to remove third last leaf node after that only two leaf nodes(x and some node v) remain from which Ayush can remove x and he wins.

you beat me by one minute ;)

Actually Ayush is true, you can see that we will remove node 4,5,6,7,8 in sequence and then it is just like pretest 1, but this time it is Ashish's turn not Ayush's.

That really wonders me how you think in that much easier way.

I guess experience is helpful

you're doing a nice job.

but what about "video tutorial for D" for the next contest? ;)

Never imagined C could be easier than A.

:(

Never imagined B and C could both be easier than A.

True bro, I wasted a lot of time in A(almost 45 minutes) rather than going for B or C but still anyhow managed to solve all of the three problems 3 minutes before the contest ended.

what's the logic behind your B submission??

exactly same as the editorialist's concept but if you have seen my code, I used a minimalFilps function directly from geeksforgeeks to get the count of minimum number of flips required to convert the array such that all 1's appear on left side and all 0's appear on right side. Here is the link to that function. Feel free to ask me if anything regarding my approach is not clear to you. Thanks for your time to have a look on my solution.

thanks!!

sushant23y what's the logic behind your B submission??

for every index calculate the cost of making every bit to left of this index to 1 and to right of this to 0. Take the min of these.

Then do the same again but for every index calculate the cost of making every bit to left of this index to

0and to right of this to1. Take the min of these.Check this answer https://codeforces.com/contest/1363/submission/82186217

Nice problemset, like it. But shitty D statement has spoiled an impression a bit :(

fast editorial

FastestFinger ==> FastestEditorial

Agreed, fast editorials, good problems, nice memes, strong pretests. (At least for me lol) Great contest!

I am having trouble deciding what sucks more — this contest or your sense of humor.

I think your comment. XD

Relevant Meme for Problem D is too close to heart <3

i'm in love with those pictures too :ddd

Adding memes to editorial is becoming a trend

Missed n==1 case for C. FML -_-

same bro

Thanks for such a good contest !

How is N^2 passing in B, even Reds have written N^2 to solve fast. How they knew it's gonna pass.

by looking at the constraints

N^2 is 10^8 iterations

10^8 should pass if you use fast I/O

Because scanning memory byte-by-byte is extremely fast. Reds write brute forces if they pass because it takes less time to write.

this was a nice contest and editorial is also very much fast.

Problemset was nice.

Here is a simpler solution for Problem A :

let k denote the number odd values in the array.

Answer is "no" if one of the following satisfies :

1) k = 0

2) k = n and x is even

3) x = n and k is even

Why ? (Left to reader)

I had actually done the same

i have done the same .....and solution is accepted.... but question says that element should not be consecutive ... and in the solution we have not consider this

Question says that elements don't necessarily need to be consecutive but they can be consecutive.

The C meme is hilarious

How to solve E when digits aren't necessarily binary?

I accidentally tried to solve this harder variant during the contest because I didn't read that digits are binary (oops...)

In problem B, I think simple O(n^2) should pass as length of string is less than 1000. But gave TLE on simple approach. Correct me if I am going wrong.

My O(n^2) solution passed easily.

Here is my Solution

have done almost the same but got tlesolution

I tried to submit in C++17(64) and it ran in 436 ms. (I don't know the reason behind it.)

Submission link

Numbers of Test cases were 100 ! It would be 10^8 in total ! My Solution failed for O(N*N) approach then I opted for using a prefix sum array !

Thanks for clarification. I wasted my attempt due to this even after knowing the efficient method :(

your most welcome

This might be the silliest of my doubts...But I've read in comments people saying for O(N*N) it would be 10^8. How come it should be 10^8 when |s|<=1000 and |t|<=100...so in the worst case it should be (1000*100)^2 = 10^10. Please tell me what I'm thinking wrong?

For EACH test case, O(1000*1000). There are 100 testcases = 100 times O(1000*1000) = O(10^8)

O(N*N) for solving each test case.

T*N*N in the worst case, therefore, 10^8.

Got it thanks!!, and one more doubt pls...what is the expected upper bound on number of operations that can be successfully executed in 1 sec without TLE. Until today I thought it was 10^7.

The upper bound is indeed 10 ^7 to 10^8 operations under 1 second to my knowledge! Correct me if am wrong !

The upper bound is close to 10^9 operations in a second with fast I/O. You can verify by running a for loop of 10^9 operations in custom invocation. But if you have multiple operations in the for loop, I would suggest not running a loop of more than 2*10^8.

Thanks for the information!!.

Can someone please explain A's solution? Why does it work? I don't get it.

Umm I will attempt to explain ! For choosing out K elements who sum up to give an Odd Number ! So it is prerequisite that We calculate in handy about how many odd and even integers are there in this array , now if no odd number exists it is clear that sum will never be able to get odd ! Another case is when You Have K as odd and CountOfOdd greater than equal to K you can fit these odd numbers in K and get a result , (For eg if you take 1 3 and 5 and sum up it gives 9 so it should be remembered that Taking ODD count of Odd Numbers and summing up gives and Odd Number , Another case will be when You have Not sufficient odd numbers to complete you K in that scenario you can take 1,3,5.. of the odd numbers you have in your count and can opt for taking other even numbers ,There is a catch for N==K case ! it is explained well in Editorial I think

Video Editorials for A, B, C, D and E

Great explanations :)

question 1

`9 7 11 14 1 6 3 12 3 20 16`

how this is YES11 14 1 6 3 12 20 you can see sum is odd

take 11 14 1 6 3 12 20, the sum will be odd

You can take 11 14 1 6 3 20 16 which has odd sum 71

System tests to problem D might be weak, I hacked my own submission 82140938.

Feel lucky tonight :P.

Read this : comment by mike

piyush33patel, thanks for the infomation. I submitted to problem D only 2 minutes before the end. When waiting for pretest, I checked my code and found a bug. I thought it would certainly fail system test since it is easy to construct a test against that bug. It is ok for me if the rating change is not final.

Uphacking doesn't affect standings, so you will keep your rating.

Please, for the love of god, someone tell me what is wrong with the following answer to E: https://codeforces.com/contest/1363/submission/82145487 I really hope something is wrong so I won't feel I was python-robbed again.

You likely hit stack overflow. It's a shame an equivalent C++ solution passes just fine.

For Python you might be able to set a new stack limit. I'm not too sure if CodeForces allows this but you could do:

This may give an error but it's worth trying. (On a side note, a Java solution with dfs also works fine)

I did similar thing using JAVA and I am simply applying DFS here, https://codeforces.com/contest/1363/submission/82320024 , but its showing TLE on 9th test case. IT IS SO SAD CODEFORCES.

Use Fast IO if you are using JAVA, I am using JAVA for a long time and haven't faced a single issue of TLE if I use Fast IO, My solution :82417618

I ended up finding one solution, and creating one solution.

1) At first I searched for a while, and found "bootstrap recursion" that someone posted a while ago. Solution: https://codeforces.com/contest/1363/submission/82165464

2) I implemented an iterative dfs. That was challenging, because you need to deal with the return values for the "recursive" calls, and also maintain local variables. Unlike a simple dfs, you can't just push all your neighbors onto a stack, but you have to push one, finish with it, somehow get a return value, and then push the next. I kept a counter that shows how many of the node's children visited the node, and when the counter reached len(neighbors), I filled the return variable, and popped it from stack. Maybe it's trivial and this solution is simple, but I looked a while for solutions for this and did not find even one (only a reference to a pdf that didn't work, about this matter). Solution: https://codeforces.com/contest/1363/submission/82215100

That's sad when your 100 lined code was actually checking n%2

Who wants to help me with D? https://codeforces.com/contest/1363/submission/82145477 Looks like I'm writing or reading incorrectly (wrong answer Token "162" doesn't correspond to pattern "!|?" error) but I don't see the mistake.

It seems that when asking for the maximum of all indices not in the same subset as the index with the maximum value, you assume the input set was ordered, then use

`z`

to iterate through the indices to ignore. If the set containing the index which has the maximum value in the array is not ordered smallest to greatest, extra indices are printed in the query.Unbelievable stupid. Thank you!

Is it just me or someone else also got deceived by the constraints of Problem C with $$$N$$$ = $$$1000$$$

I spend a lot of time doing dfs or building $$$O(N^2)$$$ solution in the end to realise that except for the degree of $$$x$$$, even all other edges are useless :P

If anyone wants a detailed explanation on A https://www.youtube.com/watch?v=0_b4YKuIPeU

Press F for everyone who failed the systest in problem D

The meme of D is the truest thing I've seen lately. Nice contest!

Interesting tutorial i've ever seen. :)

...

I guess it meant that both of the guys wanted to remove it first(special node). To do so they will make each other to remove unwanted leaf nodes. So they will start from the farthest.

The problem C is very very interested.I was completely off track the solution.Feels like crying after seeing that the solution is such easy.

Where am I going wrong for question D:

error: Idleness limit exceeded

code logic: get maximum by querying for 1 to n ans will be maximum for all k except one slot. use binary search for finding the slot number in which maximum belongs query for found slot.

Code link:82134674

Note that not all of the indices need be in a subset. In one of the last loops you print all subsets except one, but since some index might not be in a subset, it could print less indices than indicated (the first number after

`?`

), then block waiting for input.Oh I didn't see that coming.

I thought every index is part of exactly 1 slot.

Thank you. It was my first interactive that I have solved on my own.

Anybody knows where can we find more problems like A? (Once in a while such A's tend to totally massacre the contest, if possible I would like to train on such kind of problems to save myself from such wreckage.)

There was a similar problem from Dreamoon's contest. Round#631 div 2-A

Does the author of problem himself selects the

relevant meme, if so FastestFinger you've won this round unanimously.I made/choose all of them. :) (Although FastestFinger helped with the editorial of F)

I just want to take a moment and say POOR MEME GAME -_-

I didn't understand E after we reset the cost of nodes (from the start of the greedy solution). Thanks in advance if somebody explains it.

Video Solution Of Problem C : Solution

Can anyone please help me in problem D.? I have the same idea as explained in this tutorial. I'm getting, "wrong output format Expected int32, but "-4260782116" found" in test case 7. My submission: https://codeforces.com/contest/1363/submission/82151133

Update:No need . I've got my answer from previous comments. Problem was. it is not always true that given set always contains all the indices.can u please tell me my mistake in problem D,it;s giving a weird error in test case 1 itself.

https://codeforces.com/submissions/Lord_Saga

When asking for

`mv`

, you don't specify how many indices you are going to provide.Got AC . I was worried that i might not get any reply but you made my day by helping me out.

Thanks sooo much :) <3

Btw how did you put "mv" in the special box? Do you use any software?

That's inline code — you can use it from the top bar of the editor (a script-like button) or by wrapping some text in `, like `mv`.

marko312 You are really a good man bro <3

I don't know you but I became a fan.

https://codeforces.com/contest/1363/submission/82151479 Can't get rid of Idleness limit exceeded on test 7 ... can someone help?

You don't ever initialize

`vis`

, so some garbage / data from a previous test case could affect something down the line.still the same story idleness limit... https://codeforces.com/contest/1363/submission/82161988 i am frustrated now... :(

What if the index with the maximum value is not in any of the subsets?

Thanks you so much... i can see my mistake now... thanks thanks...

![ ]

this is gonna be the most upvoted editorial ever!! XDXD and maybe this cmmnt will be most downvoted ever XD (typical cf community i fkng love it)

1 8 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8

For this test case in C question, the answer should be Ashish but according to the editorial it is Ayush. Please correct me if I am making a mistake. Thanks in advance

Posting the same qn again and again ain't gonna fetch you the answer. I hope you understand that. Be patient someone will eventually pick up your qn.lllll

Extremely sorry about that

Remember, node $$$x$$$ can be picked up when it's degree is $$$<2$$$.

The answer should be Ayush, indeed. Let's simulate it.

Ayush picks $$$8$$$.

Ashish picks $$$7$$$.

Ayush picks $$$6$$$.

Ashish picks $$$5$$$.

Ayush picks $$$4$$$.

Ashish picks $$$3$$$.

Now, Ayush can pick either $$$1$$$ or $$$2$$$. He chooses $$$1$$$, and wins.

Got it!Thanks a lot for the help!!

For problem d

Suppose the root node has two children is it possible to shuffle values of two children (do they both belong to the same subtree)

yes it is possible and it is problem E not D

For this problem B, I submitted a code1 and it gave Runtime error. Here I have used long long int as the data type for all suitable variables using a 'typedef long long int ll' declaration at top

Now I just changed all the data types to 'int' by changing it to 'typedef int ll' and everything worked finecode2In some other submission I changed the string declaration to char and again everything worked fine [code3](https://codeforces.com/contest/1363/submission/82147815)I am not really able to understand the failure of code1.Please help me out !!!** For this problem my friend too faced the same issue. ***

Failed code

Passed code — just changed long long int to int

Because of memory overflow

Please go through this link

Since (some of you) liked the memes, I decided to post two of the others I had prepared, but did not post lest the editorial look messy,

Relevant Meme, Problem CPlease be assured that is not how we actually felt but only for humour purposes :) Half the credit for this goes to aryanc403

Relevant Meme, Problem DThe second one <3

can u please tell me my mistake in problem D,it;s giving a weird error in test case 1 itself.

https://codeforces.com/submissions/Lord_Saga

hoping to get a reply.

One of the best contests in quite a long time and the sweetest statements, and fast editorial! Thanks so much!

can anyone please explain to me why this N^2 solution of the problem B is giving TLE on test case 4. My Code

try to use

`ss.clear()`

instead of creating a new vector everytime. check this 82160254Thanks for the reply but I found that even My code got accepted when I submitted it with GNU C++ 14 / GNU c++ 17 (64). but giving TLE with GNU C++ 17 although I don't know the reason

Can you please explain your N*N approach a bit.

Yeah sure, we have to observe that there are only limited strings (exactly 2*N) that can satisfy given conditions. A string should be such that first i characters are all one and rest are zeros or all first i characters are zeros and rest are ones i varies from 0 to n(size of given string). Then I simply calculated difference of each of the 2*N strings with given string and took the minimum answer

It would be propably much faster if you actually do not create the strings in the first loop, but simply act like you would have done in the second loop.

It is fairly simple to find if ss[i][j] is 1 or 0.

Yea I know that

Can some one explain to me why in this test case "Ayush" wins not "Ashish" 1363C - Game On Leaves

Ayush picks node $$$4$$$. Now, it is like the first test case, only the roles are reversed. No matter what Ashish picks, he will make node $$$2$$$ pickable for Ayush.

UPD: I read your question wrong.

why not pick 3 first

Because they are playing optimally. Both of them would pick the most favorable one each move.

It is mentioned in the problem statement:

If he chooses 3 it will lead to 2 being the Leaf Node and in the next chance Ayush will choose it and win so playing optimally he wont choose 3 first

If Ayush takes node 4, Ashish is forced to take either 1 or 3, both leaving 2 as a leaf node.

why not Ayush take node 3 first

Remember, both play

optimally. Since taking node 3 would give Ashish the option to take node 2, Ayush won't do that, being able to guarantee a win by taking node 4 first.thanks i didn't read it

Coolest Editorial Ever!

Come on, i thought i would be the first problem setter who splits key idea from complete solution :(. Nice job TheOneYouWant.

what does

signify in E's Editorial code ?

In Problem D, can't we use binary search to find the index of the max element and then use that fact. Since k<=n, the no. of operations at its worst should be equal in both cases.

What I m getting wrong? Here's my submission: 82156330

Thanks in advance!!

What if the index with the maximum value is not in any of the subsets?

Thanks, got AC with that approach too. I completely forgot that the subsets are not exhaustive and this case may arise.

video Tutorial for A https://www.youtube.com/watch?v=BoO38O2Qnqg

Out of all possible errors how did I get memory limit exceeded for D ? :(( 82128649

Problem C is a harder (easier?) version of B. Binary Tree. The observations are almost identical in both problems.

can someone help me with the recursive dp or memoized approach for Problem B.

Ummmm ! Now that you have mentioned I suppose it can be done using recursion with some clever memoization where recursively create all the strings of the form 1111's followed by 0000's and strings of form 00000'ss followed by 1111's We will create all the strings and check for a minimum ans out of all such possibilities and to add some memoization for any string we can calculate number of mismatches upto some index and later use it for fast computation !

But Yes DP will be overdoing things a single prefix array will suffice to crack this problem !

Happy Coding :)

in c problem if the test case: n=6 x=2 1 2 1 6 2 3 2 4 2 5 then ashis will be winner but n is even . anyone help please

I don't think Ashish is the winner in this case ! in the first chance Ayush will go for 3,4,5 or 6 which are the leaf nodes and subsequently he is playing optimal so if you make any sort of choices from this state You will always Find Ayush having the last laugh!

Any clue about test case 37 of Problem D ?

Your code seems to fail for the same test case I generated in this comment.

Ok thanks :)

https://codeforces.com/contest/1363/submission/82161309 why fflush(stdout) is not working??

upd: fflush(stdout) will not work if you are using fast con,cout in c++

Is there any approach for C involving grundy numbers and/or nim sum? I tried really hard to find someone..

My idea is make the tree rooted from node x and calculate the amount of sons it has for each brach. Since for win the game I have to make the node x leaf, and for that need to eliminate all nodes of each branch first(all except one branch, I mean if there are k branchs, it is enough to eliminate k-1 of them) then the game is reduced to a modified nim game where the goal is reach the state {0 1} and for each turn the player can select one "heap" (amount of sons calculated previosly) and decrease it by 1.But I can't find a winning strategy for that game, please let me know if I am making some mistake..

Solved: I realized that if I consider each heap as a nim heap the grundy number of each one will be 0 if it's even and 1 otherwise (this is because I'm only allowed to take 1 element each turn and 0 is a losing state) then I find the nim sum of the k-1 heaps, if the grundy number of the remain heap is 1 my nim sum change, otherwise nothing happen. So it is enough to find the nim sum of all of them. The special cases are handled seperately. This is equivalent to the approach of the editorial, but using Spargue-Grundy theorem

solution

I loved the editorial.What an Explaination!Thank you so much FastestFinger Ashishgup TheOneYouWant. You guys won many hearts today!

Waiting for more Indian Rounds!

In Problem D, instead of binary searching the subsets, we can query[1..n] first to get the maximum, then binary search the index of the maximum by querying [1..mid] each time.

In this way, we can get the exact index of the maximum (when there are multiple, the first one).

Then we just check whether a subset contains this index. If so, we query its complement.

UPD : Got it!

Yes. Because $$$ S_i \cap S_j = \emptyset $$$, there's at most one subset which has index of first maximum element. Except this one, all position's password will be the maximum value. Then ask answer for this one with its complement.

I did exactly the same but i am getting Idleness limit exceeded. Can you help me? https://codeforces.com/contest/1363/submission/82288138

Your binary search is wrong. You are query [lo..mid] instead of [1..mid].

My bad. Querying [lo..mid] is OK.

Thanks for taking the time to see my code. The error was that ind's size was supposed to be n not k.

my logic for b was exactly the same don't know why test case 3 did't pass.

[Deleted]

Though I couldn't solve much I enjoyed it!

82161582

Can anyone tell me why this solution for Problem D is failing for testcase 37 ?

The basic idea behind the solution is that the variable

`lo`

is used to store the index of the maximum element; and`mx`

and`mn`

are the highest and the second highest elements of the array respectively.After the binary search, I use one query to check the subset

`lo+1,lo+2,....,n-1,n`

because this subarray may hold the second highest number (This is because in all the previous queries, the`mx`

variable would overshadow the the second highest number if it fell in the`lo+1,lo+2,....,n-1,n`

subarray.)Is the second highest element always the one which is used for the subset which contains the maximum index?

Here is a small failing test case:

I get it now. Thanks for your help!

UPD : Here is the link to the rectified solution : 82194067

Wow!!

what a nice contest!

thank you so much.

especially an interactive problem on my level after a long time was so good.

I enjoyed it.

Nice problems. I enjoyed a lot. Thanks.....

Can anyone explain how to solve F?

https://codeforces.com/blog/entry/52376

Check out the Problem — Shifts.

cant we do the same in O(n) , we pick the charcter everytime if we do not have it and insert it if we do have it. (just make a frequency count for that). Any counter example.

Can someone help me why 82180993 getting RTE on test 9?

My idea is to sort the nodes non-descending by its cost and try to shuffle as many nodes as you can from the lowest-cost node.

I use segment tree and euler tour tree. After every shuffling, I updates every shuffled nodes with lower bound on sets (Maybe this one causes RTE)

I know there are neater implementation using root-to-leaf minimum, I'm just curious why my code gets RTE. Thanks

EDIT: Found it! Segment tree size is not enough. set segtree size to 1,2 mil apparently gives ac, idk why it needs that much for this problem@hey i am just a beginner could u plz help me in editorial of B problem as iam unable to get .plz

I will try to explain it to you ! To make a string free of any sub sequences of '101' and '010' I think you must have deduced that much that the only possible string which will form an answer must of one of the following forms.

1) A series of 1111's 2) A series of 0000's 3) A series of 1111's followed by a series of 0000's 4) A series of 00000's followed by a series of 1111's

So The Editorial of B is trying out all Possible such strings and considering the answer as a string with minimum mismatch between the given string as input and string we are considering ! Now Trying out all strings can Give U TLE ! So Using a prefix sum array to store in handy the number of 111's you have till i'th index will help you calculate the ans !! I can help you with the code part if idea is clear to you

Thnx a lot...bro...thnx.....

Happy Coding :)

I'm having very rough times solving C. Since last 3 contests, I've found a D/E that I found easier than C. This time it was E, I could do it in about 20 minutes after contest.

Hey guys i am having some trouble debugging my solution to E.I have added a few comments to my code here. my approach involves using dfs and if a node has a cost smaller than all its ancestors, we use this weight and do all changes possible to the subtree(including the node) of this node. Any kind of help will be appreciated. Happy coding :).

Hello Codeforces!

Thanks for the great contest FastestFinger Ashishgup TheOneYouWant

I am facing problem in Question D.

My approach is almost the same

1) First I find the maximum among the whole array.

2) Then I keep lo = 1 & hi = n and do queries to find the index between [1, n] which has highest element in the array A.

3) Then I iterate over all the subsets in S to see if it contains the index having the highest element in A. If it contains such an index then I make a query on indexes not in that subset and print that. Else I print the maximum element.

I am getting the wrong answer on test 4.

My code can be seen here:- 82190773

TIA

After guessing the answer you are not reading the string

`"Correct" or "Incorrect"`

. Just fix that and your code is good to go!Oh! I completely missed that

Thanks a lot man for taking out your time.

Note that it fails on the first test set with multiple test cases. There was a notice after the sample:

Oh! I completely missed that

Thanks a lot man for taking out your time.

I have a solution for E which is similar to the idea in the editorial but it uses a small trick and without maintaining the parent and instead storing how many unbalanced cases are to be resolved by shuffling in sub-tree of a node. Code

For the case of impossibility if summation of bi != summation of ci, we print -1 otherwise we have a solution. We have a global variable ans which we print if it's possible to reshuffle values to get desired structure. So we maintain a global array 'unbalanced' which stores how many 1s in sub-tree of the node still require shuffling while maintaining a[node] <= a[par] for node != 1 (the root). So for any node let the initial unbalanced amount be c[node] — b[node]. We will see how this comes handy later. Now if we sum unbalanced[v] for all v in children of node with unbalanced[node] we get the number of 1s that cannot be shuffled within the sub-tree rooted at node. Even if it turns out to be negative it is fine as it will get balanced by some other nodes as summation bi = summation ci. Now unbalanced stores the number of 1s in sub-tree of v which cannot be resolved by any shuffles within the tree and the number of shuffles which can be made in the sub-tree is {summation abs(unbalanced[v]) | node is a parent of v + abs(c[node]-b[node]) } — {abs(unbalanced[u])}. We multiply this with a[node] and add it to the global answer variable, as the optimal cost for shuffling can only come from this because a[par] >= a[node] which I maintain by this, if(a[v] > a[node]) a[v] = a[node];

It might seem difficult to understand. A lot a of expressions in this comment would have cleared it even more. I hope someone reads this and finds it useful. :-)

Is that unrated?

No I saw a comment made by MikeMirzayanov where he mentioned that rating changes are happening for the time being and will be updated after a thorough Plagiarism Check !

have a look Comment

Another solution B: resultant string will be of form s1+s2,where s1="00.." and s2="11.." or s1="11.." and s2="00..".looking at constraints O(n*n) will work .so we can check all strings of these type to find minimum number of changes.

I love the way you guys made this editorial. The concept of

Key IdeaandDetailed Explanationwas really good .It dosen't work, why?

Because dfs is not a pure function. If you call dfs twice, it will add to cost twice and cost will be wrong.

Good contest. My ego made me stuck on A and still couldn't solve in 5 attempts.I found B and C easier.

can anybody explain how to solve problem E i am not getting it as i want to know how to things will work on tree can anybody show tree diagram??

Consider the following graph 4 1 2 2 3 3 4 then subtree of 1 is 2 3 4,subtree of 2 is 3 4 and subtree of 3 is 4 . then you are given some value of b and c . if value of b is 1 and value of c is 0 then you can shuffling between them ,and at the mean time you will consider the cost of the parent which cost is less. suppose you can shuffling node ( 2 , 4 ) or ( 3 , 4 ) .but the cost of 2 is 10 and 3 is 20 . so you will choose 2 as parent . and you will perform dfs and track down the minimum cost . To understand better you can watch this solution : https://codeforces.com/contest/1363/submission/82224132

In the editorial for D, why do we iterate from 0 to mid (inclusive) instead of st to mid (inclusive)?

Code:

I have something similar but mine is not passing.. . 82227750

The problem encountered in that submission is due to poor handling of multiple test cases — in all cases, the second test case should produce an error.

There is also a problem with the inverse querying.

Please，why I get “Memory limit exceeded” in probem D,82232793

One large problem I see is the case when

`lab`

is left as`-1`

— in that case, too many numbers get added to`ANS`

and likely corrupt the querying for the next test case. Since no error checking is done, that could leave some variables with an undefined value, possibly later causing a huge loop.I see.Thank you.

Please somebody help me out. I have done problem D using binary search as suggested in editorial but getting error: IDLENESS LIMIT EXCEEDED on test case 7. Link to my submission https://codeforces.com/contest/1363/submission/82238839 Thanks in advance :)

No need to put your brain on it. I got my silly mistake i was doing. Sorry for asking such silly questions :(

In Subsequence Hate , I got "Wrong answer on pretest 2".

My submission : 82118663

But when I checked the testcase, it said for

10111101000010100

the answer should be 7 flips

but I can make it good by using 4 flips only 1(1)11110(0)0000(0)0(0)00, which is valid

Correct me, if I'm wrong on understanding the problem statement.

Resolved: My mistake! Thanks dorijanlendvaj for correcting.

Your solution says that the answer is 7; the correct answer is 4.

The answer it expects is 4 and your code gives ans as 7 ! I have seen your code and I suppose you are tring to find first occurence of 1 and then making 0's after that as 1 and also doing the same thing for first occurence of 0' this logic will not work !! I suppose you should try to approach the problem with trying all the series possible cleverly and form an answer in O(N) time

Can anyone give a rigourous proof for the dp solution for f. What does the dp state define?

Can't understand what it means for s[1,i] = t[1,j].

The reason I'm doubting the solution is that the following version of the problem: where instead of right rotations, we swap the elements, is NP-hard. See this : https://stackoverflow.com/questions/18292202/finding-the-minimum-number-of-swaps-to-convert-one-string-to-another-where-the

Yes,I think it's a NP-hard problem, but I'm not sure they are same.Need some help...

Someone posted that problem F is actually same as this https://codeforces.com/gym/101438 problem, and the editorial of that contest provides a much better explanation in terms of LCS, which is not NP-Hard.

Thanks, that solution was more easy to understand.

I can't find the editorial of this contest,the page just include the statement of the problem, but I have seen the problem "shifts" is same as this problem.

https://codeforces.com/blog/entry/52376

Thank you, very nice.

A new era is arrived and that is EDITORIAL WITH MEMES....

https://codeforces.com/contest/1363/submission/82288453 can anyone tell me why i am getting memory limit exceeded in my code?? i have submitted 10 times not able to figure it out please help??

Your code produces a wrong answer on some test cases. However, since you don't check for the string being

`"Incorrect"`

, the code attempts to read more values, leaving some variables (especially importantly`k`

) in an undefined state.Can you guide me how to fix it?? It's my first interactive problem...

First, please do check for

`"Incorrect"`

— this should give you the correct verdict and allow you to better analyze what went wrong.For the underlying problem, I can provide a (hopefully) failing test case:

So in my while loop I should make a if condition if the input string is correct then I will continue loop and if it's incorrect I should return 0?? In this way it will work or different syntax I should prefer for this??

Yes,

`return 0;`

or`exit(0);`

should work fine for exiting if the string read in is`"Incorrect"`

.Ohk thanks for your time....

Can you also help me? https://codeforces.com/contest/1363/submission/82288138

Honestly, I spent about an hour looking at this code previously — it behaves just like mine and seems to work on the same principle, but I can't find anything that should be wrong. I even tried a few tests against it on my machine.

My next line of action would be to create a problem host (providing the problem / interaction), then generate (small) random test cases to see whether an error can be found to analyse what goes wrong.

I will do this. Thank you so much for your time and help

OK — I took yet another look at this, and I'm pretty sure I noticed the error at last:

`ind`

could be accessed with values up to $$$n$$$, but $$$k \leq n$$$, so this could go out of range, causing all sorts of problems.Silly mistake as always !! Thank you so much i was really struggling and couldn't find the error. much appreciated.

I am getting Idleness limit exceeded on problem D. Can somebody help me? https://codeforces.com/contest/1363/submission/82288138

Can someone explain the editorial solution of 1363F - Rotating Substrings in detail..

I'd like to hear another explanation too because I'm also confused about this solution

I have implemented same logic in problem D as explained in editorial still getting wrong answer. Query Function is returning a garbage value. Plz help anyone? Here is my submission id :- https://codeforces.com/contest/1363/submission/82306483

You're trying to query in the middle of printing the password.

Now I have removed query while printing password but still I am getting garbage value in query thats why it is printing garbage value in answer when i tried in custom input. Sir plz help, this is first time when I am doing a Interactive problem. https://codeforces.com/contest/1363/submission/82337085

You're getting a garbage value since the testing program closed its input, but the code is stuck in a loop trying to get more values. Note my other comment.

Sir , now I removed the infinite loop case but still it is giving wrong answer. Plz help sir https://codeforces.com/contest/1363/submission/82339279

Now, you query the maximum of the set that contains the maximum element in the array, using that value for the position where elements from that set should be ignored.

I have done this but still its giving me wrong answer :-( Please help sir. https://codeforces.com/contest/1363/submission/82363733

Interestingly enough, the first test is an edge case for your program — what happens when the greatest element is in the last set (so only the

`start = mid + 1;`

branch gets run)?Sir, now i took care of that condition also but now it is giving wrong answer on test case 14 https://codeforces.com/contest/1363/submission/82369145

The problem now is that you're making up to 11 queries to find the correct set, one to find the maximum value and another one to find the maximum outside the set which has the index corresponding to the largest value.

You need to get rid of a query somewhere, possibly changing your approach.

The second-to-last paragraph of the explanation mostly addresses this problem.

Sir, but in question maximum queries allowed are 12?

Yes, however your code might make up to 13 queries, since it could make up to 11 queries in the binary search.

Ohh, I got my solution accepted:-).Thank you very much for your time , without you it was not possible for me.

Also, the actual issue currently causing the first test to fail — your binary search gets stuck in an infinite loop if the greatest element is inside one of the subsets.

Sir , I am not able to figure out how binary search is oing in infinite loop as i am always updating start and end in each iteration , sir plz explain https://codeforces.com/contest/1363/submission/82337085

What would happen if

`start`

and`end`

were equal inside the loop (and the element with the maximum value is inside the set corresponding to`start`

/`end`

)?I am a newbie can you help me with code below? Codeforces Round 646 Div-2 1363A-Odd selection what is wrong in my code?

https://codeforces.com/contest/1363/submission/82093977

Also all suggestions will be welcome :)

Please, instead of pasting your code in the comment, provide a link to your submission — it reduces the size of the comment and makes the code more readable.

82093977

You have access to the test that failed, and it is quite well readable — you can step through your code logically to see where the fault occurs.

In particular, note this branch of the main logic:

An easy counter-example would be an array with two odd numbers and two even, asking for whether the sum can be an odd number when picking 3 elements.

Yes I got it

In Problem D, i am getting WA in case 16, but i cannot figure out why? My Approach : I first got the maximum value of full array, than by binary search find out the position of that maximum value in the array. Than just proceed the k subset. Can anybody look at my code and help me to figure out please, My Code

marko312 at first sorry for mentioning you, i saw you did reply to many comments, can you help me pls!

Since $$$1000 > 2^9$$$, you

willneed to make more than $$$9$$$ queries in your binary search for large enough inputs. It was mentioned in the editorial that the bound was tight.You can try the following test case:

In this case, your code will think that the second index in the array has the largest value.

Thanks, i miscalculated the iterations value, i count printing the answer as one of the query that is s why i took iteration = 9, now i just changed iteration = 10 and it got Accepted :D

How silly i was :(

damn!! the editorial is really good!!

Could someone please explain me problem E ? I missed something and I really don't get it and it angers me.

Why is last example impossible?

Just take node 1 and switch digits of nodes 1 and 2... Cost : 218.

Node 1 contains 0, needs 1.

Node 2 contains 0, needs 1.

If you swap the values they have, neither of them reaches its target value. Hence it is impossible.

Thanks, i didn't understand the word "shuffle" correctly.

Good follow up for beginners -In

`Problem A`

, count the`# of ways`

of choosing $$$x$$$ numbers so that the sum is odd.Solutionlet E = # of even numbers in array

# of valid ways = # of odd integers in range $$$[max(0,x-E), min(x, n-E)]$$$ inclusive.

What is the purpose of the variable mn in the editorial's solution for E?

I got it, never mind

Can someone please explain how the moves will carry out for this input -

1 5 5 4 5 4 2 3 5 4 1

I presumed -> Ayush takes 1, Ashish takes 2, Ayush takes 4, Ashish takes 5 and wins

That is correct. However, based on your solution, I think you thought that was the test that failed your code — the failing test was actually the next one:

Here, Ayush can win after Ashish's move, but your code output that Ashish'd win.

Thank you! Really

solution :- https://codeforces.com/contest/1363/submission/82384349 code for D, getting an absurd error if anyone could help?!

The diagnostics output gives quite a good warning:

Looking at the code, the reason is quite clear:

You likely want to

`resize`

the vector before assigning new values to it.Also, note that the vectors in

`s`

are never cleared.thanks for the reply, it worked!

can any one explain 1st problem?

This was my thinking in the contest:

Look at the array 'a' modulo 2. It will be 1s and 0s.

Count how many 1s there are — 'numOnes' and how many 0s there are — 'numZeros'. The minimum sum we can create with x elements is lb = max(0, x — numZeros), where we took as many 0s as possible. The maximum sum we can create is ub = min(x, numOnes), where we took as many 1s as possible. Since the entire array is 1s and zeros, we can also create any number in the range [lb, ub].

Now the sum of the x elements we pick can be odd if and only if the sum of their remainders modulo 2 is odd, that is, when there exists an odd number in the range [lb, ub]. Obviously this odd number will not exist if and only if the range consists of a single even number, that is, lb == ub && lb % 2 == 0.

My code: https://codeforces.com/contest/1363/submission/82065526

can someone help me on question D? I am getting "Idleness limit exceeded on test 7" though I used cout.flush(). Here is link to my submission : https://codeforces.com/contest/1363/submission/82422145

Have you tried going through the failing test case with your code? It prints too little numbers in the last query sometimes.

Note: the test cases there are in the hack format, so the second line of each case describes $$$A$$$.

Yeah, Later I realized my mistake, But it is still failing on test 74. But I could not see the full test description.

Link to my submission : https://codeforces.com/contest/1363/submission/82456592

In

`if(tot < n)`

,`maxm`

is set to the maximum of all values corresponding to indices not in a set. However, in the code that follows, you use it as if it was the maximum of all elements in the array.Thank you, I got it.

I came here for the memes

82879714 It said,"Wrong answer on test 2."

what is the problem? I don't understand. Please help me.

You have got some double cases here, then you output more than one answer. Maybe just a break is missing.

Please add the link of the editorial with the problems.

Problem F ( Rotating SubString )::Commented Code With Explanation101216700