1547A - Shortest Path with Obstacle
Idea: MikeMirzayanov
Tutorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
vector<int> a(2), b(2), f(2);
cin >> a[0] >> a[1];
cin >> b[0] >> b[1];
cin >> f[0] >> f[1];
int ans = abs(a[0] - b[0]) + abs(a[1] - b[1]);
if ((a[0] == b[0] && a[0] == f[0] && min(a[1], b[1]) < f[1] && f[1] < max(a[1], b[1]))
|| (a[1] == b[1] && a[1] == f[1] && min(a[0], b[0]) < f[0] && f[0] < max(a[0], b[0])))
ans += 2;
cout << ans << endl;
}
}
Idea: MikeMirzayanov
Tutorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
string s;
cin >> s;
size_t L = s.find('a');
if (L == string::npos) {
cout << "NO" << endl;
continue;
}
size_t n = s.length(), R = L;
bool yes = true;
for (size_t i = 1; i < n; i++) {
size_t pos = s.find(char('a' + i));
if (pos == string::npos || (pos != L - 1 && pos != R + 1)) {
yes = false;
break;
} else {
L = min(L, pos);
R = max(R, pos);
}
}
cout << (yes ? "YES" : "NO") << endl;
}
}
Idea: geranazavr555, MikeMirzayanov
Tutorial
Tutorial is loading...
Solution
#include <iostream>
#include <vector>
typedef std::vector<int> vi;
int main() {
int t;
std::cin >> t;
while (t--) {
int k, n, m;
std::cin >> k >> n >> m;
vi a(n), b(m);
for (int i = 0; i < n; i++)
std::cin >> a[i];
for (int i = 0; i < m; i++)
std::cin >> b[i];
int pos1 = 0, pos2 = 0;
vi res;
bool ok = true;
while (pos1 != n || pos2 != m) {
if (pos1 != n && a[pos1] == 0) {
res.push_back(0);
k++;
pos1++;
} else if (pos2 != m && b[pos2] == 0) {
res.push_back(0);
k++;
pos2++;
} else if (pos1 != n && a[pos1] <= k) {
res.push_back(a[pos1++]);
} else if (pos2 != m && b[pos2] <= k) {
res.push_back(b[pos2++]);
} else {
std::cout << -1 << '\n';
ok = false;
break;
}
}
if (ok) {
for (int cur : res)
std::cout << cur << ' ';
std::cout << std::endl;
}
}
return 0;
}
Idea: doreshnikov
Tutorial
Tutorial is loading...
Solution
def f(x, y):
return x & ~y
t = int(input())
for tt in range(t):
n = int(input())
a = list(map(int, input().split()))
ans = [0] * n
for i in range(1, n):
ans[i] = f(ans[i - 1] ^ a[i - 1], a[i])
print(" ".join(map(str, ans)))
Idea: geranazavr555, MikeMirzayanov
Tutorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n, k;
cin >> n >> k;
vector<int> a(k);
forn(i, k)
cin >> a[i];
vector<int> t(k);
forn(i, k)
cin >> t[i];
vector<long long> c(n, INT_MAX);
forn(i, k)
c[a[i] - 1] = t[i];
long long p;
vector<long long> L(n, INT_MAX);
p = INT_MAX;
forn(i, n) {
p = min(p + 1, c[i]);
L[i] = p;
}
vector<long long> R(n, INT_MAX);
p = INT_MAX;
for (int i = n - 1; i >= 0; i--) {
p = min(p + 1, c[i]);
R[i] = p;
}
forn(i, n)
cout << min(L[i], R[i]) << " ";
cout << endl;
}
}
1547F - Array Stabilization (GCD version)
Idea: doreshnikov
Tutorial
Tutorial is loading...
Solution
#include <iostream>
#include <vector>
#include <set>
using namespace std;
const unsigned int MAX_A = 1'000'000;
vector<unsigned int> sieve(MAX_A + 1);
vector<unsigned int> prime;
unsigned int gcd(unsigned int a, unsigned int b) {
return b == 0 ? a : gcd(b, a % b);
}
unsigned int solve() {
unsigned int n;
cin >> n;
vector<unsigned int> a(n);
for (unsigned int i = 0; i < n; i++) {
cin >> a[i];
}
unsigned int common = a[0];
vector<set<unsigned int>> facts(n);
for (unsigned int i = 1; i < n; i++) {
common = gcd(common, a[i]);
}
for (unsigned int i = 0; i < n; i++) {
unsigned int t = a[i] / common;
while (t != 1) {
facts[i].insert(sieve[t]);
t /= sieve[t];
}
}
unsigned int answer = 0;
for (unsigned int i = 0; i < n; i++) {
for (unsigned int p : facts[i]) {
int l = (i + n - 1) % n, r = i;
unsigned int cnt = 0;
while (facts[l].count(p) > 0) {
facts[l].erase(p);
l--; cnt++;
if (l < 0) {
l = n - 1;
}
}
while (facts[r].count(p) > 0) {
if (r != i) {
facts[r].erase(p);
}
++r %= n; cnt++;
}
answer = max(answer, cnt);
}
facts[i].clear();
}
return answer;
}
int main() {
sieve[1] = 1;
for (unsigned int i = 2; i <= MAX_A; i++) {
if (sieve[i] == 0) {
sieve[i] = i;
prime.push_back(i);
}
for (unsigned int j = 0; j < prime.size() && prime[j] <= sieve[i] && i * prime[j] <= MAX_A; j++) {
sieve[i * prime[j]] = prime[j];
}
}
unsigned int t;
cin >> t;
for (unsigned int i = 0; i < t; i++) {
cout << solve() << '\n';
}
}
Idea: MikeMirzayanov
Tutorial
Tutorial is loading...
Solution
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int n;
vector<vector<int>> g;
set<int> s[2];
void dfs(int u, vector<int>& color, bool use_s) {
color[u] = 1;
for (int v: g[u])
if (color[v] == 0)
dfs(v, color, use_s);
else if (use_s)
s[color[v] - 1].insert(v);
color[u] = 2;
}
int main() {
int t;
cin >> t;
forn(tt, t) {
int m;
cin >> n >> m;
g = vector<vector<int>>(n);
forn(i, 2)
s[i] = set<int>();
forn(i, m) {
int x, y;
cin >> x >> y;
x--, y--;
g[x].push_back(y);
}
vector<int> color = vector<int>(n);
dfs(0, color, true);
vector<vector<int>> c(2, vector<int>(n));
forn(i, 2)
for (auto u: s[i])
dfs(u, c[i], false);
forn(i, n) {
int ans = 0;
if (color[i] != 0) {
ans = 1;
if (c[0][i])
ans = -1;
else if (c[1][i])
ans = 2;
}
cout << ans << " ";
}
cout << endl;
}
}
E was a wonderful problem to solve, love it!
Can u explain e?
My solution differs from the editorial.
Let's start with the following idea: if we shift a cell righter by 1, we get closer to the conditioners on the right side and get further from the conditioners on the left side.
What this means is that we can precount the values for the very first cell with the given formula, and then we will have to see where do the air conditioners belong for the current cell, either on the right side or the left one, and change their current distance by the same value.
I hope you're familiar with priority queues or at least sets, where we will keep pairs of values: the first will be the temperature value(not the initial one, but the one we've precounted with the formula for the first cell) and the second will be the position of the air conditioner on the line; this will give us the minimum value instantly.
We will have to use two sets: one is for the left side, the other is for the right side. At first, all the conditioners obviously belong on the right side, so you should fill the right set.
The loop from 0 to n — 1 is where the magic happens. We should take the minimum conditioner off top the right set and see if it is an impostor and should have been already swapped to the left side, because its position is smaller than the position for our current cell; if it has to be swapped to the left side, then we should delete it from the right set, update the temperature value for its pair, which will become its initial value + 1 — i, and insert that to the left set(if you're struggling with how to get the initial value, you can use map, where the key would be the conditioner's position and the value would be the index in the array of initial values). After we've done that, we can be sure that the conditioners do belong to the right sets.
As we've assumed that we get closer to the right conditioners and further from the left ones, this means that we can find the minimum value as
This would give us the complexity of O(n + k * log(k)). Here's my solution with priority queues.
I probably explained it badly, you might also want to see Colin Galen's solution(1:42:52), which is the same as in the editorial and is quite good.
Hello, I think I came up an idea like you after the contest end. But my code got TLE. Can you take a look? 122107507
Fixed: 122137899
F and G were absolute gold. Thanks for the set!
yep, G was also my fav and most painful too haha.
The number of accepted solutions increased gradual way.
Proves that Level of question increased in a very uniform way. Loved this !!!
do you have discord server or group that you discuss i want to connect with you and want to learn
I am a pupil bruh, not much to teach anyway
I can give you advice that after every contest, watch upsolving videos on youtube and if they use a concept you are not aware of, go watch tutorial series of that concept
And of course, Keep practicing
Fast editorial!
Wow, I really liked this contest, not just because I am expected to gain 127 points.
A -> well, it's problem A.
B -> nice, introductory 2 pointer
C -> this took me a while because I was chasing down the wrong rabbithole
D -> interesting bit problem
E -> nice, but easy, problem
F -> nice segment tree
G -> couldn't solve
Can you explain how to solve F using segment tree
Let's imagine our array in stages. For convenience, I duplicated my array just to deal with the cyclic nature of the problem.
$$$a_1, a_2, a_3, \dots a_n$$$
$$$\gcd(a_1,a_2), \gcd(a_2, a_3), \dots \gcd(a_n, a_{n + 1} )$$$
$$$\gcd(a_1,a_2, a_3), \gcd(a_2, a_3, a_4), \dots \gcd(a_n, a_{n + 1}, a_{n + 2})$$$
etc
So let's binary search on the answer. Say, we are wondering if the answer of 3 is possible. Then, we want to ensure that $$$\gcd(a_1,a_2, a_3) = \gcd(a_2, a_3, a_4) = \dots = \gcd(a_n, a_{n + 1}, a_{n + 2})$$$. We can check this using a segment tree with range gcd queries. Since we do a binary search, we have a final of $$$\mathcal{O}(N \log N \log N \log (\max(A_i ))$$$
cool
Actually the time complexity is O(N"LogN*LogN*Log(Max(a[i])) , N*LogN for segment tree , Log N for binary search , and Log Max(A[i]) for GCD function .
oops, yes, my bad
Time complexity is $$$O(N\log{N}(\log{N} + \log{MAX}))$$$, only two log factors.
If you take gcd $$$x$$$ times, time complexity is $$$O(x + \log{MAX})$$$.
How did you get this equation?
Logarithmic time complexity for the worst case of Euclid gcd algorithm is bounded by sequential Fibonacci numbers and it sounds impossible to guarantee a big count of gcd operations on them in segment tree. Is it that?
Why do you not try the Sparse Table?It can solve this problem in
O(n log n)
Two logs, I suppose.
One for Sparse Table, and one for gcd.
another approach could be to check for every number that after how many steps or how right we'll have to go so that the gcd is 1 (I divided all the numbers by the gcd of the whole array in the start) then we take the max value. we can use seg tree to find the gcd of i to m (mid in binary search) the net complexity would be n*log^2(n)
Hey Olympia, I have tried using the same approach as you have mentioned above. I have done a binary search for each element in the array and then found the first point where the segment of the array will be equal to the gcd of the entire array. I have used range queries( segment tree) for doing so. Here is a link to my submission. Could you please guide me as to where I went wrong. Thank you.
I am quite noob :((, I don't understand why gcd(a1,a2,a3) = gcd(a2,a3,a4) = ... gcd(a(n-2), a(n-1), a(n). Can you explain that.
He is explaining an example where after two steps every element in array will become equal.
(a1,a2,a3) = gcd(a2,a3,a4) = ... gcd(a(n-2), a(n-1), a(n)
is only true for the case when ans=2 or ans=0.
ans= No. of steps.
Can you help why my binary search + segment tree solution is getting a TLE on test4 SUBMISSION :1547F Thank You.
My solution to G.
You can do a basic DFS to find if the answer is 0 or 1 or 2 for every component.
Use Tarjan's SCC algorithm to find all strongly connected components. Do a multisourced BFS from every SCC reachable from 1. Every node reachable by this BFS is a -1.
This solution works in O(N).
Can I use Kosaraju's algo instead of tarjan's SCC algo?
yes of course they're essentially equivalent.
Any Code?
how do you predict your rating change?
Incase you're using chrome, this will help: CF-predictor
It's not very accurate, but good enough to make you happy or sad.
Please, fix the code of F.
Fix this line: const unsigned int MAX_A = 1000'000;
Thank you for D, E and F. Didn't see G.
The code itself is technically correct but it's incorrectly parsed by the code highlighter tool. Will fix it in a few seconds, thank you!
Maybe it is just me who came up with bad solutions (dp for C, dijkstra for E, bfs-based toposort for G), but the implementation was quite painful for most of the problems today. Not something worth coming to Codeforces for :c
you did come up with bad solutions, on C you can do a greedy algorithm (always try to add more lines), on E it's a simple dp where you try to find the best temperature from 1 to i and from i to n (in the end you combine both dp) and on G you can do a dfs and not pass through a guy only if he has infinite paths (you also need to store which vertices you passed through in your dfs), making you only pass through each vertice at most twice
I don't question the fact that my solutions are bad, and I have also read the editorials, but I still think that implementations are unpleasant.
Isn't C greedy? You take from either one as long as you can (need enough 0s). if stuck, no answer.
E can be solved greedily. Start from the coolest AC and update all the cells unless a cell already has a better AC planted on it. Keep doing that for all ACs sorted from coolest to hottest. It can be proved that no cell will be updated more than twice.
Couldn't solve F or G.
Yes it is, but I didn't want to think and proof anything, so just implemented the first idea I got, so dumb
Well, my implementation to all questions are short imo. Well, I'm not too sure as I started CP recently.
i used bfs for E, welcome to the "overthinking" club
hi
I used lazy segment tree on E....I knew it's pretty bad when I started to debug. Edit: I'm surprised that my segment tree solution runs as fast as the linear solution.
I'm not sure how to solve E using Lazy segment tree..
But one can solve the problem using two normal segment tree's itself.
My code: 121978627
Just to confirm, for F, using Sparse Table shouldn't TLE right?
It shouldn't because even Segment trees are passing
Not at all, I have used sparse table and my sol passed within 400ms. You can have a look at my solution if u want.
This round made me want to commit not alive
not sure why, the problems were pretty good
I was being dumb and then got hacked
oh, pretty fair then
Almost greedyforces, upto E. F was a nice problem.
At the end of time I just know how to solve it but too late. Anyway I thing F is great. Great contest. Love!
I used some kind of Dijkstra Algorithm (multi source) to solve E
how ? can you explain
So I push the initial temp to a priority queue, and start processing by the lowest one, supposed it's T. Then I push T+1 to its left and right, and put them in the priority queue
I found a very cool approach in which I first iterated from left to right and store the minimum temperature in the temp list and then from right to left and did the same at last the minimum temperature is stored in the respective position.
Well fonmagnus can you please suggest me how can I do good in contests. It's been 1 and half year since I started and till now I am in Green. I don't know what is happening but eveyone else is just better than me !
What should I do ?
During the contest, I think problem G is a wonderful problem since it's exactly a proper problem for those who just learn strongly connected components to practise.
However, seeing the editorial, I think the G is more wonderful than I have thinked.
please, somebody, tell me... why my solution is wrong for problem B and which test cases it is failing... 121938514
there is a minute error... i.g. some very minute error is present... it failed the 5002nd case which is not visible.
The error seems to come on the string "abcdefghijklmnopqrstuvwxyz", your code gives No as output. I checked your code and it's because of the array declaration int alphabets[25], it should have a size of 26 not 25.
checked this for my code ... It is giving correct output
First, completely unecessary to call him a dickhead for helping you.
Second, you are wrong. In your computer it works because even though you are accessing a higher index than you allocated it doesn't give an error, which can happen sometimes when you're in your local computer, but it will give an error on codeforces and can give an error on some other computer (like brobat's).
The worst part is that that's not the only reason why the code is wrong because you got wrong answer instead of runtime error, so your idea is also wrong
That's not necessary that the idea is wrong, accessing elements out of array bounds can return unexpected values and not RE — and that can cause WA.
As far as i know, in codeforces they actually go out of their way to check if you're accessing the array in bounds and not only give you a runtime error but they also highlight the line where this is happening.
And the idea is wrong, they check where 'a' is and sees if the values increase as they go to the sides. This is not sufficient as "zax" would work but isn't actually a valid string. Also i believe the array they use to track frequencies can hold garbage data but im not sure
I used binary search+ sliding window(with map/unordered_map) but why this code is giving TLE? complexity seems like O(n*factors[a[i]]*log(n*fact[a[i]]) (including map factor)
[submission:link]
There is no need to find the position of 'a' in problem B, we can start checking the values from endpoints of string as well...
I think I have a very easy to understand solution for E: https://codeforces.me/contest/1547/submission/122007085
Iterate over conditioners, and for each go left and right, while you can cool down cells, it gives you O(n+k).
Awesome contest. Where can I find more problems similar to D?
bitmask problem from codeforce you can search in the problemset by tag
I was able to do A,C,D. But I got WA for B. I don't know where I did a mistake.Every test case I tried randomly seems to be fine.
Can someone plz help me with it?
https://codeforces.me/contest/1547/submission/121969497
The same happened to me, dude... I don't know where's the problem... you help me please 121938514 this is my solution... please please help me as soon as you get it
Yeah, sure
i think you just read the problem wrong because i have no idea of what you're checking. Could you elaborate on your idea?
First I'm checking for duplicates and any alphabet whose value is greater than length of string(considering a's value to be 1.If string length is 3 only a,b,c can be there.) and storing the positions of characters.
Now as we build from lowest alphabet, each character can go to right or left of string,i.e it can just be beside previous character or at other extreme(so the gap between to consecutive alphabets would be equal to all the previous letters before these 2 consecutive ones).( abs(mp[i]-mp[i-1])==1 || abs(mp[i]-mp[i-1])==i)
As we're building and checking the gap from lowest pair of consecutive alphabets ,if for all alphabets until length of string ,every condition satisfies then it would be alphabetical string.
Hope this helps :)
Test Cases separated by a line helped a lot while debugging. Please continue doing so.
Pizzeria Queries sends its regards.
Thanks for the Reference!
I used priority queue to solve E.121971913
Am I the only one who used the minimum on the queue to solve the problem F? 121980439
Can you explain your solution, please?
Yes, I usd struct similar to the one described here.
Instead of the minimum, I implemented the gcd function.
Using two pointers and this struct i found longest segment where gcd() not equal to one.
Its length is the solution to the problem.
Thanks for your sharing your solution. Learnt something new.
My own solutions for B, C and E:
B. If we reverse the operations, we'll need to remove letters from the beginning or from the end of the given string. Two pointers (L and R) showed the part of the string that is not removed yet. So I iterated on letters from 'a'+s.length()-1 to 'a' and shifted one of the pointers. That allows to solve this task in O(n), not O(n^2) as in editorial.
C. On each turn, we can take the minimum of a[i] and b[j] — if it's invalid, the other value is invalid as well. So, checks with a[i] == 0 and b[j] == 0 are not needed.
E. Tried to add only "effective" conditioners — conditioners which cool some cells. I sorted the given conditioners by increase of their temperature and iterated over them, checking if some conditioners could be skipped. Then, the answer is affected only with conditioners near the cell (the nearest on left side and the nearest on right side).
121992524
Please provide some hint on where this solution seems to be incorrect.
What does
&& k!=0
mean inif((i<n && a[i]==0 )||(j<m && b[j]==0) && k!=0)
?it was a realy good contest thanks for all setters and testers for make beautiful contest
D was the best and I really liked it =)
Problem: 1547F - Array Stabilization (GCD version) can be solved using two pointers stack trick, which can be learned through EDU "Two Pointer" section. Link: https://codeforces.me/edu/course/2/lesson/9/2, video is called "Segment with Small Spread", my solution: 122018965
Problem E was really interesting!
But I think, there is a small mistake in Editorial. In my opinion, it should be $$$L_{i}=min(L_{i-1}+1,c_{i})$$$ instead of $$$L_{i}=min(L_{i+1}+1,c_{i})$$$
Thanks for contest again!
For problem D, there is a solution using greedy with less thinking, but with a little worse time complexity.
If we treat every integer as a 29 bits binary numbers. To make $$$y$$$ lexicographically minimal, start scan the sequence from position 1, and each time try make $$$y_i$$$ as minimum as possible.
First of all, $$$y_1 = 0$$$.
And then for $$$i > 1$$$, we can let $$$y_i = g(x_i)$$$ first, where $$$g(x_i)$$$ is bitwise-not of $$$x_i$$$. Since by doing this, $$$x_i \oplus y_i$$$ will be all 1's, and this must satisfy the requirement of growing.
After this, we can enumerate every 1 in $$$y_i$$$ from higer position, and change every 1 to 0 if possible.
in problem G, one of the test cases is:
3 2 3 3 2 2
my answer was 1 0 0 expected answer: 1 -1 -1
acc to me, there ate 0 ways to go from vertex 1 to vertex 2 or 3. but expected answer was that there are infinite solutions. Am i missing something? My Solution link
Check it in CF's custom test, your answer is "1 -1 -1 " to this test, which is wrong and the correct answer is "1 0 0". Maybe you've read "Answer" part instead of "Output" part.
AAAh right. Thank you.
Problem E was easier than I thought...
My solution was different, involving Segment Trees (This is an overkill, btw).
I had solved a kind-of-similar problem on CSES. The problem: Pizzeria Queries
The major difference being that there were updates in that problem. However, I went ahead and coded up that solution during the contest. After the contest did I realise how simple and elegant the code for E was.
Anyways, incase someone is interested in the code: 121978627
My solution was even more different — I used Treap. I've thought of Segment tree, but didn't understand, how to account elements only later than
i
in it.USACO guide has explained the solution for Pizzeria Queries pretty well.
The code I implemented is pretty similar to the guide's solution.
Incase you want to understand how to solve it using segment trees, you can look into the solution linked above.
Can someone look at this solution for E. I used bfs for it, but for some reason I got TLE on test 12. Can someone spot a mistake that causes an infinite loop, because it should run in O(n)
Sorry, turned out solution is just shit
F is heck of a problem!!!✨
Hmmm!
A bit different approach to problem F:
Notice, that the number of times
a[i]
changes is small (worst case is log(a[i]), I believe). So if we can do a brute-force solution where we only change the elements that need to be changed, we can getN*log(MaxValue)
complexity.Note, that
a[i]
changes only if it's not a divisor ofa[i+1]
. Let's keep track of segments of elements where $$$a[l] \mathrel{\vdots} a[l+1] \mathrel{\vdots} ... \mathrel{\vdots} a[r]$$$. Only the last element may change after one iteration. It's also pretty straightforward to update the segments after the iteration as well.Code: 122069028 ( I used std::set here, so the complexity is not optimal, you can rewrite it using std::vector).
If you're interested in a video, I explained all the problems on stream, and you can watch at https://youtu.be/QKW3_9RFxDI
is it possible to do binary search on the F sum? like by taking x over 0 to n steps ?
Yeah, you can binary search on the number of operations. Basically, at $$$k$$$ th step $$$a_i$$$ becomes $$$gcd(a_i, ... , a_{(i+k)\%n})$$$. And to calculate gcd fast, you can use binary lifting. Look at my solution 121972800. This is $$$\mathcal{O}(n\cdot log^2 n)$$$ but you can make it faster by combining binary lifting and binary search. Similar to the idea mentioned here.
Problem E was great. Can Problem E be solved using priority_queue ?
148276776 Can anyone please explain, why it is giving WA on test-2?