Idea: fcspartakm

**Tutorial**

Tutorial is loading...

**Solution**

```
for i in range(int(input())):
n, x = map(int, input().split())
print(1 if n <= 2 else (n - 3) // x + 2)
```

Idea: BledDest

**Tutorial**

Tutorial is loading...

**Solution**

```
for i in range(int(input())):
n, m = map(int, input().split())
a = []
for i in range(n):
a.append([[int(x) for x in input().split()] for i in range(2)])
ok = False
for i in range(n):
ok |= a[i][0][1] == a[i][1][0]
ok &= m % 2 == 0
print("YES" if ok else "NO")
```

Idea: vovuh

**Tutorial**

Tutorial is loading...

**Solution**

```
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int ans = 1e9;
for (int x = 1; x * x <= n; ++x) {
ans = min(ans, x - 1 + ((n - x) + x - 1) / x);
}
cout << ans << endl;
}
return 0;
}
```

**Solution 2**

```
#include<bits/stdc++.h>
using namespace std;
const long double EPS = 1e-9;
long long f(long long x)
{
long long z = sqrtl(x);
long long ans = 1e18;
for(int i = -5; i <= 5; i++)
{
long long z2 = z - i;
if(z2 > x || z2 < 1)
continue;
ans = min(ans, z2 - 2 + (x + z2 - 1) / z2);
}
return ans;
}
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
long long x;
cin >> x;
cout << f(x) << endl;
}
}
```

Idea: BledDest

**Tutorial**

Tutorial is loading...

**Solution**

```
n = int(input())
a = [int(x) for x in input().split()]
d = set()
d.add(0)
cur = 0
ans = 0
for i in range(n):
cur += a[i]
if cur in d:
ans += 1
d = set()
d.add(0)
cur = a[i]
d.add(cur)
print(ans)
```

Idea: fcspartakm

**Tutorial**

Tutorial is loading...

**Solution**

```
#include <bits/stdc++.h>
#define sz(v) int(v.size())
#define all(v) v.begin(), v.end()
#define pb push_back
#define ft first
#define sc second
using namespace std;
int n;
vector<int> a, b;
inline void read() {
cin >> n;
a.resize(3);
b.resize(3);
for (int i = 0; i < 3; i++) cin >> a[i];
for (int i = 0; i < 3; i++) cin >> b[i];
}
inline void solve() {
int ans1 = INT_MAX;
vector<pair<int, int> > ord;
ord.pb({0, 0});
ord.pb({0, 2});
ord.pb({1, 1});
ord.pb({1, 0});
ord.pb({2, 2});
ord.pb({2, 1});
sort(all(ord));
do {
vector<int> a1 = a, b1 = b;
for (int i = 0; i < sz(ord); i++) {
int cnt = min(a1[ord[i].ft], b1[ord[i].sc]);
a1[ord[i].ft] -= cnt;
b1[ord[i].sc] -= cnt;
}
int cur = min(a1[0], b1[1]) + min(a1[1], b1[2]) + min(a1[2], b1[0]);
ans1 = min(ans1, cur);
} while(next_permutation(all(ord)));
int ans2 = min(a[0], b[1]) + min(a[1], b[2]) + min(a[2], b[0]);
cout << ans1 << ' ' << ans2 << endl;
}
int main () {
read();
solve();
}
```

1426F - Number of Subsequences

Idea: fcspartakm

**Tutorial**

Tutorial is loading...

**Solution**

```
#include <bits/stdc++.h>
using namespace std;
const int MOD = int(1e9) + 7;
const int N = 200043;
const int K = 4;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int n;
string s;
int dp[N][K][K];
char buf[N];
int pow3[N];
int main() {
scanf("%d", &n);
scanf("%s", buf);
s = buf;
int cntQ = 0;
for(auto c : s)
if(c == '?')
cntQ++;
pow3[0] = 1;
for(int i = 1; i < N; i++)
pow3[i] = mul(pow3[i - 1], 3);
dp[0][0][0] = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j <= 3; j++)
for(int k = 0; k <= 3; k++)
{
if(!dp[i][j][k]) continue;
dp[i + 1][j][k] = add(dp[i + 1][j][k], dp[i][j][k]);
if(j < 3 && (s[i] == '?' || s[i] - 'a' == j))
{
int nk = (s[i] == '?' ? k + 1 : k);
dp[i + 1][j + 1][nk] = add(dp[i + 1][j + 1][nk], dp[i][j][k]);
}
}
int ans = 0;
for(int i = 0; i <= 3; i++)
if(cntQ >= i)
ans = add(ans, mul(dp[n][3][i], pow3[cntQ - i]));
printf("%d\n", ans);
}
```

Wow that was faster than flash!!

I SUCCESSFULLY GAVE MY FIRST CONTEST. I WAS ABLE TO SOLVE ONE QUESTION.THANK YOU FOR THE EDITORIAL AND I HOPE TO PARTICIPATE IN MORE CONTESTS LIKE THIS AND LEARN NEW THINGS .

I wonder how many people did prove the correctness of their solution to problem E.

Max flow :)

nishant403, please explain how problem E is related to max flows. I tried a lot to think in this direction but could not figure it out.

consider rock paper scissor as 3 nodes.

player1's three nodes : a1,a2,a3

player2's three nodes : b1,b2,b3

we link a1 with b1,b2, link a2 with b2,b3, link a3 with b3,b1 (for example a1 is rock,b1 is rock ,b2 is paper ,a1->b1 draw,a1->b2 lose)

root is the source with infinite flow,the you should maximize b1+b2+b3

the n — b1 — b2 — b3 is minimum win. so maxflow can tell your the answer(make b1 + b2 + b3 flow as much as possible from a1,a2,a3)

Thanks for the insight :)

Is maxflow minflow some algo?? Related to graph??

yes

What are the prerequisite to learn it??

BFS/DFS is enough imo. Then you can look at Ford Fulkerson algo which computes the max flow and min cut.

In which question max flow and min cut are usefull??

Such as bipartite graph matching,which can be solved with the time complexity of $$$O(\sqrt n m)$$$.

Some guys from the testers (and authors) who do not bother about proofs just wrote mincost maxflow solutions :D

Could you please explain the logic behind E? As in, how do we prove that the optimization problem has that solution?

Proof by AC

What a nice proof! I think max flows should be in the tutorial.XD

See my proof for E E simple proof

Can you provide some resource to understand how maxflow works in such problems or at least topic names?

I wrote the following during the contest, and it got accepted. I see a lot of confusion in the comments about the problem. Can you please check and tell me if this is a correct approach? I am doubtful (after reading so many comments about 'flow') if I got lucky that it passed all test cases.

This is correct. We can prove it by greedy. The structure of answer at the end must be one of the $$$( a_1, b_2)$$$, $$$(a_2, b_3)$$$, $$$(a_3, b_1)$$$ after deleting the other elements optimaly. Suppose $$$a_1$$$ has the biggest remaining value after deletion. (The other situations are similar), then $$$a_1$$$ is the hardest to delete. We should delete $$$a_1$$$ with all $$$b_1$$$ and $$$b_3$$$. If we waste $$$b_1,b_3$$$ in deleting $$$a_2,a_3$$$,the answer will be even worse. If $$$a_1 < 0$$$ then the answer is $$$0$$$ (we can even save elements from the hardest case, therefore $$$a_2,a_3$$$ can also be deleted to $$$0$$$), otherwise the answer should be $$$a_1 - b_1 - b_3$$$.

i wonder if those russian high school students are also checking out the solutions in coddeforces or not ?

Nice problemset btw .

Nah, the first few stages of this competition are hosted on our local site with some really dumb restrictions I don't want talk about. But, iirc, the third (semifinals) stage is hosted on some local domain of codeforces.

To all the 'wow that was fast' comments, that's what she said...!!

Underrated comment

Oof

In problem E, for finding the min wins many people have directly used max(0, a1 — b1 — b3) + max(0, a2 — b1 — b2) + max(0, a3 — b2 — b3) . Can someone prove how this is correct ?

We need to use max(0, a1 — b1 — b3) a1 for b2, It's similar for other two cases. The only problem is that we use some (b1 + b3) for a1 and some (b1 + b2) for a2, will it be enough? We can see that (b1 + b2 + b3) is greater or equal to (a1 + a2), so it's ok.

I think this greedy solution works correctly. However, I'm sorry that I can't give a formal prove.

Is it actually correct??? maybe just the pretests???

I did $$$max(0, b1 - a1 - a2, b2 - a2 - a3, b3 - a3 - a1)$$$ and it passed. I have some intuition that it would work but not sure at all. Someone prove this please.

We have a draw if Bob use the same thing as Alice and losing if Bob counters some specific item.

Wins for Alice are situations where Bob have some extra $$$b'_i$$$, which cannot be matched with $$$a_i$$$ or $$$a_{(i+1)\%{3}}$$$. If there are no such extra $$$b'_i$$$ then Bob can create outplaying strategy.

So, if we have some $$$b_i$$$, such that

$$$b_i > a_i + a_{(i+1)\%{3}}$$$

then

$$$b'_i = b_i - a_i - a_{(i+1)\%3}$$$

Our goal is to find all these $$$b'_i$$$.

We can prove that: there is only one such $$$b_i$$$ , if it exists.

Proof:

Let we have 2 of them, $$$i \neq j$$$

$$$b_i > a_i + a_{(i+1)\%{3}}$$$

$$$b_j > a_j + a_{(j+1)\%{3}}$$$

then

$$$b_i + b_j > a_i + a_j + a_{(i+1)\%{3}} + a_{(j+1)\%{3}}$$$

For every $$$i, j$$$ the same situation will appear:

$$$b_i + b_j > a_k + a_m + 2a_{3-k-m}$$$

$$$(k \neq m)$$$

Also we have this statement

$$$b_i + b_j + b_{3-i-j} = a_k + a_m + a_{3-k-m} = n$$$

And so, next statement is going to be true

$$$a_{3-k-m} + b_{3-i-j} < 0$$$

Or simply

$$$a_p + b_q < 0$$$

For some $$$p$$$ and $$$q$$$, but every $$$a_p$$$ and $$$b_q$$$ are >= 0, so we have a contradiction.

So, there is only one group of items with extra items in it or there is no such group. Quantity of these extra items is the answer, otherwise the answer is 0.

I think instead of

aand_{(i+1)%3}athere should be_{(j+1)%3}aand_{(i+2)%3}a,correct me if I am wrong. Anyway great explanation!_{(j+2)%3}Obviously, this is a lower bound, but can we reach it? Just to prove it (1) (a1-b1-b3)+(a2-b1-b2)+(a3-b2-b3) = -n (2) B1=a1-b1-b3 >= -n (3) B2=a2-b1-b2 >= -n (4) B3=a3-b2-b3 >= -n If two of them are greater than 0, then the other is less than -n, but this is impossible, all three are either less than or equal to 0, or only one is greater than 0. I.If B1<=0,B2<=0 and B3<=0，this is correct. II.Only one is greater than 0.For example, a1-b1-b3>0, and after removing the game that Alice won, a1=b1+b3, so that b1 and b3 consume a1. At this time, b1=0, b3=0, a1=0, obviously a2 , a3 can't win b2

Was this tutorial posted even before the contest finish? xD

You came early

That's what she said

Lol I solved E exactly same as written in editorial , I initially thought that it was an overkill but now I realized it was intended.

https://mirror.codeforces.com/contest/1426/submission/94114892 why this doesn't work?

Could anyone please show me the steps for

n = 42?For the first 5 steps, add 1 to get [6] as the array

For the next 6 steps, append 6 in the array to get [6 6 6 6 6 6 6]

How the author arives at the part that not more than O(sqrt(n)) is required if anyone can help me proving this.

You to make the sum

at leastn. so best way is to go till sqrt(n) and then just append it. Check the sample cases.Assume that we are fixing x as the value taken by all elements of the array, and y as the number of elements. We need to check for all (x, y) such that x * y >= n.

For a particular x, y can simply be calculated as y = ceil(n / x). Thus, the number of moves required = (x — 1) + (y — 1) = x + y — 2

If you take x beyond sqrt(n), you start getting same values for y for continuous range of x, which implies unnecessarily wasting moves by increasing the value of our array element to a higher x, and appending it the same number of times, y.

Consider the case of n = 12

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

y = [12, 6, 4, 3, 3, 2, 2, 2, 2, 2, 2, 1]

As you can see, after x = sqrt(n), y takes the same value for a range of x out of which we only need the distinct one's.

The distinct values of y (after x = sqrt(n)) are y = [3, 2, 1] and corresponding x = [4, 6, 12] which gives the same (x, y) pairs as traversing x till sqrt(n) did, just the values are swapped!

P.S. : not a very formal proof, but I hope this helps you understand why checking beyond sqrt(n) is not required.

int ans=INT_MAX; for(int i=1;i*i<=n;i++){ int x=ceil((n)/(float)i); ans=min(ans,i-1+x-1); } cout<<ans<<endl;

Why is this not correct?

Not sure if

floatcauses an overflow, try changing it todouble?Thanks a lot for the help. cuber_coder

soln Actually, it reduces to this, can you please expain the correctness of the above o(1) solution?

lets say the number of times we do +1 operation be x,then number of steps will be (x-1)+(n-1)/x,minimimum occurs when x-1=(n-1)/x (using A.M.,G.M. property),hence x=sqrt(n).

I think it should be x-1 = (n-x)/x. Got the idea of cuber_coder. Thanks!

For C: Answer = sqrt(4*N — 1) — 1

Is this correct ?

let the increment be X, then the answer must be Ans= ceil((n-x)/x) + x-1 So using the arithmetic mean concept answer is greatest when both terms are equal, so ceil((n-x)/x) = x-1 or you can say that x must be in between sqrt(n)-10 to sqrt(n)+10

My submission : 94074745

Hi ,

can you please explain , the reasoning behind considering both terms equal .afaik , Ans >= 2 * (ceil(n-x)/x)*(x-1) acc to AM>=GM . what am i missing ?

We know that AM >= GM But we want answer to be minimum possible,

That mean AM=GM (least possible)That mean (x+y)/2= sqrt(xy) this is only possible when x=y. => (ceil(n-x)/x) = (x-1) => ((n-x)+(x-1))/x = (x-1) =>. (n-1)/x = x-1 Or we can say thatx = sqrt(n) ± 10..If you are still confused ask me I would be happy to solve them ans plslikethis comment :)I am very new to coding, Can you please explain me in problem C, we were trying to make an array but you are using arithmetic mean and geometric mean. How did you reach to that conclusion? I understood solution1 in editorial but cannot reach to AM and GM.

In these type of Questions first try to find the function of answer which is dependent on x. Then try to figure out how you would maximize it. Solve as many problems as you can.. this will help alot.. :)

Could you please tell me where can I find such problems ?

I want to practise this types of problems more

I dont know any specific topic, I would suggest keep reading editorial and comments for such tricks :)

Finally I understood AM and GM. Thanks for your help

i can understand the AM>=GM concept. so (n-1/x) + (x-1) is to be minimised. from here how do you relate it to AM , GM ?

Also how did you come to the conclusion that we have to increase till sqrt(n) and then copy

We know that for two positive numbers a and b,

and the equality holds only when a=b..

so, from there we get that

`(n-1/x) + (x-1)`

is minimum only when`(n-1/x) = (x-1)`

solving it we'll get`x = 0.5 ± sqrt(n - 1.5)`

so to be on safe side check for all the values of x form`[sqrt(n)-10 , sqrt(n)+10]`

.Thank you for your valuable time. Also answer my second qn , how did you come to the conclusion that we have to increase till sqrt(n) and then copy ie. before coming up with the before (n-1/x) + (x-1) after taking ceil ie (n-x+(x-1))/x + x-1

we have to increase till sqrt(n)We don't have to go till the sqrt, I'm saying that the answer lies between`[sqrt(n)-10 , sqrt(n)+10]`

Also for the ceil part,

`ceil(x/y) = (x+y-1)/y`

you can check by putting random numbers.. :)Can anyone please explain the approach in F?

How is this possible Editorial was out before the contest xD! The questions were easy but conceptual...Thanks vovuh!

The editorial came in O(1) time.

I think the problem E should have been B/C question type because, for minimum moves, we had to just generate all permutations in a brute force. Not much logic involved over there!

this is actually how i do it XD

E is not even a problem to 1800, just dont get why testers put a such easy problem to that position

I thought it would be too stupid to generate all combinations on E and I gave up...

Problem C can be done without even using a loop, basic math.

can u explain?

Try to plot the graph of the formula given in the editorial:

`x + ceil(x/n) - 2`

If you remove the ceiling from the expression, the resulting expression`x + x/n - 2`

is a lower bound for the initial expression (because always`ceil(x) >= x`

). So, if we find the smallest integer value of that expression for`x >= 0`

, we'll be done. Using some calculus, you can find that this expression is minimized for`x = sqrt(n)`

, so ceiling it and plugging it into the original equation will give us the smallest integer value of the expression. (I hope I could explain it correctly...)how can you be sure that i = ceil(sqrt(n)) , UPD : got it

Can anyone explain for problem C, how adding 1 till we reach a number x and then copying it is the most optimal way?

As suggested in the editorial, we can prove this by swapping the order of the two operations and checking which results in a better solution.

Let's say you have $$$x$$$ in the beginning, if you do increment and add, you'll have $$$(x+1)+(x+1) = 2x+2$$$. Instead, if you decide to add and then increment, you'll have $$$x + x + 1 = 2x+1$$$.

Thus we can see that if we ever do increment after adding to set, we'll always be worse off. That is, we should always increment the value first and then add it.

I am using ternary search to find the minimum of the function given in the tutorial but I am getting WA on test case 2. Could you tell me what is the problem? Submission: https://mirror.codeforces.com/contest/1426/submission/94132053

The function $$$F(x) = x + n/(x+1)$$$ is ternary on real numbers when $$$x, n >= 0$$$.

But for integers $$$F(x) = x + ceil(n/(x+1))$$$ doesn't seem to be ternary.

Both functions seem to have their minimum point pretty close tho (I don't have a proof for this. I hope somebody could provide one or even some insight or intuition).

You can plug in arbitrary values of n and draw both functions here to visualize it: https://www.desmos.com/calculator.

You can avoid this problem in this problem by searching using doubles and try the integers around the minimum point (which may or may not be fractional). I did something similar in this submission: https://mirror.codeforces.com/contest/1426/submission/94170281

What a nice trick!

Please note that this is not a general trick. It relies on both functions having their minimas pretty close.

I know, but I guess that the ceil function is what make F(x)=x+ceil(n/(x+1)) not unimodal, so removing the round part give us a better candidate function for ternary search...

Thanks for the clarification btw

You're welcome. Thanks for the insights.

Can anyone help me figure out why didn't my solution to C work even though it iterates from 1 to 2*sqrt(n) ? Here's my submission and thank you :)

Simple Solution for F using combinatorics. 94117068

Kindly explain your solution.

Fix the $$$b$$$ in a position and count the number of possible $$$a$$$ in the prefix and possible $$$c$$$ in the suffix.

Problem A: Can someone explain how did the formula floor(n-3 / x ) + 2 come from? Thanks in advance

We have, $$$2 + x + x + x + ... + x \geq N \Rightarrow 2 + (Step-1) \times x \geq N$$$

This results in $$$Step \geq \frac{N-2}{x} + 1 \Rightarrow Step = \lceil\frac{N+x-2}{x}\rceil$$$

Now, either you can just use this in your program, or else there is a neat way to do this and that is $$$\lceil\frac{a}{b}\rceil = \lfloor\frac{a+b-1}{b}\rfloor$$$. If you use this result, then the above expression converts to $$$Step = \lfloor\frac{N+2x-3}{x}\rfloor = \lfloor\frac{N-3}{x}\rfloor + 2$$$.

You can try to verify that the ceil to floor conversion works for yourself.

I understand the ceil to floor conversion, but would you please elaborate the inequality to equality conversion of Step ≥ N−2x+1 ⇒ Step=⌈ (N+x−2)/ x⌉ ?

Basically, we want the smallest integer which is either equal to or greater than this fraction, which is the definition of the ceiling function.

Oh, I understood you just transformed the 1 into x / x so you can use the ceiling to flooring conversion. Thank you

Actually, you don't even need to do that, you can leave the 1 as is an only change the fraction. It'll come out to be the same.

what is step-1

Step is the level you are at. So $$$2$$$ for the first level and for the remaining $$$Step-1$$$ levels you have $$$x$$$ rooms, which gives you, $$$2 + (Step-1)\times x$$$ total rooms.

can you tell me the corresponding mathematical topic of this approach.like how to find the formula

I am not sure how to answer this. I'm tempted to say this comes under linear equations!? After getting the equation, I don't think you need to get the exact formula as stated in the editorial, just solve it as you would on paper.

Another solution for finding minimum wins for ALICE in E . a1 b1 c1 ---> set with alice

a2 b2 c2 ---> set with bob.

to minimize wins a1 must be played against a2 and c2 thus a1 depends on a2 , c2 b1 depends on b2 a2 c1 depends on c2 b2.

also I claim that a2 handles a1 and b1 . b2 handles b1 , c1 , c2 handles c1 and a1 that is cyclic order. lets supppose any one of the following situation is true.

a2>=(a1+b1) --->(1)

b2>=(b1+c1) ---->(2)

c2>=(c1+a1) ---->(3)

in any of this case we can make 2 values of a1,b1,c1=0; example in case of situation 1 a1 b1 can become 0. c1 can be minimised by remaining b2 c2. by subtracting minimum accordingly. thus remaining value of c1 is answer. similarly we can check for other cases.

In case any of these situation is not true

then simply the minimum value is 0. proved below

Proof.

Since a2<(a1+b1); b2<(c1+b1)==>(4); c2<(c1+a1) -->(5) since every 3 inequality holds so at first we can reduce any one of a1 and b1 by amount a2 and make a2 completely 0. then from inequality 4 we can make b1 0 and b2 0 or still if we have b2 left we can reduce c1 . now reduces some a1+c1==c2 as we reduced a1 +b1+c1 by amount a2+b2 and since a1+b1+c1==n thus reduced value is n-(a2+b2)==c1. thus remaining sum from first set equals last remaining value. Hence we can make alice lose every match in this scenario.

Submission!

94112692

Small correction brother, thus reduced value is n-(a2+b2)==c2 not c1

Can someone explain a solution using flows in problem E? I know only the basics on this topic and I'm really curious how it can be applied in this problem.

You can link the source to Alice's options (1-rock, 2-scissors, 3-paper) with their respectives capacities (a1, a2, a3) and the sink to Bob's ones (4-rock, 5-scissors, 6-paper) with capacities (b1, b2, b3). Then link the options that make Alice not win (draw or lose) mentioned in the editorial with infinite capacity and just calculate the max flow in that network. The edges will be:

Note that (4, 5, 6) are Bob's options (rock, scissors, paper) but with other numbers to not repeat nodes. So the minimun number of rounds Alice can win will be (n — max flow) Code: link

"Then link the options that make Alice not win (draw or lose) mentioned in the editorial with

infinite capacityand just calculate the max flow in that network"Can you please give some intuition behind the infinite capacity part. ( I got how the edges will be connected but why the capacity will be infinite ?)

Sure, here we are maximizing the amount of times that Alice can draw or lose (minimizing the times that win) and the flow algorithm just add the Edge with the minimal capacity in the augmenting path. We don't want to consider the capacity of these intermediate edges, so assign infinite to them ensure that :)

Can we do the third problem using DP?

no because of time limits. otherwise we can make a recursive solution easily.

How? can you tell the recurrence?

ok so we have to make n from least steps. and our recurrence depends on two things. first -> value we want , second- > max value we have. n = value we want, maxi = max value we have. solve(n, maxi) = 1 + min((solve(n-1, maxi+ 1), solve(n-maxi, maxi)); here base case is if n <= then return 0;

great!! I couldn't come up with it but got the thought process.

https://mirror.codeforces.com/contest/1426/submission/94126035

Can anyone tell me the error in this sol for D?

Line 39 — variable cur overflows the range of

intPlease look at these two submissions to problem C.

Sub1 : https://mirror.codeforces.com/contest/1426/submission/94126382

Sub2 : https://mirror.codeforces.com/contest/1426/submission/94126537

Sub1 uses ceil function and Sub2 uses the technique in author's solution 1.

Sub2 is accepted while Sub2 gaves TLE. Can you please explain why ceil function lead to TLE? ;_;

Maybe some problem with double or something. People usually avoid using ceil for these reasons.

P.S. I don't know if you know this or not, but C++ has a build-in swap function.

Done!! I would never use ceil again ;_;.

Oh ok, I didn't know about swap.

Its just me or someone also felt that nowadays problem A,B,C in codeforces Div-2 and Div-3 rounds are of almost same levels?

another nice solution for F with math.

we can make substring

abcby taking a charecterband oneain left(left of b) and onecin right side(right of b)hence for a string

s(which doesn't contain`'?'`

) we can calculate the number ofabcsubsequence as the following method :$$$a_i = $$$

`number of a before the positon i`

$$$c_i = $$$

`number of c after the positon i`

$$$ans = \sum_{\text{s[i]=='b'}}{a_i\times c_i}$$$

If we allow

`'?'`

in our string then what will happen? :$$$p_i = $$$

`number of ? before the positon i`

$$$q_i = $$$

`number of ? after the positon i`

Then for $$$i^{th}$$$ position if it is

`'b'`

then in left there might be $$$a_i + k$$$ numbers of`a`

, where $$$0\le k \le p_i$$$how many string are there that have exactly $$$a_i + k$$$ numbers of

`a`

before the $$$i^{th}$$$ position ?the answer is $$$\binom{p_i}{k}\times 2^{p_i-k}$$$

(we can do , pretty much the same things for right side)

summing up the idea we got our total answer:

$$$\text{answer = }\sum_{\text{s[i]=='b' or s[i]=='?'}}{(\sum_{k=0}^{p_i}{(a_i+k)\times\binom{p_i}{k}\times 2^{p_i-k}}) \times (\sum_{k=0}^{q_i}{(c_i+k)\times\binom{q_i}{k}\times 2^{q_i-k}})}$$$

we can write $$$(\sum_{k=0}^{p_i}{(a_i+k)\times\binom{p_i}{k}\times 2^{p_i-k}})$$$ this part as this $$$(3^{p_i-1}(3a_i+p_i))$$$

this things reduce our solution in :

$$$\text{answer = }\sum_{\text{s[i]=='b' or s[i]=='?'}}{(3^{p_i-1}(3a_i+p_i)) \times (3^{q_i-1}(3c_i+q_i))}$$$

we can easily calculate this in

`O(n)`

you can see my solution here

steinum

`we can write (∑pik=0(ai+k)×(pik)×2pi−k) this part as this (3pi−1(3ai+1))`

. Is there any formula for this line you wrote??well , I dont know if there is any well known formula for it or not.

$$$\sum{(a_i+k)\times \binom{p_i}{k} \times 2^{p_i-k}}$$$

$$$\Longrightarrow a \sum{\binom{p_i}{k} \times 2^{p_i-k}} + \sum{k \times \binom{p_i}{k} \times 2^{p_i-k}}$$$

$$$\Longrightarrow 3^{p_i}a+3^{p_i-1}p_i$$$

for the first part we can define a problem :

`you have to choose 'k' ball from p ball and color them white, for the rest of the ball you can color them with eigther black or blue`

this problem can relate $$$\sum{\binom{p_i}{k} \times 2^{p_i-k}}=3^{p_i}$$$

and, for the second part we can define another problem :

`you have to choose 'k' ball from p ball and color them white, for the rest of the ball you can color them with eigther black or blue. And from the white balls you can pick one ball`

this problem can relate $$$\sum{k \times \binom{p_i}{k} \times 2^{p_i-k}}=3^{p_i-1}p_i$$$

2nd formula will give p×pow(3, p-1)

yes... I got some Typo ... thanks

Can C be solved using Binary search ? it worked on sample test cases but i guess i was not able to converge the search space?

You can solve it using the ternary search. The answer will first decrease and then increase. But if you have the intuition that the answer won't be too big, you can just iterate until your new answer is better than the previous one.

https://mirror.codeforces.com/contest/1426/submission/94078419 Can't it be done only using binary search?

Ternary search may not work. The answer is not

strictlyincreasing or decreasing.Yes, you're right, Thanks!

I have done it using ternary search. The only thing you need to take care is that when the (value at mid) == (value at (mid + 1)) then recursively search for the best answer in both (low, mid -1) and (mid + 1, high) ranges.

My submission : 94125048

Actually ternary search can work here..you can have a look at the graph :

Note x can only take integer values.

Oh yes I missed putting floor...but still the graph does decrease then increase/

But not "strictly", for ternary search the graph must be strictly decreasing then strictly increasing.

In D, Why do we need to clear the set? Can't we keep the prefixes from the left side and move on?

Then you will count extra. Ex- 1 -2 1 -2 3. In this case you will add a positive no in bw -2 and 1. but you will add extra since you will consider tha array -2 1 -2 3 also as sum=0.. But we have already inserted a no so sum is not 0. Hence we don't want to save arr[0] and arr[1] contribution in set.

No, because the prefixes "restart" after you insert a big number.

Please explain what this line means in E :

"It can be shown that if we started using some combination we are better to end it before using the other one. " .

Does it means that we need to minimise both of them by minimum of them ?

It means suppose we are currently Choosing paper for Alice and Scissor for Bob , then we must continue until its not possible to use this combination (because either paper finished or scissor finished or both).

Fine. But then editorial also says that order of these steps does not matter.

So i perform for first test case as follows:

Take a1 and b1. Nothing changes.

Take a2 and b2. Both reduces to 0.

Take a3 and b3. Nothing changes.

Only value remains are b1 and a3.

So minimum value should be 1 using these steps . Where i went wrong ?

You should take first b3 with a2, then b2 with a1.

So these are the 6 types of combinations in which Alice loses. So it can be shown that if you are going to use some combination more then once, for example — a2 and b1, it is never efficient to use a2 — b1, then use another combination and again a2 — b1. So now you have six different segments of combinations which you got to reorder in the best way. You try all 6! variations and choose the best one.

I get it that we can try all orders of combinations.

But why editorial says "It is also possible that the order of these combinations does not matter, but we didn't prove that fact " ?

Aah, it means that there might be a constant solution where you don't have to try all variations but they haven't proved it.

For problem E how we will get minimum win as 119 for following example?

129 is lowest I can think of.

First use all your Papers against their Paper and Scissors. In this way, you'll have 119 Papers remaining.

Got it. Thank you!

I want to know how this max flow works in such problems. I think 94072786 uses max flow.

If you can provide me with some resource that would be great. Thank you again.

This contest was one of the greatest programming contest..I have ever seen in my life..(problem statements pleased me!)

yeah..that was super..the problem statements are so cool..and I like easy small codes..and wanted more contests from..BledDest,fcspartakm and vovuh..thank you guys for this contest..

I think max flow is easier than other approaches for E xD. Maybe it should be written in the tutorial, at least it's interesting.

Problem F is a thing of beauty.

joy forever

John Keats fans...

Sorry for my poor English,and it may sound silly...But I hope it will be helpful for you bros

Can anybody tell why the best solution will be near sqrt(n) in Problem C

We should get n (or nearest) by multiplying two numbers and the sum of two numbers should be minimum (greedy) hence, the rule!

Which numbers do we multiply? We can only do +1 or copy (sum). Where is the multiplication?

You increment some times ok, this takes you to $$$X$$$. This will take approx $$$X$$$ steps. Now you'll add it $$$Y$$$ times to make the sum $$$N$$$. This will take $$$Y$$$ steps. You want $$$X+Y$$$ to be minimum, given $$$XY=N$$$. Which gives you the desired condition of approx $$$\sqrt{N}$$$

For C, How did you come up with the intuition that we only need to go till sqrt(n) instead of n/2?

This comment might help!

Can anyone tell me on what test case my solution for B fails? It is hacked. Here is my submission.

I misunderstood problem C and wrote a completely different solution but it still seems to pass the tests. Can someone hack my solution or tell me why it is correct. This 94146956 is my submission. Also I wonder if anyone else wrote a similar solution?

i think proplem E must D and D must be E any one see that E is so easy

for Problem C why the array could not consists of copies of different numbers?

for problem 1 instead of the formula mentioned above i used (ceil((n-2)/x)+1), this too passed all the test cases, could someone explain me whether this is equal to the formula mentioned above or is there any test case where this fails

It's same, you can use $$$\lceil \frac{a}{b}\rceil = \lfloor\frac{a+b-1}{b}\rfloor$$$

Why is p(r) and p(l-1) has to be same in problem D??? Can someone please explain it to me

If p(r) = p(l-1) we can say there ia no change is prefix sum or sum of the interval (l,r) is 0.

Arr[l] + arr[l+1]....arr[r] = 0

P(r) — p(l-1) = 0

So, P(r) = p(l-1)

`It is also possible that the order of these combinations does not matter, but we didn't prove that fact.`

What does this statement mean? I tried running the brute against this:

47

14 21 12

30 9 8

But for more than 500 different orders the minimum calculated was different from the actual one.

He might be taking of some special cases

Like, a= {3,3,3} and b= {5,5,5}

Here the order of permutation doesn't really matter.

Okay, I thought that the order doesn't matter in general because mentioning that it won't matter for some special cases is unnecessary.

Can anyone explain me 1426D — Non-zero Segments problem's logic please. I am not able to understand the provided solution.

Let us define $$$presum_{k}$$$ as the prefix sum, $$$a_k$$$ as the array.

Let's define $$$i,j$$$ as indexs($$$i < j$$$)：

In order to avoid this situation， we insert a $$$+\infty$$$

behind the $$$a_j$$$. Like this: $$$a_{i+1}, \cdots, a_{j-1}, \stackrel{\infty}{\downarrow},a_{j}$$$.Then reconsider from $$$a_j$$$Part of the core code:

hi first of all nice explanation thank you for that.

but i have certain doubts

why we have clear the prefix sum left of the new element added, why we dont consider it anymore and can you tell how the complexity of the program in the editorial is nlogn?

thanks

hi, — Under normal circumstances, we need to add an infinite number to the prefix sum

before the insertion positionObviously, after inserting an infinite number, we can guarantee that this situation does not exist：

So we don’t need to consider the prefix sum before the insertion position.If we do not clear it, it will affect subsequent operations.Like this:

If you do not clean up, it will appear $$$mp.count(5)$$$. Actually that is $$$5 + \infty$$$. So cleaning is to simulate the process of adding infinity.

i do not konw the extacly complexity of the program in the editorial, because i konw little about py, if the operation

`in`

and`add`

are $$$\mathcal{O}(1)$$$, the algorithm is $$$\mathcal{O}(n)$$$, if the operations are $$$\mathcal{O}(\log n)$$$, the algorithm is $$$\mathcal{O}(n \log n)$$$I have a little bit confusion about test case 3 (

`-1 1 -1 1 -1 1 1 -1 -1`

) .Here prefix sum is

`-1 0 -1 0 -1 0 1 0 -1`

. I have to insert a number before every 0 according to describe above. Then there is only 4 options. So ,How the result is 6?. Please clarify my fault.OK， I have also had this problem, which is also the key to solving this problem. You insert a number before the first

0like thisthen, the prefix sum will be [Reconsider the next element from infinity]:

To make it clearer：

You can find that after inserting a number, a new 0 may be generated while eliminating a 0.

Your idea is offline, but this is actually an online problem. Need dynamic processing. in my opinion

My solution to F, it maintain 6 cnt for

a, ?, ab, a?, ?b, ??and get the result.Hi guys, In problem C: why do we need to add the bolded term? ans = min(ans, x — 1 + ((n — x) +

x — 1) / x); and in the tutorial he didn't mentioned this term thanks.It's actually a trick for ceiling

Instead of doing ceil(a / b) you just do (a +

b — 1) / bHow to solve C if instead of having sum greater than or equal to n it were to be exactly equal to n?

The cost for reaching sum exactly n, and for reaching sum at least n is the same. Suppose you are duplicating number i. If n % i = 0 then you reach sum exactly n. Otherwise, while increasing 1 to i with operation one, when you reach n % i duplicate it, this way you save the need to duplicate i one more time, because the n % i will reach the sum to n. As you can see, the cost is the same. Funny thing, same code gets AC in both problems.

in c why the solution doesnt go beyon root n?

thanks

If you increment your number to $$$sqrt(n)$$$, you won't need more than $$$sqrt(n)$$$ copies of it since $$$sqrt(n) * sqrt(n) == n$$$

ohh thank you got it.

As noted, Problem F can have different solutions with varying implementation complexity. Here is a simpler one, imo.

At each index, find count of subsequences

'a','ab'and'abc'(conveniently named as such in the code below) appearing in all combinations so far. One thing to note is, when appending 'a', the new 'a' appears in how many? count of number of strings so far (call it'm'below). Leaving out mods in the (pseudo) code for easier reading.My submission: 94171796

ps: I see this is very similar to DP, except no explicit

dptable. It's similar to how you can calculatefibonacci(n)using`a=0, b=1, c=1; for(3..n) b = c = a + (a = b); print c;`

Bad idea to do it in one statement, but meh! you get the idea :)i also thought about same solution. but i couldn't think about m. why m= m*3 and a += 2*a + m what i was doing was a = 3*a + 1. can you explain why you used m and how it work a little more.

mis total number of different strings so far. For each'?'we have 3 choices (a, b, c) sox 3for each'?'.`a = 3 * a + m;`

which is the same. When you see'?', you replace it with one of 'a' or 'b' or 'c'. Ineachof these cases, you carry over previous counts of`a, ab, abc`

(those not including this index). Additionally, if you include this index, each of them increase by the same factor as in their corresponding cases above.Amazing solution

Please help me with what's wrong here. https://mirror.codeforces.com/contest/1426/submission/94178071

Have a look at my code (accepted) for 1426C - Increase and Copy

`int n ;`

cin >> n ;

int a = sqrt(n);

int b = n / a ;

if(n % a) b++;

cout << a + b — 2 << endl ;

I hope , you will find it more easy (no loops or iterations) than many other approaches :)

Please explain your logic !

You have to find two integers

aandbsuch that`a*b >= n`

and`a+b`

is minimum possible.These values will be

`sqrt(n)`

and`ceil(n / sqrt(n))`

.Approach :You have to increment the

1(present in array) toa. This will take(a-1)moves.Then append this number

ato the array(b-1)times.Ultimately, element

ais presentbtimes in array which gives`a*b >= n`

Total moves will be :

(a-1)increments +(b-1) appendsSo answer will be

`(a + b — 2)`

.Hope it helps :)

The ratings are not updated yet. Is there any problem with the contest or something else? When can we expect rating change? UPD: the ratings are changed now.

same doubt

same question

For problem E, the answer for the minimum can directly be given as $$$max({0, b_1 - a_2 - a_3, b_2 - a_3 - a_1, b_3 - a_1 - a_2})$$$.

I understand that number of moves will be x-1+((n-x)/x) but why ((n-x)+x-1)/x ?? I cant understand the "X-1" at the second part

say you wish to get the sum 9 using 4s. you have to use 3 4s (4+4+4=12) but a simple n/x gives answer 2 in this case. suppose there is a case where we need to get sum 9*k using k's. you need 9 k's. for all n where 9*k < n <= 10*k, the answer has to be 10. (n+k-1)/k ensures this.

I didn't get it. sorry

take x=4. now, - n/x=0 for n=0,1,2,3. - n/x=1 for n=4,5,6,7. and so on. But we need this: - f(n)=0 for n=0. - f(n)=1 for n=1,2,3,4. - f(n)=2 for n=5,6,7,8. we can get this if f(n)=(n+x-1)/x. (we are shifting those x-1 numbers into the next group by adding x-1 to n.)

To avoid floating point operations we write it as

`Ceil(A/B) = Floor(A + B - 1 / B)`

; For example Ceil(7/3) = Floor(7 + 2 / 3) = 3 Or Ceil(7/2) = Floor(7 + 1/ 2) = 4 We convert Ceil to floor because in most programming languages floor(A / B) = A / B. Note : This only works for positive values. For negative values we have to make some changes.In E, how to proof the maximum number? The editorial doesn't have an detail.

Example:

22

5 8 9

11 7 4

The maximum number is min(5,7) + min(8,4) + min(9,11) = 18

And the thing left is

0 4 0

2 2 0

So The answer is 18-2 = 16 ?

Alice has 4 scissors and Bob has 2 scissors and 2 rocks, so Alice has to lose 2 more rounds?

But the correct answer is 18, so I'm confused. Can anyone explain please ?

Alice won 18 rounds and lost 2 rounds , there is no points thing here so doing 18-2 is not needed. the maximum number of wins will just be 18

Thanks for clarifying! I misread the statement.

thanks is said by upvoting. :sad:

F is a nice problem

soln can someone tell why this solution works for problem c?

easy solution for C

formula...(ceil)(((sqrt(n)-1)*2.0))...

is the answer https://mirror.codeforces.com/contest/1426/submission/94245532

Can you please explain, how you arrived at this conclusion?

Can anyone tell why we are changing abc,ab,a,and o values in reverse order in s[i] = '?' section and what is the significance of using variable 'o' here

"o" is the total number of possible strings so far (it's equal to 3^(number of ?s))

The assignments are done "backwards" because to calculate abc you need the original ab, not the updated one (same for ab and a, and a and o).

"o" is the total number of possible strings so far. ok but why do we need this. when we find "b", we increase count of "ab" by count of "a" so far. because all previous "a" can pair up with this "b" giving us "ab".... and same with "c", when we find "c" , we increase count of "abc" by count of "ab" so far. because all previous "ab" can pair up with this "c" giving us "abc".

but when we find "a", why are we not just increasing count of "a" by one? because "a" doesn't need to be paired up with any previous character?

why are increasing count of "a" by number of string? please help

I need a little help in Problem E :- I thought of solving it like counting number of subsequence of "abc" the transition is trivial to counting number of sub-sequence . i.e if the current characters match then

`dp[i][j] = dp[i-1][j-1] + dp[i-1][j]`

and when it doesn't match and current is not equal to '?' then`dp[i][j] = dp[i-1][j]`

. For the question mark part`dp[i][j] = dp[i-1][j-1] + 3*dp[i-1][j]`

actually out of 3 possible character one of it is going to be equal and rest 2 not so this case is just sum of previous 2 cases.Everything is fine but for consecutive '?' it is wrong for eg for the last sample test-case it gives 44 instead of 46. Can anyone provide feedback am i missing some case??

You are missing one thing. Let's say $$$dp(i,\text{'a'})$$$ is the amount of times $$$\text{'a'}$$$ appears in all sequences on prefix $$$[1\dots i]$$$. Let's also say that $$$k_i$$$ is the amount of question marks on prefix $$$[1\dots i]$$$

Then,

Can anyone tell what is wrong in my code please

https://mirror.codeforces.com/contest/1426/submission/94357901

Can you explain it?

Of course. a : the number of substring "a" b : the number of substring "a...b" c : the number of substring "a...b...c" mul: the number of strings recently So u can see that when strings were added - "a": a += mul; - "b": the number of substring "a..b" increases by the number of "a" - "c": the same as b; - "?":this is more interesting. The number of strings, a, b, c multiplies by 3 and then increases by 0, mul, a, b respectively. So the answer is c.

can anyone explain how he find min numbers of win in E problem I didn't understand what he was telling in tutorial.

try all the combinations.6C2=720 ways to permute all possible options to find the best way. Use next_permutation from C++ for trying all possible combinations.

In problem E the order matters. Random order will give WA.

Can someone explain me, why in problem c solution, ans = min(ans, x — 1 + ((n — x) + x — 1) / x) is written, and not ans = min(ans, x — 1 + n/x). I mean it will take x-1 increments to make 1 equal to x and then the number of moves to make the sum greater than equal to n will be n/x. Please point out where I'm making mistake.

How does sqrt(n) solution pass in problem C? There are 1000 test cases and 1000*sqrt(1e9) = 31622776. isn't 30 million operations too much for one second? I think around 2 million operations are maximum for 1 second. vovuh please let me know. Thanks.

problem C: we should copy the number

kthe square root of the least perfect square that not less thannthen the answer isk — 1 + (n — 1) / kI solved E with simple recursion. My submission if anyone interested.

How do you link your submission like this

see the options provided by codeforces while writing comment.

Problem C: I haven't got this line in the editorial :

Someone please explain me the reason/logic for this statement. Thanks a lot!It is pretty intuitive that we firstly need to do all increments and only then copy numbers (because otherwise we can swap the order of moves and the sum will not decrease).If you first copy and then increase something, you get a smaller sum. Try it on any example.

Alternative solution for F:

I iterated over positions where the value of the position is 'b'. For each position, I precomputed the number of occurrences of 'a' before, '?' before, 'c' after and '?' after.

Now, calculating the number of substrings where 'abc' is contained, where the 'b' is of the position I'm at, is pretty straightforward. https://mirror.codeforces.com/contest/1426/submission/101849687

I have submitted O(sqrt(n)) solution problem C but I it is giving TLE at test case 4, I am not able to figure out what is the problem with my solution. My friend's solution got accepted with same logic. I' going to share both submission links please anyone look into them and let me know what the problem is.

My submission Link: Here

My Friend's Link : Here

Please help me to find the problem with my code.

Editorial for problem F is made ridiculously hard to understand and implement. That's not the easiest way I can assure.

Can someone figure out why this code doesnt work

I have used a simple 2-d DP where upto index i :

DP[i].a = the numer of subsequences 'a'

DP[i].ab = the numer of subsequences 'ab'

DP[i].abc = the numer of subsequences 'abc'

when s[i]= a,b or c update them normally and when s[i]='?' , i consider all 3 cases one by one

Where am I wrong? does anyone solve it using 2-D DP instead of 3-D ? is 3-D even necessary here?

in D problem why the time complexity if nlogn it should be o(N) if we are using unordered set , unordered set can work too right ??