Идея: BledDest
Разбор
Tutorial is loading...
Решение (Neon)
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int tc;
cin >> tc;
while (tc--) {
string s;
cin >> s;
vector<int> cnt(10);
for (auto c : s) ++cnt[c - '0'];
int mx = *max_element(cnt.begin(), cnt.end());
if (mx == 4) cout << -1;
else if (mx == 3) cout << 6;
else cout << 4;
cout << '\n';
}
}
Идея: BledDest
Разбор
Tutorial is loading...
Решение 1 (adedalic)
fun main() {
repeat(readln().toInt()) {
val n = readln().toLong()
var l = (-1).toLong()
var r = 1e9.toLong()
while (r - l > 1) {
val mid = (l + r) / 2
if (mid * mid >= n)
r = mid
else
l = mid
}
println(r - 1)
}
}
Решение 2 (adedalic)
import kotlin.math.sqrt
fun main() {
repeat(readln().toInt()) {
val n = readln().toLong()
var ans = sqrt(n.toDouble()).toLong()
while (ans * ans > n)
ans--
while (ans * ans < n)
ans++
println(ans - 1)
}
}
Идея: BledDest
Разбор
Tutorial is loading...
Решение (BledDest)
def solve(n, k):
if n == 0:
return []
if k < n:
a = [-1 for i in range(n)]
if k > 0:
a[k - 1] = 200
a[k] = -400
else:
a = solve(n - 1, k - n)
a.append(1000)
return a
t = int(input())
for i in range(t):
n, k = map(int, input().split())
b = solve(n, k)
print(*b)
1809D - Сортировка бинарной строки
Идея: BledDest
Разбор
Tutorial is loading...
Решение (Neon)
#include <bits/stdc++.h>
using namespace std;
const long long pw10 = 1e12;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int tc;
cin >> tc;
while (tc--) {
string s;
cin >> s;
int n = s.size();
int cnt0 = 0, cnt1 = count(s.begin(), s.end(), '1');
long long ans = 1e18;
if (n == 1) ans = 0;
for (int i = 0; i < n - 1; ++i) {
cnt0 += s[i] == '0';
cnt1 -= s[i] == '1';
int k = cnt0 + cnt1 + (s[i] == '1') + (s[i + 1] == '0');
long long cur = (n - k) * (pw10 + 1);
if (s[i] > s[i + 1]) cur += pw10;
ans = min(ans, cur);
}
cout << ans << '\n';
}
}
Идея: BledDest
Разбор
Tutorial is loading...
Решение (awoo)
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int n, a, b;
scanf("%d%d%d", &n, &a, &b);
vector<int> v(n);
forn(i, n) scanf("%d", &v[i]);
vector<vector<int>> ans(a + 1, vector<int>(b + 1));
forn(cd, a + b + 1){
int l = max(0, cd - b), r = min(a, cd);
int sum = 0;
for (int x : v){
sum += x;
l = max({l, sum, cd + sum - b});
r = min({r, a + sum, sum + cd});
}
if (l > r) l = r = max(0, cd - b);
int res = l;
for (int x : v){
if (x > 0)
res -= min({res, x, b - (cd - res)});
else
res += min({cd - res, -x, a - res});
}
forn(c, cd + 1) if (c <= a && cd - c <= b){
ans[c][cd - c] = (c < l ? res : (c > r ? res + r - l : res + c - l));
}
}
forn(i, a + 1){
forn(j, b + 1)
printf("%d ", ans[i][j]);
puts("");
}
return 0;
}
1809F - Путешествие по Берляндии
Идея: BledDest
Разбор (Neon)
Tutorial is loading...
Решение (awoo)
#include<bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
void solve(){
int n, k;
scanf("%d%d", &n, &k);
vector<int> a(n);
forn(i, n) scanf("%d", &a[i]);
vector<int> b(n);
forn(i, n) scanf("%d", &b[i]);
vector<long long> pr(2 * n + 1);
forn(i, 2 * n) pr[i + 1] = pr[i] + a[i % n];
vector<long long> dist(n);
vector<long long> cost(n);
int cnt = 0;
for (int i = 2 * n - 1; i >= 0; --i){
if (i < n){
if (b[i] == 2){
dist[i] = 1;
cost[i] = a[i] * 2;
}
else if (cnt == 0){
dist[i] = 1;
cost[i] = a[i];
}
else{
int j = lower_bound(pr.begin() + i, pr.begin() + i + cnt + 1, pr[i] + k) - pr.begin();
assert(j > i);
dist[i] = j - i;
if (pr[j] - pr[i] <= k)
cost[i] = pr[j] - pr[i];
else
cost[i] = 2 * (pr[j] - pr[i]) - k;
}
}
if (b[i % n] == 2) ++cnt;
else cnt = 0;
}
int pw = 0;
while ((1 << pw) <= n) ++pw;
vector<vector<long long>> distk(pw, dist);
vector<vector<long long>> costk(pw, cost);
for (int j = 1; j < pw; ++j) forn(i, n){
distk[j][i] = distk[j - 1][i] + distk[j - 1][(i + distk[j - 1][i]) % n];
costk[j][i] = costk[j - 1][i] + costk[j - 1][(i + distk[j - 1][i]) % n];
}
forn(i, n){
int pos = i;
long long tot = 0;
long long ans = 0;
for (int j = pw - 1; j >= 0; --j) if (tot + distk[j][pos] <= n){
tot += distk[j][pos];
ans += costk[j][pos];
pos = (pos + distk[j][pos]) % n;
}
if (tot < n) ans += pr[i + n] - pr[i + tot];
printf("%lld ", ans);
}
puts("");
}
int main(){
int tc;
scanf("%d", &tc);
while (tc--) solve();
}
Идея: BledDest
Разбор
Tutorial is loading...
Решение (BledDest)
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y)
{
return ((x + y) % MOD + MOD) % MOD;
}
int mul(int x, int y)
{
return x * 1ll * y % MOD;
}
int binpow(int x, int y)
{
int z = 1;
while(y)
{
if(y % 2 == 1) z = mul(z, x);
x = mul(x, x);
y /= 2;
}
return z;
}
int inv(int x)
{
return binpow(x, MOD - 2);
}
int divide(int x, int y)
{
return mul(x, inv(y));
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
vector<int> a(n);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
reverse(a.begin(), a.end());
vector<int> fact(n + 1);
fact[0] = 1;
for(int i = 1; i <= n; i++)
fact[i] = mul(fact[i - 1], i);
// for each player, we find the first player which doesn't conflict with them
vector<int> first_no_conflict(n);
for(int i = 0; i < n; i++)
{
if(i) first_no_conflict[i] = first_no_conflict[i - 1];
while(first_no_conflict[i] < n && a[first_no_conflict[i]] >= a[i] - k)
first_no_conflict[i]++;
}
vector<int> dp(n + 1);
if(a[0] - a[1] > k) dp[1] = 1;
for(int i = 1; i < n; i++)
{
// first choice: put a[i] on the first position
// then we put all which conflict with a[i] on any position other than 1
int no_of_conflicting = first_no_conflict[i] - i - 1;
// put all conflicting with a[i] on any position other than 1
// the first one chooses from i positions, the second - from i+1 positions, and so on
// so the number of ways is fact[i + no_of_conflicting - 1] / fact[i - 1]
dp[i + no_of_conflicting + 1] = add(dp[i + no_of_conflicting + 1], mul(dp[i], divide(fact[i + no_of_conflicting - 1], fact[i - 1])));
// second choice: put a[i] on any other position
dp[i + 1] = add(dp[i + 1], mul(dp[i], i));
}
printf("%d\n", dp[n]);
}
What is the purpose behind setting limits such that (na + nb + ab) logn solutions fail E?
I have tried to optimize it, i got it down to 2.5s in a mashup with adjusted limits, couldnt get it to pass.
The problem was already quite hard enough without the limits, imo n<=1e3 wud be much better.
Good contest otherwise though, i liked both C and D
If you let $$$n = 1000$$$, squeezing $$$O(nab)$$$ with some constant optimizations into TL feels very probable
That was just an instance, even n = 5000 allows both my solutions (segment tree/bs + sparse) to pass (i think though it might be tight for seg)
Especially sad for us since a slightly different idea and the same complexity passes due to good constant.
My (na + nb)logn solution seemed to pass pretty comfortably: https://codeforces.net/contest/1809/submission/198874838.
Your solution has a completely different idea (and is similiar to the actual idea i guess)
I will explain my solution : If each operation moved the maximum amount it could, the problem was simple, so lets try to simulate each process for a certain starting position till the next time we dont move the maximum amount. This can be done easily with a segment tree.(or bs + sparse table) If we memoize the values, this becomes O(na + nb + ab) logn Reasoning : there are atmost 2*na + 2*nb + ab states because after each operation, because each simulation is run either at a starting position(ab of them) or when atleast one tank is either empty/full (2na + 2nb)
I don’t even know how to optimise my solution more to get it to less than 2 seconds, it’s at 7 seconds mark.
the issue is that it feels that it may pass, so we waste time coding it
Wait, really? $$$10^7$$$ times log operations (also including the fact that this logarithm comes from segment tree, so the constant is big) feels passable in 2 seconds? Can you show any problems where it actually passes under those constraints?
Yeah it is very tight i agree, 1e7 * 2 * log (1000) * segtree constant = 2e8 * segtree constant, so mathematically I didn’t feel like it’d certainly TLE
1) you do not need a segment tree, you can use binary search + sparse table 2) the log factor is a logn, which is around 13, so its about 2.5 * 10^8 complexity, not unreasonable 3) my recursive segment tree runs in 4s which is only twice the TL. If i could write iterative segmemt tree, i am pretty sure it would pass
https://codeforces.net/problemset/problem/1523/H Intended solution complexity : 4e4 * 900 * log in 2s If i am not mistaken thats 3.6e7 log.
I tried every combination for problem C after setting the number 2 and it got accepted. Here is the CODE : 198939113
Your code is not understandable, Could you explain your idea?
Its simple i just take 2 and created an array of just 2 till the no. of positive subarrays in it is <=k then there can be two cases :
1) no. of positive subarrays = k this is the best case so we will just put -1000 on the rest of the places.
2) No. of positive subarrays>k .Then i just removed a 2 then look for a negative element which satisfy the condition no. of positive subarrays=k by brute force.This will have at max = 30*30*1000=9*10^5 operation for the worst case. which is under the time limit.
P.S: i think i just poorly implemented it but yk thats just the first thing which came to my mind and it worked XD
I used a similar strategy (https://codeforces.net/contest/1809/submission/198826221) but you don't need to do a search to work out the negative element. You can simply use:
(k — number of positive subarrays)*2 + 1
My approach https://codeforces.net/contest/1809/submission/250402936
another solution for task B
https://codeforces.net/contest/1809/submission/198975521
nic3
Can someone help me prove my solution for C? I thought my solution was an elegant linear time solution but it did rely on one claim I was only probably sure was true. My claim was that: for any number 0 <= k <= n*(n+1)/2, and with access to the numbers 1...n, we can always greedily choose the largest n that fits and add it to the sum until we reach k. If this claim is true, then we can solve C using the following strategy:
Initialize an array of length n, all 0s
If we "set" index i of the array, then it will create n-i positive subarrays. We set the largest indices that fit into the sum of k.
Now we iterate through the array backwards and set the values such that the set indices make every subarray ahead of them positive and the unset indices make every subarray ahead of them negative.
Solution: 198783142
I didn't prove that we can always make k greedily using the numbers 1...n, but I thought it might be true because it felt similar to the Div 4 G problem.
"If we "set" index i of the array, then it will create n-i positive subarrays". I'm pretty sure this is not true. For example, array 00100 has exactly 5 positive subarrays. However, I think that you probably wanted to say that if I turn on all the bits from 0 to i-1, then turning i on would add exactly n — i — 1 positive subarrays.
Problem E becomes more interesting if instead of requesting all (c,d) pairs we only request q pairs. Limits like n<10^4, a+b<10^18, q<10^6
1809F - Traveling in Berland could be solved in $$$O(n)$$$ by using 2 pointers
We can duplicate $$$a, b$$$, st $$$a[i + n] = a[i]$$$ and $$$b[i + n] = b[i]$$$
Suppose we are solving for $$$k$$$ so our path starts at $$$k$$$ and ends in $$$k + n$$$
For example we have $$$x, y, z, \dots, last$$$ st $$$k \le x \le y \le z \le \dots \le last \le k + n$$$ and $$$b[x] = b[y] = b[z] = \dots = b[last] = 1$$$
We can split path into $$$k \rightarrow x \rightarrow y \rightarrow z \rightarrow \dots \rightarrow last \rightarrow k + n$$$
For points $$$x, y, z, \dots$$$ we can use 2 pointers. For example in point $$$x$$$ we will buy $$$\min(len[x \rightarrow y], limit)$$$ if $$$limit < len[x \rightarrow y]$$$ we will buy more in other points with cost 2
For $$$k \rightarrow x$$$ and $$$last \rightarrow k + n$$$ we can compute naively. Total complxity $$$O(n)$$$ 198830497
Graph explanation of E: (consider for all cases of (c, d) with same value of c+d)
Agree that nO(log n) is overkill.
I used a similar (the same) idea (199142190) — in gas station i with $$$b_i=\$1$$$ (let's call it 1-station) you always fill the minimum of full tank, and fuel required to reach the next station j that is 1-station or j is final.
You could pre-compute the amount you fill (call it $$$w_i$$$) at the 1-station i. Given starting position start, the total you fill at all 1-stations is $$$\sum(w_i, i \in 1-station) - w_j + FilledAtj$$$, here j — is the last 1-station on a journey started at start.
So it is enough to keep track of the last 1-station on a journey and compute filled amount at this station — easy given that the end of journey is at start.
P.S.: Obviously your answer for each journey is 2 * Total Fuel Required — Total Filled At 1-stations.
if anyone solved D using dp, can you pls tell me the approach?
I just memoized all states using DFS. If we are at a position and it is a 1, we can either continue or delete it and incur the cost. There is a third option of swapping with the number in front of it if it is a 0 and we have no other 1's to the left. If we are at a position and it is a 0, we can delete it and incur the cost. If there are no 1's the left, we can either continue or swap it with the number in front of it. The memoization will look like memo[pos][has_0][swapped] for each state
Let $$$dp_{i, j}$$$, be the cheapest way to process the first $$$i$$$ characters of the string with the following states:
You can see the transitions in more detail here: 198854887.
Or without array<int, 2>: 198995188.
How did you come up with the dp states? Any intuition that helped? Thanks.
/* * Use dynamic programming * state dp[c][p] -> cost to make array from c -> n sorted Given [0 — c-1] * sorted * and whether 1 has occured already or not * transition is case by case * if char is 0 or char is 1 * based on p1 we can decide to either remove curr, swap curr, or do nothing * swap is optimal for char 1 with next 0 * so at each index need to maintain what is next 0 for each char 1 * next 0 can be done by iterating in reverse order */
https://codeforces.net/contest/1809/submission/277877896
I actually didn't like the tutorial for task B
It's way too complicated for beginners
O(1) Solution
O(logN) Solution
Try to format the code while commenting.
Otherwise it becomes unreadable, and will result in huge downvotes.
It appeared in order, but after posting it took a random configuration... Don't know why
There is an option while commenting, if you want to write source code.
You can use that.
sqrt() method isn't O(1) . so your O(1) solution is not really O(1).
I solved F after the contest with a solution that is O(n) 198883707, then noticed that each b_i is limited to either 1 or 2. The 1 or 2 constraint is essentially not required and would only slightly simplify the code.
Can you explain your solution?
First detect consecutive sequence of cities with non-descending fuel cost per liter. A round trip started at a city not in the sequence would visit all the cities in order from begin to end. A round trip started at a city within the sequence would visit the suffix cities and later all the prefix cities in the sequence. In either cases, because the fuel price is non-descending, it is always optimal to purchase as much fuel as sufficient to reach the end of the sequence limited to the tank capacity of course.
For each such sequence [B,E], we run DP to compute the pre[] and suf[] array where pre[i] is cost to reach i from B and suf[i] is the cost to reach E+1 from city i. Such computation is O(M) where M is the length of the sequence. I will skip more details to compute the pre and suf array.
Once we have all the individual sequences handled, for each city i, its round trip cost includes the whole cost of all other sequences it does not belong to, plus pre[i] + suf[i]. It takes O(N) to compute the value for all the cities as answer. Overall the complexity is O(N).
Can anyone explain B's given test case? Why is answer for 975461057789971042 987654321? I am sure it should be 987654320.
the answer would have been 987654320 if the input was 975461057789971041 (1 less than the current input)
Use 'sqrtl' to find the square root. The input is of the order 10^18 so sqrt will give precision errors. The exact square root of 975461057789971042 is 987654321.000000000506249999, ceil of that minus 1 is the final answer ~ 987654321.
There are 4 * m points (x, y) that satisfies |x|+|y| = m for m >= 1. The diagram below shows points 4 + 12 = 16 points for m = 1 and 3. The total number of points for m = 1, 3, 5, ..., 2 * k — 1 is 4k^2. For k = 493827161, the value is 975461059765279684 which is greater than 975461057789971042, so the answer should be <= 2k-1 = 987654321.
An illustration that 987654320 won't work: if we use m = 0, 2, 4, 6, ..., 987654320, the total number of points is 1 + 4 * (2 + 4 + ... + 987654320) = 1 + 987654320^2 = 975461055814662401 which is one less than the required 975461055814662402 in your example.
A simple solution for task B is just print " (int) sqrt(n-1)" ;)
your have to define int to long long int.
It works only on C++17.
yupp...it is simple...but how do you come up with that, how am i going to come up with the logic that just
cout<<(int)sqrt(n-1);
that is what the editorial is about.A Solution for B
include <bits/stdc++.h>
using namespace std; int main(){ int t; long long a; cin >> t; while(t--){ cin >> a; a = a — 1; long long res = sqrt(a) / 1; cout << res << endl; } return 0; }
I have two almost similar logic solution for problem B, one is failing while the other one is working.
Failing one- https://codeforces.net/contest/1809/submission/199048077,
Working one- https://codeforces.net/contest/1809/submission/199048367
Could someone help understand what's going wrong here? Also I see that for c++ sqrt(n-1) works while not for JAVA, why is that so?
there are precision errors. in java , the number is converted to double before taking the root. eg — root 25 can be 4.999 and the int of this would be 4 , so we need to add this line while(x * x < n) x++; so if there is any precision error it would be corrected
Another possible solution for D:
Iterating over s from right to left each time we assign our answer the minimum value of 3 + 1 possible estimates and our current answer.
Submission: 199079054
O(1) solution for B:
Solution: If N is a perfect square then the answer is √N — 1 and otherwise it's just √N
198856454
you can just calculate floor(sqrt(N-1))
Yeah, listen to the expert ^^
1809G is similar to 1437F, although the constraint of 1809G is tighter.
In problem D, how do they determine that it is optimal to have at most one delete operation.
Perhaps few person remember that EDU rounds may reuse old problems.
Actually 1809E - Two Tanks is a resemble of an old task OneDimensionalRobot from SRM 608 authored by rng_58.
https://youtu.be/xvyXv1IO7yg
Video sols for A,B,C
F can be solve in O(n) instead of O(nlogn). You can preprocess (not sure how to say it, you get the idea) the prefix and suffix of every position with gas price 2, then calculate the answer of any city with gas price 1.
The difference between different starting points will be: the concecutive price 2 cities that got seperated by the starting position. Just calculate the offset with prefix and suffix then you get the correct answer.
199636012
Is D solvable if it was given a permutation instead of a binary string?
I get Wa5 because of I mul 1e12 and I dont realize it, terribly
in problem D
Can you explain why did this give a WA? I did the same mistake and got AC after using a new variable assigned with $$$1e12$$$.
WA submission : 265403408 AC submission : 265403860
can anyone recommend problems similar to E
Alternate solution for C in O(n): https://codeforces.net/contest/1809/submission/209213026
We realise we can form an array [2, 2, 2, 2, -x, -1000, -1000 ...], -x will depend on the number of good subarrays you have yet to form from [2,2,2,2].
We try our best to form the most good subarrays at the left side, then once we could not do it anymore, we still have some leftover good subarrays to form. We can then set the value of -x to be such that we will form +leftover more good subarrays.
Problem G is totally the same as 1437F - Emotional Fishermen.
Alternate $$$O(n)$$$ solution for problem F:
Firstly, let us divide the city into maximal continuous segments of type-$$$1$$$ and type-$$$2$$$ cities (cities having fuel cost 1 and 2 respectively) by considering the starting city to be $$$1$$$.
Observations:
So for a fixed starting point $$$s$$$, the maximal segments are defined and constant.
For a type-$$$2$$$ segment $$$S$$$, define :
The answer for a set of maximal segments is $$$\sum{a_i}(\text{over all type-1 segments}) + \sum{sub_s + 2(sum_s - sub_s)} (\text{over all type-2 segments})$$$.
Now when we iterate over the starting city $$$s$$$, at most two terms in this summation change on each iteration (corresponding to the type-$$$2$$$ segment we are "splitting" by $$$s$$$), these can easily by fixed in $$$O(1)$$$.
Implementation: link
Simple O(N) solution to problem C: 262967868