Привет, Сodeforces!
Мы очень благодарны Вам за участие в нашем раунде.
Спасибо Qwerty1232 за помощь при написании разбора.
Не сомневайся в себе, не сомневайся в своем решении. Не доказывай. Тестирующая система существует чтобы тестировать. Засылай.
Несколько наблюдений, если $$$(n; m) \neq (1; 1)$$$: - Сергей будет телепортироваться только 1 раз - Марго может не использовать порталы ни разу
Сергей и Марго будут двигаться только по направлению к целям (Сергей по увеличению $$$x$$$ и $$$y$$$, Марго по уменьшению $$$x$$$ и увеличению $$$y$$$.
Марго может двигаться по одному маршруту независимо от размеров доски.
1715A - Хмурогруз
Для удобства скажем, что вверх — по уменьшению x координаты, вниз — по увеличению x координаты, влево — по уменьшению y координаты, вправо — по увеличению.
Оптимальным является такое решение:
- Марго идет "наверх" к Сереже, тратит на это $$$(n - 1)$$$ единиц энергии, а потом вправо к своему месту назначения, потратив на это еще $$$(m - 1)$$$ единиц энергии.
- У Сережи появляется выбор: очевидно, что ему надо телепортироваться из начальной позиции или до конца вниз, или до конца вправо. Выберет он то, что сэкономит как можно больше энергии, а значит он переместится вдоль большей стороны за 1 единицу энергии.
- Дальше Сереже остается честно пройти меньшую сторону, на что он потратит $$$min(n, m) - 1$$$ единиц энергии.
Как не сложно заметить, если хоть одна из размерностей отличается от $$$1$$$, то ответом будет $$$(n - 1) + (m - 1) + 1 + (min(n, m) - 1) = min(n, m) + n + m - 2$$$. При $$$(n, m) = (1, 1)$$$ ответ, очевидно, $$$0$$$.
1715A - Хмурогруз
Очевидно, что, не считая 1 случая, Сереже всегда выгодно использовать телепортацию. Пускай первый посещенный им портал это $$$A$$$, а последний это $$$B$$$. Также очевидно, что ему не имеет смысла телепортироваться более 1 раза, поэтому будем считать, что он всегда телепортируется из $$$A$$$ в $$$B$$$ и точка.
Для удобства введем функцию манхэттенского расстояния между двумя точками: $$$dist(P_1, P_2) = |{P_1}_x - {P_2}_x| + |{P_1}_y - {P_2}_y|$$$.
Рассмотрим следующие случаи относительного расположения этих двух порталов:
- $$$A_x \le B_x$$$ и $$$Ay > By$$$
Марго надо сделать как минимум $$$(n - 1) + (m - 1)$$$ шагов. Порталы не помогают Сереже приблизиться к цели по оси $$$y$$$, поэтому ему придется сделать как минимум $$$(m - 1)$$$ шагов.
- $$$A_x > B_x$$$ и $$$A_y \le B_y$$$
Марго надо сделать как минимум $$$(n - 1) + (m - 1)$$$ шагов. Порталы не помогают Сереже приблизиться к цели по оси $$$x$$$, поэтому ему придется сделать как минимум $$$(n - 1)$$$ шагов.
- $$$A_x \le Bx$$$ и $$$Ay \le By$$$
Марго сделает как минимум $$$dist(A, B)$$$ шагов между двумя порталами. Путь между этими двумя порталами или обнуляет ее прогресс по оси $$$x$$$, или же по оси $$$y$$$, в зависимости от того, какой из порталов $$$A$$$ или $$$B$$$ она создала первым. Поэтому ей придется сделать еще как минимум $$$(n - 1)$$$ или $$$(m - 1)$$$ шагов. Сереже же придется сделать как минимум $$$(n - 1) + (m - 1) - dist(A, B)$$$ шагов.
- $$$Ax > Bx$$$ и $$$Ay > By$$$
Марго проделает как минимум $$$(n - 1) + (m - 1)$$$ шагов. Использование Сергеем портала обнулет его прогресс по обоим осям, поэтому ему также придется сделать как минимум $$$(n - 1) + (m - 1)$$$ шагов.
Во всех случаях количество необходимой энергии не менее, чем $$$(n-1) + (m-1) + min(n-1, m-1)$$$, что и требовалось доказать.
В какой-то момент после того, как эта задача была придумана, я загорелся желанием формально ее доказать. Я был очень доволен результатом — доказательство задачи A было длиннее, чем обычные разборы задач Fdiv2, а иногда даже и Fdiv1. За несколько дней до раунда Monogon рассказал, что есть решение гораздо проще для понимания, за что я ему очень благодарен! Но я бы хотел сохранить изначальную версию, как пример того, как не надо доказывать самую простую задачу второго дивизиона.
Жадник.
- Каким может быть минимальное и максимальное $$$s$$$ при остальных равных?
- Какое число мы всегда можем прибавить к числу, которое делится на $$$x$$$, чтобы не увеличить ответ?
- Минимальное $$$s$$$ не может быть меньше $$$x \cdot b$$$
- максимальный остаток при делении на $$$x$$$ это $$$x - 1$$$.
Рассмотрите задачу относительно границ между блоками
Для каждых двух соседних различающихся чисел считайте, сколько подотрезков их содержит.
Для изменений достаточно знать только соседние числа и позицию.
- Решение на С++: 169162300
Задачу можно решать независимо по разрядам.
Какие условия сразу дают нам сделать какие-то выводы? Те, которые говорят, что битовое или какого-то разряда в $$$i$$$-ом и $$$j$$$-ом числе это $$$0$$$, потому что тогда определенно точно оба этих бита равны 0.
Решая задачу по разрядам, сначала удовлетворите условие из второй подсказки, а затем пытайтесь занулить биты, начиная с первого числа.
- Решение на С++: 169162393
Для каждого $$$i$$$ от $$$1$$$ до $$$n$$$ попробуйте найти кратчайший путь из $$$1$$$ в $$$i$$$, оканчивающийся авиаперелетом.
Как решить задачу для $$$k = 1$$$?
Если вы решили задачу для $$$k = i$$$, то как её решить для $$$k = i + 1$$$?
- Решение на С++: 169162508
Несмотря на огромную степерь свободы, есть очень простое решение. Если у Вас выходит что-то сложное, в особенности, если Вы используете продвинутую геометрию, то, скорее всего, Вы делаете что-то не так.
Попробуйте пилообразные фигуры
Можно обойтись только двумя запросами
В этих двух запросах используется одна фигура, просто повернутая на $$$90^\circ$$$, а сама фигура переодична
- Решение на С++: 169162576
TLE on D T.T
Trash contest
no u
Wow, such a fast tutorial!
One of the best C
For experts or higher I guess
I don't think Monoblock's company is having many sales with such a complicated captcha.
Thanks for the really nice contest and also the editorial:)
Though I couldn't perform as well as I expected, the contest and the problems were interesting :)
I think convex hull trick is too complicated for div2 E, please don't add such tasks
You can also do it with D&C dp, I think this was a nice question. You learn these tricks but there aren't many "easy" questions on them because they are generally reserved for harder problems with more observation. This was a simple application and personally I got a nice Aha moment when realising I could use D&C, imo this way you get a chance to build an intuition for them
my hands finally knows about CHT by this task
You can also solve E using Divide and Conquer DP because of the square cost function
My submission
can you elaborate on the divide and conquer dp?
The objective of the D&C was to calculate the minimum distance after a flight(assuming the flight just landed at some point), so you have a set of distances you got from dijkstra in $$$dp$$$_$$$old$$$, then you calculate post flight distance for $$$i$$$, aka $$$dp$$$_$$$new[i]$$$ as $$$min_j (dp$$$_$$$old[j] + (i-j)^2) $$$
I divided this up into two parts
$$$min_{j<i} (dp$$$_$$$old[j] + (i-j)^2)$$$
$$$min_{j>i} (dp$$$_$$$old[j] + (i-j)^2)$$$
Both of these are what I solved using D&C DP, followed by more Dijkstra to calculate travel via roads
nice get the divide and conquer now,
using the optimal to cut up the array was cool wouldn't have thought of that
Can you elaborate how to solve one of those partial minimums? I was able to do that only with some crazy math.
Let $$$opt[i]$$$ be the index $$$j, j<i$$$ which gave the minimum value of $$$dp[j] + (i-j)^2$$$, then Divide and Conquer DP works iff $$$x < y$$$ implies that $$$opt[x] < opt[y]$$$, which you can see is the case here with some light maths. What you do is, if you want to calculate $$$dp[l]$$$ to $$$dp[r]$$$, let $$$mid$$$ be the middle point, you calculate $$$dp[mid]$$$ and $$$opt[mid]$$$ in $$$O(r-l)$$$, and once you calculate $$$opt[mid]$$$, it reduces the range you need to search for the rest of the elements, then you recursively do this calculate $$$dp[mid]$$$ and $$$opt[mid]$$$ for the segments that are left and right of $$$mid$$$.
This was very brief but you can read more about Divide and Conquer DP here
Can someone explain the Convex Hull Trick mentioned in E? I can't figure a way to calculate the minimum for each node without iterating over all other nodes to get $$$d_{new}[v]$$$
Its a somewhat advanced DP optimisation trick that allows you to optimise dp of the type $$$dp[i] = max_{j<i} dp[j] + cost(j, i)$$$ from $$$O(n^2)$$$ to $$$O(n log(n))$$$ by looking at each of the previously computed DP values as lines with decreasing slopes. You can find tutorial videos online, this is where I personally learned it
You can also use Li Chao tree (it is just advanced segment tree) Both are data structures that allows you to find minimum/maximum of linear functions' values in O(log(n))
For D, another solution is to simply build the answer from left to right, choosing the minimum value of $$$a_i$$$ each time.
To do this, first we need to restrict which bit of each $$$a_i$$$ can be $$$1$$$. This can easily be done by looping through all the condition $$$(i, j, x)$$$:
Let call $$$allowed_i$$$ the number that has all allowed 1-bit of $$$a_i$$$, then we can see that $$$a_i = allowed_i$$$ is a solution to the conditions, and for all solution, $$$a_i$$$ is a submask of $$$allowed_i$$$.
Then we can loop from $$$1$$$ to $$$n$$$ and construct $$$a_i$$$.
For $$$a_1$$$, we want to make it as small as possible, which mean we want each bit to be $$$0$$$, if possible. We can loop through all the condition $$$(1, j, x)$$$ to check which bit of $$$a_1$$$ must be $$$1$$$. Simply, if a bit is $$$1$$$ in $$$x$$$, but $$$0$$$ in $$$allowed_j$$$, then that bit must be $$$1$$$ in $$$a_1$$$.
It's easy to see that after this process, the best $$$a_1$$$ is just all the forced bits. We can then loop over the conditions $$$(1, j, x)$$$ and force the $$$1$$$ bits on $$$a_j$$$. Just repeat this to get the answer.
You can see my implementation here: 169201529. (Please excuse the weird syntax, I'm experimenting with it).
My implementation is $$$O(n + mlog(m))$$$ due to sorting the initial conditions, but $$$O(n + m)$$$ is achievable as we can do the work for all bits at once in this solution.
Submitted same thing, but with O(n+m) complexity: 169137143
The code now gives WA on newer tests: 169199626
I think you need to handle $$$l = r$$$ cases.
Updated.
I thought it would be a problem at some point during the contest, but then I forgot about it. Because I got AC, I thought it wasn't necessary and the thing will handle itself somehow.
glad to see that REDs also think this way.
Hello sir, I think I use the same solution with you, but why I get WA on test $$$4$$$?
My submission: 169330231
Take a look at Ticket 16079 from CF Stress for a counter example.
Hello sir, can you help me with my solution?: 169535486 Thank in advance!
Take a look at Ticket 16085 from CF Stress for a counter example.
Accepted!! TYSM <3 <3 <3
Hello! Could you please tell the reason for contest extended? As for me, nothing was wrong, so I'm just curious. Thanks!
During contest many contestants expirienced issues with Bad Gateway
мы не можем найти лексикографически меньшее решение глобально.
Тут наверное "не" лишнее.Спасибо, исправил
In problem C, Can Somebody explain why to add number of segments in initial answer? i.e After adding the number of subsegments, we get the answer: 6⋅72=21,21+14=35.
consider any subarray with no joints ,the answer will be one; if there are x joints in a subarray, the beauty value is actually x+1; so the number 21 that you see is actually number of segments when we consider them without joints and the we add 14 to compensate for all the joints that could be considered;
Video Solution for Problem C and Problem D.
Hello, Can someone please explain why this failed (Problem B)? 169134990
Your solution failed because: 1. The lower bound for s would be b * k (handled properly) 2. The upper bound for s would be b * k + n * (k — 1) (your code does not handle this properly).
As, after setting first element to b * k, you can still add k — 1 to each element of the array.
Counter Test Case: 1 2 3 1 6
Correct Answer: (5, 1) or (4, 2) Your Code output: -1
Hi, anybody can explain, why my solution is wrong? WA test 4 https://codeforces.me/contest/1715/submission/169168903
Hi! It seems like you forgot that if the ith bit of (a | b) is equal to 0, then the ith bits of both a and b must be equal to zero.
An alternative randomized solution for Problem F:
Disclaimer: My solution fails on test 65, but I think it is probably an implementation error. Please correct me if this solution is just completely wrong.
The basic idea is to draw a lot of rectangles of the width of the field. Draw the first one at $$$y=0$$$ with height $$$1 \cdot \varepsilon$$$. Draw the next one at $$$y=1 + \varepsilon$$$ with height $$$2 \cdot \varepsilon$$$, and so on, each one exactly $$$1$$$ apart and $$$1 \cdot \varepsilon$$$ taller. We choose $$$\varepsilon$$$ as a very small number.
Since we have to draw one polygon we can just connect all rectangles on one side.
The square can only intersect one rectangle since they are each $$$1$$$ apart. We don't want any rectangle to only partially intersect with the square, so we offset everything by a random number between 0 and 1. This makes a partial intersection very unlikely since the height of our rectangles is very small.
With the answer to our query we can determine which rectangle the square intersects with and we know the $$$y$$$-coordinate is within the interval $$$[y_{rectangle}-1, y_{rectangle}]$$$. To determine the exact coordinate we can just query this interval and calculate $$$y$$$ with the intersection area.
We can repeat this for $$$x$$$ to get the answer in
Unable to parse markup [type=CF_MATHJAX]
queries.My solution is similar to yours. But I chose to randomly set a small value for the width of each rectangle, and fixed the interval between each rectangle to 1.
It passed all the test points. Here it is.169490864
I'm so sorry that I am poor in English.
Can anybody tell why my solution for D doesn't pass? It has same complexity. O((n + m) * log(x)).
Here is solution: 169156511
I have not gone through your code, but I can tell you the Test case where it fails Counter Test Case: 2 2 1 2 7 2 2 6
Correct Answer: 1 6 Your code output: 0 6
I hope this would help you :)
Ok. Thanks so much.
В задаче С если ее делать на питоне, в претесте 2 есть тест который выдает TL на абсолютно верный код в котором ввод делается через input(), если считывать через sys.stdin.readline(), то тест проходится. Кто нибудь подскажет это можно как то отаппелировать? А то выглядит как вполне себе некорректный тест и обидно жесть как, 1.5 часа на задачу потратил. К слову все решения этой задачи на питоне сделаны только через sys.stdin.readline()
Вот пруфы: неверное решение с input(): https://codeforces.me/contest/1715/submission/169157450 такое же но с sys.stdin.readline(): https://codeforces.me/contest/1715/submission/169171912
Тест корректный. А стандартный ввод в питоне медленный. Интересующее вас явление можно найти в интернете по запросу "fast io python". Вот пример одной из неплохих статей, которые можно найти вышеописанным способом: https://www.geeksforgeeks.org/python-input-methods-competitive-programming/
sys.stdin.readline()
действительно является более быстрым способом считывания, поэтому ваш код и стал проходить.The evolution of $$$Div2$$$ $$$E$$$
May I take the picture away?
Sure.
can someone tell the rating of the C problem ?
I guess somewhere around 1700...
ok thanks, it is harder than the usual Div2 C problems
Agree.I felt the same XD
Excuse me, but I'm just curious about the meaning of "XD".
see the XD by rotating your device, it is text form of laughing emoji (this one)
Similar to ;) or :)
I think C was reasonable for Div 2 since the only major (intellectually) hard part was figuring out how to compute the cost at the start. Transitions between queries were really simple (albeit long) and didn't require much thinking.
Oh no! I realized the solution of prob.F during the contest, but is only cost 2 operations, so i didn't dare to write it :(
Oh no! I got the solution of F during the contest, but it only cost 2 steps.So I didn't dare to write:(
Спасибо за отличный раунд! Последняя задача очень понравилась.
A solution I thought of for E was to use a segment tree, what you would do is take the old distance and add $$$i^2$$$ to each $$$a_i$$$, doing that and taking the minimum of the array gives the answer for $$$i = 0$$$, then for moving forward from $$$i-1$$$ to $$$i$$$, you add the AP -1,-3,-5.. To the suffix and ...5,3,1 to the prefix — essentially adjusting the square terms we added. For this we of course need a segment tree that can add an AP to a range and take the minimum of all elements, can anyone confirm if that's possible? If it is can you point me to some resource?
Problem D video editorial
D does not require any graph theory knowledge at all.
Initially, there are $$$30n$$$ unknown bits.
We can do a first pass over the queries to find all bits $$$p$$$ and $$$q$$$ such that $$$p \mid q = 0$$$, which means $$$p = q = 0$$$. These are the only bits that must be 0 in order to satisfy the statements (you can hypothetically set all remaining bits to 1 and this will satisfy the statements, but likely will not be lexicographically least).
Then we can do a second pass over the queries to find all bits $$$p$$$ such that $$$p \mid 0 = 1$$$ or $$$p \mid p = 1$$$, which means $$$p = 1$$$. The former can arise due to forced 0 bits from the first pass, while the latter can arise from statements where $$$i = j$$$. These are the only bits that must be 1 in order to satisfy the constraints (though you can't simply turn all remaining bits into 0 this time, since our remaining equations have the form $$$p \mid q = 1$$$).
With the fixed bits out of the way, we can greedily clear all non-fixed bits of $$$a_1$$$ to 0. If any of these bits were involved in an equation of the form $$$p \mid q = 1$$$, then the other bit in the equation becomes fixed to 1 to satisfy it. We can then repeat for $$$a_2$$$ and so on.
Runtime: $$$O(m + n)$$$, with a constant 30 iterations for everything.
My Submission: 169185957 (I checked for $$$i = j$$$ and $$$p \mid q = 0$$$ while reading the statements)
E is trash
No
About C, It confuses me that where n*(n+1)/2(in the tutorial is 6*7/2)comes from?
In my opinion, it is easier to have an initial array filled with the same number. The initial answer is $$$n \cdot (n+1)/2$$$ since that is the number of subarrays, and each subarray will have an awesomeness of 1. After that, we only have to know how to handle the changes after each operation.
Thanks!I think I get that.
when i looked at my submission after contest, i was surprised when i saw
wrong answer Statement not true: (i, j, x) = (78387, 31267, 38016256)
after that i used
assert
to check if the limit on every bit is satisfied. to my surprise, theassert
doesn't happen.can anyone tell me why? the submission id is 169192815
There are $$$q$$$ statements, but your solution reads $$$n$$$ statements only.
ohhhhhh thanks!!
when i noticed it, i really laughed out very loud
In problem E, could anyone explain the Dijkstra part mentioned in the editorial? How to transfer from "ending with air travel" to "ending with a usual edge"?
My solution of E:
Let's just use Dijkstra algorithm with only roads. Now repeat next thing k times:
For each v:
dp[new_layer][v] = min(dp[previous_layer][v], minimum_of(cost_of_flight + dp[previous_layer][from]))
Run Dijkstra on updated distances
Answer for vertex i after k repeats is dp[k][i]
Submission using Li Chao tree for finding minimum_of(): 169168040
What does it mean to "Run Dijkstra on updated distances"?
How is it different from normal Dijkstra?
It is not any different. You have some precounted distances, use them instead of INF you use usually and run usual Dijkstra
Great contest! I like A,C and F personally.
The system tests of problem
D
are too weak. Will it be retested?I used a slightly different approach to D that didn't require a seperate pass for each bit:
This gives each vertex its smallest possible value subject to the values given to previous vertexes, so gives the lexically smallest possible sequence of values.
See my solution 169149168
I think one could create a similar solution without creating a graph by doing two passes through the data, which might be more efficient.
My last comment is wrong. On the second pass one needs to go through the array values (vertexes) in order, and to know the final values of all lower numbered adjacent vertexes before calculating the value of current vertex, so this needs full adjacency information (i.e a graph).
"С" прикольная задача, но я не понимаю, как у решивших вообще появилась такая идея решения? Что их сподвигло на конкретно это решение? Объяснение понять-то не так просто, а кто-то смог это ещё и придумать.
The time complexity between 169232632 and 169236193 is the same. The only difference is I scanned in increasing order instead of decreasing order. I wonder whether it is a trick to cut down time.
This solution is easy for problem A.
... https://codeforces.me/contest/1715/submission/169123715
which topic this problem belongs to ? as i want to learn more about it to solve similar problems
No topic
Greedy and Math
In problem E,
I'm facing a weird issue, when I initialize the distance to all the arrays with >= 1e14, it gives WA on test case = 37, otherwise, it passed all the test cases.
https://codeforces.me/contest/1715/submission/169246634
https://codeforces.me/contest/1715/submission/169246972
Can someone help me?
All that I'm changing between the two submissions is
for(int i=2;i<=n;i++) dist[i] = ll(1e14);
[Removed, as it was an in invalid test case].
The test you provided isn't valid because $$$k$$$ must be at least $$$1$$$. In fact, when $$$k$$$ is at least $$$1$$$, taking a direct flight from $$$1$$$ to $$$n$$$ is always an option, so the answer is bounded by $$$(n - 1)^2 < 10^{10}$$$.
My guess is that you overflow in your
HullDynamic
class.k
s andb
s can both overflow int, and so multiplication might overflow long long:(x->b - y->b) * (z->m - y->m)
UPD: Changed
long long
s toint128
in your HullDynamic class, AC now: 169286182Thanks mate.
Why in authors code of C.Monoblock, they used (n — (i + 1) + 1) instead of (n-i)? As both will give same answer. Why to use (n — (i + 1) + 1). (In for loop)
for our understanding...
What's that in C++ code for E?
Can anyone help me find out why my solution didn't pass for D ?
Here's my solution: for each index 1<= i <=n, let's find the bits that must be set to zero. Now let's iterate over the array starting from the last element, for each element we will only consider the statement that include another element with smaller index. For each statement that include that element, let's set to 1 all of the bits that are set to 1 in the OR value and can be set to 1 in the current index, the other bits will be set to 1 in the other element since we can't set them in the current one.
Here is a link to my submission: https://codeforces.me/contest/1715/submission/169171341
Any help will be more than appreciated.
Simple counter:
Your code gives 0 1 1, answer should be 0 1 0.
Oh I see where I went wrong, thank you !
Problem F: Life will be harder if the query polygon must have all of its points lying inside the field. (This is the problem statement came from my misunderstood :)).
rockstar_an is the best, thanks to him I'm an Expert.
PS : He is my dad :)
Thanks my son.
Best father-son duo. Tears :')
Best duo.
Problem F is brilliant! Liked it very much :)
Can anyone help me find out why my solution didn't pass for D ?
I think I have written as what have been talked in blog. I have tried to fix it, but I failed.
My submission:169346279
Take a look at Ticket 16078 from CF Stress for a counter example.
Thanks.
Can someone tell me why my code for problem D is failing? here's the code: https://codeforces.me/contest/1715/submission/169397612
Take a look at Ticket 16081 from CF Stress for a counter example.
yea I'm such an idiot it should be bfs not dfs lol, thanks for the test :) now I got AC thank God.
I disagree with Advice #0. You should always consider risk of wasting time on implementation of solution. And thinking about proof and trying to prove may save you from that.
For those who 1715E - Long Way Home for some reason don't understand why this thing can be applied here: within min first square component may be considered as parameter and second square term can be extracted from min because it's being constant in query.
Could anyone help me find why this submission https://codeforces.me/contest/1715/submission/169450718 which is
O(32(m+n))
gets TLE but https://codeforces.me/contest/1715/submission/169452067 which could beO(32 * 32(m+n))
passes? The only difference is that I changed from a two-dimension vector to one-dimension vector, where bit information are added in edges instead of one-bit-one-graph. I have been thinking for the whole night. Thx...In author solution for problem E why is it: while (ll.size() >= 2 && l.intersect(ll[ll.size() — 2]) <= x.back())
and not: while (ll.size() >= 2 && l.intersect(ll[ll.size() — 2]) >= x.back())
won't the authors solution remove lines from the Convex Hull that actualy need to be in it.
Figured it out.. brain fart
We are searching for Min not Max .
Why does my solution for Problem D give TLE, pls someone explain.172482735
Interestingly, D has similar idea to https://codeforces.me/problemset/problem/1594/D, but you have to do it 30 times
I solved problem C with segtree
https://codeforces.me/contest/1715/submission/215391566
I solved a harder problem actually, I can query any segment and find its required value.
There is a small typo in your template, it's "WEIRD" not "WIERD". Please fix it as it might cause denial of judgement verdicts.
Can anyone please tell me why this solution for D gives TLE, even though the number of operations would be about 1.2e7?
https://codeforces.me/contest/1715/submission/285557915