Problem author: MikeMirzayanov
Editorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
cin >> n;
int last;
cin >> last;
int ans = 0;
for (int i = 1; i < n; i++) {
int nw;
cin >> nw;
int a = min(last, nw), b = max(last, nw);
while (a * 2 < b) {
ans++;
a *= 2;
}
last = nw;
}
cout << ans << "\n";
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
Problem author: MikeMirzayanov
Editorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
int res = 0;
vector<int> cnt(3);
for (int x = 0; x <= 2; x++) {
for (int i = 0; i < n; i++) {
if (a[i] % 3 == x) {
cnt[x]++;
}
}
}
while (*min_element(cnt.begin(), cnt.end()) != n / 3) {
for (int i = 0; i < 3; i++) {
if (cnt[i] > n / 3) {
res++;
cnt[i]--;
cnt[(i + 1) % 3]++;
}
}
}
cout << res << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
Problem author: MikeMirzayanov
Editorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const ll N = 1'000'000'000'000L;
unordered_set<ll> cubes;
void precalc() {
for (ll i = 1; i * i * i <= N; i++) {
cubes.insert(i * i * i);
}
}
void solve() {
ll x;
cin >> x;
for (ll i = 1; i * i * i <= x; i++) {
if (cubes.count(x - i * i * i)) {
cout << "YES\n";
return;
}
}
cout << "NO\n";
}
int main() {
precalc();
int t;
cin >> t;
while (t--) {
solve();
}
}
1490D - Permutation Transformation
Problem author: MikeMirzayanov
Editorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
void build(int l, int r, vector<int> const &a, vector<int> &d, int curD = 0) {
if (r < l) {
return;
}
if (l == r) {
d[l] = curD;
return;
}
int m = l;
for (int i = l + 1; i <= r; i++) {
if (a[m] < a[i]) {
m = i;
}
}
d[m] = curD;
build(l, m - 1, a, d, curD + 1);
build(m + 1, r, a, d, curD + 1);
}
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
vector<int> d(n);
build(0, n - 1, a, d);
for (int x :d) {
cout << x << " ";
}
cout << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
Problem authors: Stepavly, Supermagzzz
Editorial
Tutorial is loading...
Solution
def win(pos : int, a : list):
power = a[pos]
for i in range(len(a)):
if i == pos:
continue
if power < a[i]:
return False
power += a[i]
return True
t = int(input())
while t > 0:
t -= 1
n = int(input())
a = list(map(int, input().split(' ')))
b = a.copy()
a.sort()
l = -1
r = n - 1
while r - l > 1:
m = (l + r) // 2
if (win(m, a)):
r = m
else:
l = m
winIds = []
for i in range(n):
if b[i] >= a[r]:
winIds.append(i + 1)
print(len(winIds))
print(*winIds)
Problem author: MikeMirzayanov
Editorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
map<int, int> cnt;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
cnt[x]++;
}
map<int, int> groupedByCnt;
for (auto[x, y] : cnt) {
groupedByCnt[y]++;
}
int res = n;
int left = 0, right = n, rightCnt = (int) cnt.size();
for (auto[x, y] : groupedByCnt) {
res = min(res, left + right - rightCnt * x);
left += x * y;
right -= x * y;
rightCnt -= y;
}
cout << res << endl;
}
int main() {
int tests;
cin >> tests;
while (tests-- > 0) {
solve();
}
return 0;
}
Problem authors: Stepavly, Supermagzzz, MikeMirzayanov, sodafago
Editorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n, m;
cin >> n >> m;
vector<ll> a(n);
ll allSum = 0;
vector<ll> pref;
vector<int> ind;
int curInd = 0;
for (ll &e : a) {
cin >> e;
allSum += e;
if (pref.empty() || allSum > pref.back()) {
pref.push_back(allSum);
ind.push_back(curInd);
}
curInd++;
}
for (int q = 0; q < m; q++) {
ll x;
cin >> x;
if (pref.back() < x && allSum <= 0) {
cout << -1 << " ";
continue;
}
ll needTimes = 0;
if (pref.back() < x) {
needTimes = (x - pref.back() + allSum - 1) / allSum;
}
x -= needTimes * allSum;
cout << needTimes * n + ind[lower_bound(pref.begin(), pref.end(), x) - pref.begin()] << " ";
}
cout << "\n";
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
Balanced Round with good and Interesting problems !!
Can we use ternary search to solve F?
I think no, in order ternary search to work you would need the cost to be decreasing and then increasing as a function of C (U shape).
But here it's more complicated it's increasing on some of the value which are number of times a given number appears, and decreasing everywhere else
I think you can not use ternary search on integers if there are f(i) == f(i+1).
You can solve it with ternary search if you erase counter duplicates. But then it is not necessary to use ternary search because the size drops to sqrt(n) and it fits in the time limit.
I used ternary search and it passed pretests
I am sure it only passed pretests because no setter considered that someone would try ternary search on a function so potentially far from having a single local minimum. You are lucky nobody hacked any similar-enough solutions during the open hacking phase.
Thanks for the hack, I wasn't pretty sure that it would pass systests I guess I was lucky enough
can anyone please tell me why this code(link )for F gives tle while this code(link) passes? Unordered map is faster on average than map right?
Anti-hash test. Read this
For E maybe the linear solution is find largest i such that prefix_sum[i-1]<v[i]. Then everyone from that index till last can win.
deleted
radix-sort ((:
They do say its linear after sorting
Here is the Linear Solution for E 122427418.
In D, isn't the worst-case time complexity of given solution O(n^2)? Then how will it not give TLE?
$$$n\le 100$$$ so $$$O(n^2)$$$ is enough.
But t<=100, this means at worst case there would be (100*100)^2 which is 10^8?
$$$O(n^2)$$$ is the time complexity for a single run.
There're $$$t$$$ cases, so the total complexity is $$$O(t\cdot n^2)$$$.
$$$100 \times 100^2 =10^6$$$ is enough.
It's $$$t \times n^2 = 100 \times 100 \times 100 = 10^6$$$.
In Problem G Once we change x = x — full_spins*s
How we can be sure that new x will be less than max(pref) and we will be able to find it using lower_bound?
Now we have a new problem, given x, find the first position i in the array, such that pref[i]≥x. This problem can be solved using binary search. If pref is not sorted into the array, that is, there is j, such that pref[j−1]>pref[j], then pref[j] can simply be thrown out of the array (the answer will never be reached on it).
After assigning new value to x = x — full_spins*(sum) we can not be sure that it will be less than max(pref) and above argument is not valid then.
E.X.
a = [1,1,1,1,-2] x = 15
Sol S = 2 full_spins = (15-4)//S = 11/2 = 5
so new x = 15 — 5*2 = 5 and as max(pref) = 4 < 5 we can not find it using lower_bound()
I think full_spins should be ceil instead of floor
You are right
Have you noticed how full_spins is calculated? full_spins = (x — maxPref + sum — 1) / sum, where maxPref is the maximum prefix of the array, and sum is the sum of the entire array. After full_spins turnovers, at least maxPref is suitable for us to cover the entire amount. There is a small error in editorial — you need to divide with rounding up.
Yeah their is mistake in editorial while code is right. I didn't see the code and thought my approach would be wrong which is basically same
I also tried to implement it based on the editorial but didn't get the correct output for the sample. I looked at the solution and I found that ceil was used instead of floor.
So the formula in the editorial should be changed from: ($$$\lfloor \frac{x - \max_{i=0}^{n-1} pref[i]}{S} \rfloor$$$) to ($$$\lceil \frac{x - \max_{i=0}^{n-1} pref[i]}{S} \rceil$$$)
Stepavly Can you please check this and update the editorial accordingly? Thanks
I overlooked the constraints in problem D and ended up with an efficient solution of nlogn. :)
I don't think your solution is n*log n. Take this case, for example, [1, 2, 3, 4] or any sorted array.
I used input from 2e5 and it ran 410ms, 52.67MB
sort array
Here are some video solutions to all of the problems, and a bit of hype around being 1st
Linear solution(after sorting) for E:
Sort players by tokens in ascending order. The player $$$i$$$ can win if $$$a_1+\dots + a_i\ge a_{i+1}$$$ and player $$$i+1$$$ can win(player $$$n$$$ can always win). So we can calculate the prefix sum and iterate from player with max tokens to player with min tokens and this gives us the linear solution.
code: 107566237
Hey Thallium54 I have also done by prefix sum approach by sorting and my code looks similar to you but my code is giving wrong answer on test case 2 , can you please tell me why it is giving wrong answer Code 107641891
You only considered the first half of the winning condition.
thanks got it
i did exactly did this, did not even think about the solution from the editorial, since this was just right there in front of my eyes after realizing what the problem wanted lol
Hey Thallium54, i solve the problem exactly like your approach but i got stuck in the last loop and i know exactly the test case that i got stuck into but i dont know why iterating from the max giving me AC while iterating from minimum giving me WA on 2, i would appreciate your help
WA: 107739869 AC: 107733400
See here, the reason your second code works is that you broke the loop if the winning condition isn't satisfied, thus the later players won't be counted. The editorial also says that winning players form a suffix, that's why you should iterate from the max.
hi, i try nearly the same code as yours, but change a little when sort, then get WA at test 5. sadly, i can't see the wrong case. and when i use a normal sort it passed. so... maybe the order of
a[i].second
does matter the result. but why...i think only tokens matter. or are there other problems. thxYour comparison doesn't establish a "strict weak ordering". See this for more information.
oh, i see. i'd better just use '<'. thx
Recursion Solution for D was very elegant, I wasted a lot of time on coming up with an iterative Solution :(
My Iterative solution for anyone interested.
Can you explain this iterative solution
Editorial has mentioned nlogn solution for problem F. but my O(nlogn) solution got TLE on test case 5 :( Link: https://codeforces.net/contest/1490/submission/107615964
It is O(N^2) I think , TC : when all elements occur only once
Can problem G be solved if the drive only stopped when the sum was exactly $$$x$$$?
I misread the problem statement and while trying to solve it and I got some interesting observations (until I realized my mistake) but I'm not sure they make a solution that always works.
I noticed that for each query we need to get something like $$$k*sum + pref = x$$$, being $$$sum$$$ the sum of all the elements of the array, $$$pref$$$ any prefix of the array (even an empty one), $$$x$$$ the number in each query, and $$$k \geq 0$$$. So we can rewrite it as $$$k = \frac{x-pref}{sum}$$$ and since $$$k$$$ has to be an integer, then $$$x-pref$$$ has to be divisible by $$$sum$$$, i.e. $$$x-pref \equiv 0 \pmod{sum}$$$, so $$$x \equiv pref \pmod{sum}$$$. Knowing this, I can store and sort all the prefixes of the array by having them $$$\mathrm{mod}\ sum$$$, while also keeping the original numbers (for example, by storing the prefix sum in a separate array and the corresponding indices in the sorted array, with pairs of numbers, so then I know both the original value and the index to calculate the number of movements).
Then when answering queries, I only need to get $$$x \pmod{sum}$$$ and find it in the sorted prefix array I calculated before, with binary search, for example. If I can't find it, then it's impossible. Otherwise I can calculate the number of movements retrieving the original value of the prefix I found, and the answer would be I think $$$\lfloor{}\frac{x-pref}{sum}{}\rfloor{}n + prefInd$$$ being $$$prefInd$$$ the index of the chosen prefix. Note that I would have to be careful if $$$x \equiv 0 \pmod{sum}$$$, which in that case we don't sum any prefix index, and even subtract $$$1$$$ from the previous expression as we are looking for the amount of movements (we didn't do this before when having a prefix since if we have the array 0-indexed, we were already considering one movement more from the end back to the start of the array).
Something to note is that I may not have to store all the prefixes from the original array, as they can be both positive and negative. This means I can end up choosing a negative prefix while $$$sum$$$ was positive. To explain this better, let's look at how I'm supposedly getting $$$k$$$. I said $$$k = \frac{x-pref}{sum}$$$. $$$x$$$ is always a positive integer (given by the constraints of the problem), while both $$$sum$$$ and $$$pref$$$ can either be positive or negative. $$$k$$$ has to be non-negative (obviously, we can't make a negative amount of full turns with the drive), so we need to consider some cases:
And I think by processing the queries offline from lower to greater $$$x$$$ (we can sort them beforehand), and also using some data structure like a
set
to add and erase the prefixes, sorted by $$$\mathrm{mod}\ sum$$$, while keeping up with the cases mentioned, it's possible to do it efficiently.Please correct me if I'm wrong, as it's quite probable that I messed up when thinking of this and it's everything wrong. But I thought it was an interesting problem to think of, which derived from a silly mistake in my part.
I too misread and was thinking how it could be solved
Can Someone please explain how is the first optimization in F working, i.e. how are there there are no more than sqrt(n) unique values of C, thanks in advance.
P.S.: I tried to write sqrt(n) in the fashion shown on the Katex website, but didn't see the symbol in the preview, so if someone could help me with that too, it would be great. Thanks in Advance
Cnt cannot have more than root N values Because in worst case you will have count array as 1,2,3,4,5,...X which will lead you to n=X*(X+1)/2 . So X <root N
got it thanks
For G, the number of spins should be ceil instead of floor?
Yess , It should be ceil.
For problem F, just curious, what is the binary search approach? Any explanation or code will be helpful..
107604489 of user MasterMind uses ternary search
bcollet It turns out that my solution doesn't work. thanks to clyring for the hack. here is the graph for the hack where my solution fail. There are several local minimums
upload pic
What exactly is plotted in this graph? The costs I calculated when preparing the hack were
[24, 14, 15, 12]
, tricking your code with the local minimum at $$$C=2$$$. It is possible to create more local minima, but the size $$$n$$$ of such testcases will get rather large fairly quickly.The x-axes represent the value of $$$C$$$. and the y-axes represent the cost (which is the minimum number of elements to remove) based on the hack test data. $$$cc$$$ in my code represent the frequency of frequencies of numbers provided by your hack test data. The function I used is:
$$$[1, 2, 2, 3, 3, 11, 11, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 12, 12, 12, 12]$$$
$$$[cc: [(1, 1), (2, 4), (3, 1), (4, 6)]]$$$
That's what I calculated... and I used your code to calculate it! Now I see the problem: The x-axis on your chart is the parameter
mid
you passed intoget
, which causes out-of-bounds accesses when it is greater than 3, sincecc.size()
is 4.In problem F, complexity of my code is O(nlogn) which is fine according to constraints but it is giving TLE in system testing can anyone please find out the problem. solution link
Use map instead of unordered_map. In case of unordered_map, it can hit worst case complexity (O(n)) in case of collisions. Map will never go beyond log(n), since it implements self-balancing tree. Please correct me if I am wrong.
But in either case complexity will not increase from nlogn...
use map instead of unordered_map because worst case complexity is o(n) my solution was also giving tle but when I used map it got accepted in a given time limit see my solution I have also used binary search. Heuit Invincible06
Use a custom hash function to avoid anti-hash hack. I added one to your code and it passed easily 107711223
Thanks a lot, so should I add it to my template and use whenever i want to use unordered_map, or do i need to change something in struct anytime?
no need to change
Can someone explain how to get the formula for the number of full spins in problem G.
Let us suppose we get maxima as the maximum prefix sum during first spin. Now let's assume we have y full spins and sum[n] is the prefix sum at the end of first spin.
So we should have (y*sum[n] +maxima)>=x. This implies y =((x- maxima +sum[n]- 1)/sum[n]).
.
.
Could anyone please help me as to why my submission gets a TLE for D? I have implemented the same idea during contest. I tried several times to debug but I couldn't :/ I can see that it's because there are 1e6 operations involved at max, there needs to be some optimisation to prevent TLE. But I don't know what exactly to do. My submission: 107614061
You're solving subparts(recursion) inside the loop.Try taking it outside,it'd work then.
These function calls should be outside(after) the loop.
1490D - Трансформация перестановки can be solve in $$$O(n)$$$ time and space complexity using Cartesian tree 107689365
Problem F — Equalize the Array
"you can consider only unique values of C (there are no more than O(n*√n)), and get a solution in O(n*√n)"
I used this approach mentioned in the editorial during the contest and get a TLE in test case 12.
Here is my submission:107609642
Use map instead of unordered_map. Same thing happened with me. Also read this blog
Will someone please attach this editorial to the contest itself? I think my color grants me the power to do so, but haven't tried and don't want to risk making a mess on a public round.
For problem 1490C — Sum of Cubes : In the Editorial's code there is precomputation of the cubes upto 10^9. It means this loop is going to iterate that 10^9 times , then it is supposed to give TLE. Since we are allowed to have only 10*8 operation per sec as per the standards of OJ. Please suggest if I am wrong.
it iterates $$$\sqrt[3]{10^{12}} = 10^4$$$ times.
for-loop constraint is
i * i * i <= N
There is a small bug in the editorial for 1490G - Old Floppy Drive . The formula
needs to be changed to
So that in the first member you have amount of full cycles multiplied by the total sum during the cycle.
for Problem G: for testcase
1
2 2
2 0
1 2
according to me ans should be:[-1 0]
but the query is giving: [0 0]
can someone help me understand where i am going wrong. here is my code:
see the third step in the algorithm, 'sum is at least x'. so when query for the case x=1, the sum=2 will be just ok, and time is 0.
I have a 'problem' with task F.
I use map to count number of occurences of a given number. When i use unordered_map<int,int> I get TLE on test 12( > 2sec). https://codeforces.net/contest/1490/submission/107876739
When I change to map<int,int> my solution takes < 200ms. This means, that unordered_map<int,int> in this case is at least 10 times slower. Why is it so? My previous experience (including performance tests) was, that for unordered_map is not slower than map, especially, if the number of elements is large (as probably in test case 12, where the sequence seems to be arithmetic). https://codeforces.net/contest/1490/submission/107876786
Test case 12: 1 200000 53201 106402 159603 212804 266005 319206 372407 425608 478809 532010 585211 638412 691613 744814 798015 851216 904417 957618 1010819 1064020 ...
Edit: I could have read previous comments before posting this, sorry. Problem solved.
Really liked this contest!
Problem G.
In the full spin calculating step, Why do we have to (x — max(pref[0..n])) before / sum?
Because the pointer could not reach the max(pref[0..n]) at the end, and we will substract more than necessary. The full spin could less than the answer.
Please help me, thank you.
In problem F(equalise the array) i am getting wrong answer at test case 20. I have tried a lot of test cases but i am not able to figure out the problem. Can someone please help me with this. This is my submission 109139946.
Why am I getting TLE? Isn't it O(nlogn) algorithm?
Is it necessary to use
unordered_set
instead ofset
in problem C ??