Любой массив можно отсортировать не более, чем за $$$\frac{n(n-1)}2$$$ операций. Подумайте либо угадайте, в каком случае понадобится ровно $$$\frac{n(n-1)}2$$$.
#include<iostream>
using namespace std;
int a[1000000+5];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while (t--)
{
int n;
cin>>n;
for (int i=0; i<n; i++)
{
cin>>a[i];
}
bool can=false;
for (int i=1; i<n; i++)
{
if (a[i]>=a[i-1])
{
can=true;
break;
}
}
if (can) cout<<"YES"<<'\n';
else cout<<"NO"<<'\n';
}
}
Придумайте простой критерий, когда a_i & a_j >= a_i ^ a_j
, рассмотрев биты от старшего к младшему. Примените его, чтобы быстро вычислить ответ.
#include<iostream>
#include<vector>
#include<algorithm>
#include<ctime>
#include<random>
using namespace std;
mt19937 rnd(time(NULL));
int a[1000000+5];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while (t--)
{
int n;
cin>>n;
for (int i=0; i<n; i++)
{
cin>>a[i];
}
int64_t ans=0;
for (int j=29; j>=0; j--)
{
int64_t cnt=0;
for (int i=0; i<n; i++)
{
if (a[i]>=(1<<j)&&a[i]<(1<<(j+1)))
{
cnt++;
}
}
ans+=cnt*(cnt-1)/2;
}
cout<<ans<<'\n';
}
}
1420C1 - Армия покемонов (простая версия)
Используйте динамическое программирование.
#include <iostream>
#include <vector>
using namespace std;
inline int64_t calc(const vector<int> &a) {
int n = a.size();
vector<int64_t> d1(n+1), d2(n+1);
d1[0] = -static_cast<int64_t>(1e18);
d2[0] = 0;
for (int i = 0; i < n; ++i) {
d1[i+1] = max(d1[i], d2[i] + a[i]);
d2[i+1] = max(d2[i], d1[i] - a[i]);
}
return max(d1.back(), d2.back());
}
int main() {
ios_base::sync_with_stdio(false);
int t; cin >> t;
while (t--) {
int n, q; cin >> n >> q;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
cout << calc(a) << "\n";
for (int i = 0; i < q; ++i) {
int l, r; cin >> l >> r; --l; --r;
swap(a[l], a[r]);
cout << calc(a) << "\n";
}
}
return 0;
}
1420C2 - Армия покемонов (сложная версия)
Здесь динамическое программирование не сработает. Подумайте, выгодно ли брать в ответ что-либо, кроме локальных минимумов и максимумов.
import java.io.*;
import java.util.*;
public class C2_Java {
int[] a;
int n;
long ans;
void add(int i, int sign) {
if (i == 0 || i == n+1) return;
if (a[i-1] < a[i] && a[i] > a[i+1]) ans += sign * a[i];
if (a[i-1] > a[i] && a[i] < a[i+1]) ans -= sign * a[i];
}
void addTwo(int l, int r, int sign) {
if (l == r) return;
if (l+1 == r) {
add(l-1, sign);
add(l, sign);
add(r, sign);
add(r+1, sign);
return;
}
add(l-1, sign);
add(l, sign);
add(l+1, sign);
if (l+2 != r) add(r-1, sign);
add(r, sign);
add(r+1, sign);
}
public void run() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer tok = new StringTokenizer(in.readLine());
int t = Integer.parseInt(tok.nextToken());
while (t --> 0) {
tok = new StringTokenizer(in.readLine());
n = Integer.parseInt(tok.nextToken());
int q = Integer.parseInt(tok.nextToken());
a = new int[n + 2];
tok = new StringTokenizer(in.readLine());
for (int i = 1; i <= n; ++i) {
a[i] = Integer.parseInt(tok.nextToken());
}
a[0] = -1;
a[n+1] = -1;
ans = 0;
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= n; ++i) {
if (a[i-1] < a[i] && a[i] > a[i+1]) ans += a[i];
if (a[i-1] > a[i] && a[i] < a[i+1]) ans -= a[i];
}
builder.append(ans).append("\n");
while (q --> 0) {
tok = new StringTokenizer(in.readLine());
int l = Integer.parseInt(tok.nextToken());
int r = Integer.parseInt(tok.nextToken());
if (l == r) {
builder.append(ans).append("\n");
continue;
}
addTwo(l, r, -1);
int tmp = a[l];
a[l] = a[r];
a[r] = tmp;
addTwo(l, r, +1);
builder.append(ans).append("\n");
}
out.write(builder.toString());
}
in.close();
out.close();
}
public static void main(String[] args) throws IOException {
(new C2_Java()).run();
}
}
#include<iostream>
using namespace std;
#define int long long
int a[1000000+5];
int n;
int ans=0;
inline void insert(int i)
{
if (i==0||i==n+1) return;
if (a[i-1]<a[i]&&a[i]>a[i+1]) ans+=a[i];
if (a[i-1]>a[i]&&a[i]<a[i+1]) ans-=a[i];
}
inline void erase(int i)
{
if (i==0||i==n+1) return;
if (a[i-1]<a[i]&&a[i]>a[i+1]) ans-=a[i];
if (a[i-1]>a[i]&&a[i]<a[i+1]) ans+=a[i];
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while (t--)
{
int q;
cin>>n>>q;
for (int i=1; i<=n; i++)
{
cin>>a[i];
}
a[0]=-1;
a[n+1]=-1;
ans=0;
for (int i=1; i<=n; i++)
{
if (a[i-1]<a[i]&&a[i]>a[i+1]) ans+=a[i];
if (a[i-1]>a[i]&&a[i]<a[i+1]) ans-=a[i];
}
cout<<ans<<'\n';
while (q--)
{
int l,r;
cin>>l>>r;
erase(l-1);
erase(l);
erase(l+1);
if (l!=r)
{
if (r-1!=l+1&&r-1!=l) erase(r-1);
if (r!=l+1) erase(r);
erase(r+1);
}
swap(a[l],a[r]);
insert(l-1);
insert(l);
insert(l+1);
if (l!=r)
{
if (r-1!=l+1&&r-1!=l) insert(r-1);
if (r!=l+1) insert(r);
insert(r+1);
}
cout<<ans<<'\n';
}
}
}
Пересечение любых $$$k$$$ отрезков либо пусто, либо дает отрезок. Зафиксируйте левую границу пересечения и посчитайте количество наборов из $$$k$$$ отрезков, у которых пересечение начинается в этой левой границе.
import java.io.*;
import java.util.*;
public class D_Java {
public static final int MOD = 998244353;
public static int mul(int a, int b) {
return (int)((long)a * (long)b % MOD);
}
int[] f;
int[] rf;
public int C(int n, int k) {
return (k < 0 || k > n) ? 0 : mul(f[n], mul(rf[n-k], rf[k]));
}
public static int pow(int a, int n) {
int res = 1;
while (n != 0) {
if ((n & 1) == 1) {
res = mul(res, a);
}
a = mul(a, a);
n >>= 1;
}
return res;
}
static void shuffleArray(int[] a) {
Random rnd = new Random();
for (int i = a.length-1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int tmp = a[index];
a[index] = a[i];
a[i] = tmp;
}
}
public static int inv(int a) {
return pow(a, MOD-2);
}
public void doIt() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tok.nextToken());
int k = Integer.parseInt(tok.nextToken());
f = new int[n+42];
rf = new int[n+42];
f[0] = rf[0] = 1;
for (int i = 1; i < f.length; ++i) {
f[i] = mul(f[i-1], i);
rf[i] = mul(rf[i-1], inv(i));
}
int[] events = new int[2*n];
for (int i = 0; i < n; ++i) {
tok = new StringTokenizer(in.readLine());
int le = Integer.parseInt(tok.nextToken());
int ri = Integer.parseInt(tok.nextToken());
events[i] = le*2;
events[i + n] = ri*2 + 1;
}
shuffleArray(events);
Arrays.sort(events);
int ans = 0;
int balance = 0;
for (int r = 0; r < 2*n;) {
int l = r;
while (r < 2*n && events[l] == events[r]) {
++r;
}
int added = r - l;
if (events[l] % 2 == 0) {
// Open event
ans += C(balance + added, k);
if (ans >= MOD) ans -= MOD;
ans += MOD - C(balance, k);
if (ans >= MOD) ans -= MOD;
balance += added;
} else {
// Close event
balance -= added;
}
}
in.close();
System.out.println(ans);
}
public static void main(String[] args) throws IOException {
(new D_Java()).doIt();
}
}
Давайте вместо массива из нулей и единиц будем хранить количество нулей между каждой парой соседних единиц. Как тогда будут выглядеть операции обмена? А как посчитать защищенность армии в таком случае?
Пусть нам дан исходный массив и конечный. Подумайте, за сколько операций можно первый превратить во второй.
Соедините все вместе и напишите ДП.
#include <cassert>
#include <climits>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
template<typename T>
inline void umin(T &a, const T &b) {
a = min(a, b);
}
template<typename T>
inline void umax(T &a, const T &b) {
a = max(a, b);
}
int main() {
ios_base::sync_with_stdio(false);
int n; cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
a.push_back(1);
vector<int> gg;
for (int i = 0; i <= n; ++i) {
int s = i;
while (a[i] == 0) ++i;
gg.push_back(i - s);
}
vector<int> p = gg;
partial_sum(begin(p), end(p), begin(p));
constexpr int mx = 103;
constexpr int dx = mx + 1, dy = mx + 1, dz = mx * (mx + 1) / 2 + 1;
static int dp[dx][dy][dz] = {};
for (int i = 0; i < dx; ++i) {
for (int j = 0; j < dy; ++j) {
for (int k = 0; k < dz; ++k) {
dp[i][j][k] = INT_MAX;
}
}
}
dp[0][0][0] = 0;
int k = gg.size(), l = p.back();
for (int i = 0; i < k; ++i) {
for (int j = 0; j <= l; ++j) {
for (int s = 0; s <= n * (n-1) / 2; ++s) {
if (dp[i][j][s] == INT_MAX) continue;
for (int q = j; q <= l; ++q) {
umin(dp[i+1][q][s + abs(q - p[i])], dp[i][j][s] + (q-j)*(q-j));
}
}
}
}
int mn = INT_MAX;
for (int s = 0; s <= n * (n-1) / 2; ++s) {
umin(mn, dp[k][l][s]);
int val = l*l - mn;
assert(val % 2 == 0);
cout << val/2 << " ";
}
cout << endl;
return 0;
}
Ого! Настолько быстрый разбор, да ещё с подсказками! Очень здорово, что вы сделали их. Надеюсь, многие авторы тоже так будут делать в разборах)
++. Просто за подсказки уже топовый разбор. Задачи, в целом, тоже классные были.
Очень полезно и отлично, что разборы идут с подсказками! Было бы хорошо увидеть подсказки перед разбором задачи и в дальнейших контестах.
Auto comment: topic has been translated by gepardo (original revision, translated revision, compare)
Actually, many people say that now there are practically no data structure or DP tasks, only ad-hoc and constructive. Well, this contest disproves this. There were no constructive tasks, but there were Segment Tree in C2 (there is a solution using it) and DP in E.
One contest doesn't disprove a trend.
I am actually better at ad-hoc and constructive currently and loved the trend :sobs:, But I do like these rounds where I learn a lot.
Please could you explain/hint about the Segment tree solution of C2. How will we merge answer of left and right for getting answer of current node ? Thanks in advance!
You can maintain four quantities in the segment tree node i.e maximum strength given that
1. first element has $$$plus$$$ sign before it and last one also has $$$plus$$$ sign
2. first element has $$$plus$$$ sign and last has $$$minus$$$
3. first element has $$$minus$$$ sign and last has $$$plus$$$ sign
4. first element has $$$minus$$$ sign and last has $$$minus$$$ sign
You can easily implement merge and update operations.
Here is my implementation https://codeforces.com/contest/1420/submission/93716090. There may be easier solutions but this one was more obvious and intutive
Got it bro. Thanks a lot _Bishop_.
Tch tch, "fenwick123" had to use segment tree. xD
Hi Sir, I wanted to know is there any site that focusses more on data structures and less on ad-hoc?
I think atcoder contests are better in this matter.
I implemented segtree and received tle in C2. someone willing to help? https://codeforces.com/contest/1420/submission/93731337
Massive output, use \n instead of endl.
Also, if you exepected segtree, the constraints could've been relaxed (:
Wind_Eagle Can you please Explain
1420B.Rock and Lever
Not able to understand.From the editorial codeWhy to need to check
a[i]<(1<<j+1)
.Why the total number of pairs is cnt*(cnt-1)/2.Can you please explain.Tried to understand for so long still not cleara[i]>=(1<<j)
is actually $$$a_i \geq 2^j$$$, anda[i]<(1<<(j+1))
is actually $$$a_i < 2^{j+1}$$$. If some number is greater or equal than $$$2^j$$$, and strictly smaller, than $$$2^{j+1}$$$, than it contains $$$j$$$-th bit as the greatest bit.cnt*(cnt-1)/2
is actually $$$C_n^2$$$, where C is binomial coefficient. More easily, this is the number of ways to pick to different things from a set of $$$n$$$ things. In this task we want to choose the number of ways to pick two numbers from $$$n$$$ numbers.It seems to me that you should first study some simple maths, like basic combinatorics, bit arithmetics and number theory. With mathematical base it is much easier to study CP.
Thank you for solving my contest!
For E, if we accept solution in O(n^5), I think it may be better to choose a smaller n. For me, I was too afraid that an O(n^5) solution will TL and just tried to think of a better solution.
We initially thought of making $$$n \le 100$$$ in this problem, because my solution in $$$O(n^5)$$$ passes with such constraints. Anyway, the DP solution is pretty fast and $$$n^5$$$ can be easily divided by some constant factor, so the constraints may seem too big for $$$O(n^5)$$$.
I can understand your choosing n<=80. Maybe I just need to accept the fact that computers are much faster nowadays.
BTW, my solution at https://paste.storage.boleyn.su/cfr672d2e.cpp should have a better time complexity. I have not analyzed its TC yet so this is just my guess.
Can you explain your approach? Is it true that you use a DP similar to the one described in the editorial, but you optimized the code by skipping invalid DP states?
For the last dimension, it is non-decreasing, so we can express it using a vector<pair<int,int>> and reduce some useless states.
My guess is that there may be a bound better than O(n^2) for it. It would be nice to prove or disprove my guess.
UPD: I tested it with larger constraints. It turns out that my guess is wrong. The size of vector<pair<int,int>> is still O(n^2).
I felt like D had hard time limits. But, later realized after contest with precomputation of inverse of each factorial it could have been made faster.
Can you(someone) explain how to do that? Cause I got a TLE on pretest-11.
precompute fact 1 to n and mod inverse of those instead of computing them every time.
Actually, I did that but still got a TLE(UPDATED: NEVER MIND I PASSED IT)
you can calculate the mod inverse at run time also, pre-computing the factorials is enough
Precompute factorials from 0 to N (here $$$3*10^{5}) $$$ initially in an array, say $$$fact$$$.
Then calculate inverse factorial of N using formula $$$inv_f(N) = fact(N)^{MOD-2} \% MOD $$$
which takes $$$ O(\log_2 (MOD))$$$ time. Using this value, now fill the remaing values from N-1 to 0 using recurrence : $$$inv_f(i) = (i+1)*inv_f(i+1)$$$.
Thus we can precompute inverse factorials in $$$ O(N) $$$ complexity.
Solution for reference : 93729779
Hey, I precomputed the factorials and inverse factorials similar to your solution but I am getting TLE.
Use binary exponentiation in your powmod function to calculate $$$a^b$$$ in log(b) complexity, you are calculating it in O(b) time. You can read it here : cp-algo
Thanks, didn't know about binary exponentiation.
Note that precalculateing the inverse factorial does not give a better runtime. We never need to calculate more than $$$3*10^5$$$ inverses. So precalculating them just uses more memory, but not less time.
But to calculate $$$3*10^5$$$ inverse factorials you'd have to calculate them in $$$O(log_2(Mod))$$$ individually resulting in $$$O(N*log(Mod)$$$ time. But here I am precalculating them in $$$O(N)$$$, so I am unable to understand your logic behind why this won't give better runtime? Can you please elaborate.
You are right. I was irritated by the long runtime of your solution. But that is caused by the use of the map instead of sorting an array once.
I encountered this for the first time, tried to dig around but can't figure out why this works-
Can u help or tell me where to look.
Does this makes sense?
$$$(n+1)!^{−1} = (n!*(n+1))^{-1}$$$
$$$(n+1)!^{−1} = n!^{−1}*(n+1)^{−1}$$$
$$$(n+1)!^{−1}*(n+1) = n!^{−1}$$$
Watch from 16:00 onwards Lecture on Combinatorics By Kevin Charles Atienza
Hi there. Please, tell me about inverse factorial of N. What is it?
I precomputed the factorials and the inverses, thus my solution was linear, though I think $$$O(n\log mod)$$$ should fit in time.
Great problemset, like it . waiting for your next contest,thanks
For some problem editorial is in english and for others it's in russian . Pls Fix.
The English versions will be loaded in several minutes.
Can you tell if the elements of array in C1 are not distinct what will happen??
I don't understand your question. The elements $$$a_i$$$ are distinct by problem statement. Or do you want to know if the intended solution works if equal elements are allowed?
Yess if we go by approach for maxima and minima approach for C1 problem then will it work??
It is unclear how we will treat an element if its neighbor is equal to it. Or even worse, when both neighbors are equal to our element. Will it be a local maximum or local minimum? Also it's important that local minima and local maxima must alternate (this property is used actively in the proof).
Anyway, it's an interesting question on how to fix the solution when equal elements are allowed.
If you solve C1 using dynamic programming, you should not be affected by equal elements.
One may assume that out of equal neighboring elements, the left one is smaller. This is equivalent to adding $$$i \cdot \varepsilon$$$ to $$$a_i$$$, which makes all elements distinct while keeping the answer the same if $$$\varepsilon \rightarrow 0$$$.
A trivial fix is to break ties by index, so that if $$$a_i = a_{i+1}$$$, we can simply pretend $$$a_i < a_{i+1}$$$. This is safe because the value of the optimal solution is continuous in the values of $$$a_i$$$ and we can imagine taking $$$a_i = \lim_{\varepsilon \to 0^+} a_i + i \cdot \varepsilon$$$ simultaneously at all indices. Alternatively, the solutions based on the $$$\sum_{i = 1}^n \max (0, a_i - a_{i-1})$$$ formula or on segment trees are completely unchanged, since they do not make use of the distinctness constraint in any way.
EDIT: I was beaten to the punch! So it goes.
what is "Разбор"???? is it rated??
It is a Russian word for "parsing".
It's better to translate "разбор" as "analysis" :)
Round was great. Kudos to author!!
My editorial is in Russian :(
Everything is OK now, except problem E.
UPD: Problem E is also OK now.
Does "except problem E" mean this?![](/predownloaded/aa/c0/aac0006fd77a0890b3d3fdc91ab9c45acfaff407.png)
Yes.
I could not solve a single problem in this contest, should I die? Why am I even alive.
Don't feel demotivated you have given just few contest.just keep practicing and keep motivated :)
just take your meds : one tourist stream every day ! starting with : https://www.youtube.com/watch?v=97tieEKfvBs
I don't understand the solution for problem D. This is my understanding so far :-
For example: if there is a starting point on 42 and our count of segments excluding this is 10 and the value of k is 3. then I found out the solution is to add
ncr(10,k-1)
.Now the count is 11 and if we again reach to another starting position on 45 so again we will addncr(11,k-1)
.Now count is 12.So if I understood it correctly, then we will choose one out of k to be the current one and choose rest k-1 from the previous segments right?
If we fixed a starting point, we may pick any $$$k$$$ segments that contain it. But there must be at least one segment that start in this point (note that more than one one segment may start in the same point).
Actually, I was talking something like this solution.
I tried this concept after the contest.
I understood your solution. It's mostly the same as in the tutorial, but it considers the segments that start in the same point in a shorter and nicer way.
How to solve C2 using segment tree?
I used an ad-hoc segment tree with 4 values for each range:
The value (max/even) of a node is the max from these values:
The rest of the values are obtained similarly. Updating the tree is the same as a regular segment tree.
Here is my code.
I am still a bit surprised to see the no. of submissions on the Problem D, Is it some sort of a standard algo or question? Because some were able to this in a matter of just few minutes, if it is then please do tell me
I don't know weather it's standard or not but many interval related questions have similar approach.
What is the approach?
My approach for D. Rescue Nibel : I will tell you the method i used to solve, i don't know weather its similar to tutorial's but mine one is easy.I will create a array and put inside
L
andR + 1
for all intervals. So array will have size =2 * N
. Then sort the array. We keep a variablecnt
which will tell the number of lamps which are currently ON. Initiallycnt = 0
. Now we will iterate over all element of array (in chronological order). Let the current element bex
. Nowx
will either be starting time or (ending time + 1) of some interval. If it is starting time andcnt >= k - 1
then we addNCR(cnt, k - 1)
to the answer. We takek - 1
because thekth
element will be the lamp whose starting time isx
and remainingk - 1
we take from ourcnt
(lamps which are already in ON state). Then we increment ourcnt
by 1. If x is (ending time + 1) of some lamp then we just decrement ourcnt
. This is my code --->Can you please share the code for NCR(cnt, k, MOD)
I did follow the same approach but end up having a run time error which was certainly "Arithmetic Exception" while computing this Combination
It fails over 11th test case....could you please share some insights
My Submission
Please read this https://www.geeksforgeeks.org/compute-ncr-p-set-3-using-fermat-little-theorem/
For anyone looking for his submission.
I think you should try ** Min Stations for trains ** problem on GFG.
https://www.geeksforgeeks.org/number-of-ways-to-choose-k-intersecting-line-segments-on-x-axis/ I found it on geeks for geeks after the contest.
I had a Java solution TLE on D which I fixed by just using a hashmap to cache the results of modular inverse :/
w/o cache: https://codeforces.com/contest/1420/submission/93688984
w/ cache: https://codeforces.com/contest/1420/submission/93691811
Solution for Problem C2
Suddenly it turns out that a single request will change the state of no more than six elements
Didn't get intuition for this statement! Someone Please elaborate
Only the neighbour elements affect local maximum and local minimum. So, if you swap $$$l$$$ and $$$r$$$, you will need to recalculate only $$$l$$$, $$$r$$$ and their neighbours (in the worst case, it will be $$$l-1$$$, $$$l$$$, $$$l+1$$$, $$$r-1$$$, $$$r$$$ and $$$r+1$$$, thus six elements).
Whether an element is a local maximum (or minimum) or not solely depends on its relation to the neighbors, as the required condition for a local maximum is a_i > a_{i-1} and a_i > a_{i+1} (reverse signs for a minimum). Now when swapping elements at given positions l and r, this will affect the status of the elements at positions l-1, l, l+1, and r-1, r, r+1 (note that these triplets may partly overlap).
https://medium.com/@harryjobz/pok%C3%A9mon-army-3f4348d57143
can't we solve problem b using tries
Why cut a apple using sword?
Yes, we can. https://codeforces.com/contest/1420/submission/93721816
Спасибо за быстрый разбор :)
I am looking details description of solution D or a video tutorial
Isn't the solution of problem D detailed enough?
may be..but i can't understand this..
You can try looking at secondthread's youtube channel , I guess it may help.Youtube channel name is "SecondThread".
This is the implementation. Hope it helps.
I've succesfully uphacked myself. Turns out I forgot to check if all ai are different and still passed systests :D
Never knew that we can hack our own answers!
Can anyone please explain why my code for Problem D got Accepted when I used fastI/O but was getting TLE without using fastI/O even after that fact that the question had just one testcase per testfile?
fast I/O is so powerful that it can even reduce your acceptance time to half. Even I was amazed when I first observed it, few days back.
It is because of the large input file, you have to read 6 * 10^5 numbers
Thanx a lot buddy!
Your welcome my friend.
C1 was already on internet. Make this contest unrated https://tkramesh.wordpress.com/2009/10/08/maximum-alternating-sum-subsequence/
C1 is a standard dp problem, you can't argue on that basis to make the contest unrated. It is difficult to make new problems and very easy to make new accounts.
I agree making a new problem is a difficult task but at least we shouldn't use the same language as has been used on other sources. Just googling "maximum alternating sum subsequence" gives you the solution (I googled after seeing this).
Can C1 be solved w/o dynamic programming i.e greedy?
See solution for C2.
yes you just need to select each local maxima and minima, and remove the last minima.
Is there a typo in the summation of $$$p(A)$$$ for E? Isn't it
Yes, this is a typo. Thanks for finding it out.
We assign 4 values to each node (corresponding to a segment of the array) in the segment tree, which are the maximum value obtained if: 1/ The sequence begins with a (+) sign (addition) and ends with a (+) sign. 2/ The sequence begins with a (+) sign and ends with a (-) sign (substraction). 3/ The sequence begins with a (-) sign and ends with a (+) sign. 4/ The sequence begins with a (-) sign and ends with a (-) sign. For each node, these values can be deduced from its two children. My submission for more details: 93687329
i think the time limit for D is really bad, i made this submission in the contest and i got a TLE after it ,i don't know why my code gets TLE is the problem with factor 2? https://codeforces.com/contest/1420/submission/93716363
i think the time limit for D is really bad, i made this submission in the contest and i got a TLE after it ,i don't know why my code gets TLE is the problem with factor 2? https://codeforces.com/contest/1420/submission/93716363
Same happend with me bro see this, can you help why its happening in my code?
I really like this kind of editorial where hints are provided rather than directly displaying the solution approach completely. I wish more than more authors adopt this strategy. Also, the problem statements were quite nice. Thank you for the good round and helpful editorials.
You are welcome :)
Well done testers and setters, this was a great contest.
thanks for giving hints before solutions, would expect the same for future contests
I heard that D was copied from gfg. I was surprised at number of submissions of D
An observation free solution for C1 and C2:
First let's try to solve this problem using divide and conquer. On every divide stage, we need the following information for each halve:
For the state where $$$R - L = 0$$$,
In the conquer stage, we need to merge these properties. We can easily do this as follows:
Our final answer will be $$$max(1, 2)$$$ over the entire array. This divide and conquer can solve C1. The question is, how do we keep updating this?
Well, in this 'divide and conquer', the conquer part is only $$$O(1)$$$. Therefore, this is a decomposable search problem which can be handled fast by segment trees.
Therefore to AC C2 we can create a segment tree where each node in the segment tree stores the 4 properties mentioned above and the merge function performs the max operations as described above. After this, it's standard.
Time Complexity: $$$O(N + Q \cdot LogN)$$$
You can view my submission for clarity:
https://codeforces.com/contest/1420/submission/93674507
Note: There was a much easier solution using some problem specific observations, but it's always better to have a solution that works on a wider range of cases. I hope this helped :)
To make it cleaner change 2 and 3 to "Maximum sum subsequence of even size starting with a positive element" and "Maximum sum subsequence of even size starting with a negative element", this removes isolated 1L 1R 2L 2R from the max, because the base case turns into 0 (empty subsequence has even size) instead of -10^16.
Yeah GG
I liked the fact that hints are provided before the full solution. Thank you so much!
What is event method mentioned in D's solution?
We intend to keep track of the number of lamps which are switched ON at a particular instance of time,let's call that variable x. Now consider turning ON and turning OFF of each lamps as seperate events.It's intuitive that the numbers of lamps switched ON (variable x) only changes at the time of an event(switching ON or switching OFF of some lamp). Hence we sort all the events in non-decreasing order of their occurence and process them one by one. (Note that for some time T if there are multiple events occuring ,we place the switching ON events before the switching OFF events because the question mentions that lamps are switched ON from li to ri inclusive).
As we process the events 1by1, if we encounter a switching ON event, x is incremented, otherwise x is decremented.(quite intuitive). Whenever there is a switching on event and x>=k-1 , there are X choose K-1 ways of selecting k-1 lamps ,which cobmined with the current lamp being switched on gives us a new solution of k lamps.(My Submission)
If you are new to this technique, https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/ is a good introductory problem.
Thanks for your explanation. I had this thought first but hesitated in doing it.
Thank you for the explanation. For anyone who did not get it, an alternate explanation could be that we just have to chronologically sort all that happens and iterate over it while maintaining a counter of the number of bulbs still switched on. Just keep in mind to switch off a bulb after switching on all the bulbs at that instant.
I found an AC submission to problem B in my room:
https://codeforces.com/contest/1420/submission/93659129
It has O (n^2) complexity but runs surprisingly fast due to the use of intel vectorization.
Is this possible on AMD processors?
AMD processors have the same instruction set as Intel and support vectorization, so I think it's possible.
Does this mean that we can just pass simple n2 loops like these with this vectorization technique?
Sometimes it helps to fit into time limits, but these cases are not so often. Vectorization improves speed only in constant time, so if I make $$$200'000$$$ instead of $$$100'000$$$, then the $$$O(n)$$$ solution will be two times slower, but vectorized $$$O(n^2)$$$ will become four times slower, because it's still $$$O(n^2)$$$. Additionally, not every solution is good to vectorize.
What is intel vectorization and why this O(n^2) solution passing??
In short, it allow the core perform multiple instructions simutanenously.
OMG!! I tried my luck with the exact same approach but got tle.....Can you plz explain what is Intel vectorization?
You need a new generation of intel cpu e.g. 9th or 10th gen. Older cpus do not support this feature.
So it means who has high processor laptop dont need to worry about time complexity??
No, having a better algorithm is always better.
Vectorization is available for long time. According to Wiki, AVX2 is supported in Intel CPUs since 2013, and SSE is used for even longer period. Why do you think that only 9th or 10th generations are supported?
I guess so because this code runs on my computer in 6 seconds (intel xeon 6th gen).
1) What compiler are you using?
2) Did you see the generated assembly?
If your CPU doesn't support AVX2 instructions and the compiled binary has them, the program will simply crash.
I am using GCC 8.2 Windows, C++14. The compiler bypass all directives and generate the output exe as the same as normal
Then your compiler didn't produce such instructions. It doesn't mean that CPU is not capable of executing AVX2.
If you try to compile https://codeforces.com/contest/1420/submission/93659129 with
-O2
, everything should be optimized and AVX2 will be used.So does this mean that someone with 9th/10th gen processor can get AC easily by doing 10^10 operations in like 1 second?
It's not true for every program. Vectorization improves the speed much only in the specific parts, like short loops which iterate over the array. You cannot just write
#pragma GCC target("avx,avx2")
and make any program two times faster. But there are some problems on Codeforces where solutions in $$$O(n^2)$$$ with vectorization passed with $$$n \le 100'000$$$.Clean solution to C1 using maxima minima approach
For C2, the answer can be written as $$$\sum_{i=0}^{n}{max(0, a_i-a_{i+1})}$$$, where, $$$a_0 = a_{n+1} = 0$$$. Viewed this way, updates become very easy.
Actually , problem E has a solution in only $$$O(N^4)$$$ with simple convex hull trick . You can check my solution here .
Fantastic!
Can anyone explain to me the problem b's code? why j from 29 to 0?
It is because 1<= Ai <=10^9. So Ai can have maximum length of 29 in binary form.
ok thx!
For 1420C2 - Pokémon Army (hard version), instead of storing the local maxima/minima, we actually only need to store the current value of each element.
Why?
Because the best answer we can get can also be represented in
If we add an extra $$$0$$$ to the end of the array.
So for each query, we need to check at most 4 pairs: $$$(l-1,l)$$$, $$$(l,l+1)$$$, $$$(r-1,r)$$$, $$$(r,r+1)$$$. Note that there might be duplicates, so we need to use a set to deduplicate.
If the original pair is counted in the current sum, then we subtract it from the sum.
Then we do the swap and check the pairs again. If the new pair should be counted, we just add it to the sum.
I think this solution is clearer than the official one.
AC submission: 93743846
i am getting wrong answer for test case 44 in problem D. please help me out. i have done the same thing as mentioned in editorial most probably. submission : 93742154
Please help lucifer1004
This solution is really nice :) Do you have an AC submission?
I have added my submission.
I think it should be $$$\sum max(0, a_{i+1} - a_{i})$$$, $$$i = 0$$$ to $$$n$$$, $$$a_0 = 0$$$ and $$$a_{n+1} = 0$$$
The two forms are equivalent.
Note that I only add one $$$0$$$ at the end, while you add $$$0$$$ at both front and end.
i am getting wrong answer for test case 44 in problem D. please help me out. i have done the same thing as mentioned in editorial most probably. submission : 93742154
I really like this editorial providing hints not only solutions.
Actually DP solution with $$$O(n + q\sqrt{n})$$$ is also conceivable for C2 although because of hard constraints it gets a TLE. My approach, drawing inspiration from Mo's algorithm, was basically to split the pokemons into $$$\sqrt{n}$$$ segments of size $$$\sqrt{n}$$$ each. For each segment we can calculate following 4 things in $$$O(\sqrt{n})$$$ time (using the approach in C1). 1. Max +- sequence with even number of terms. 2. Max -+ sequence with even number of terms. 3. Max +- sequence with odd number of terms 4. Max -+ sequence with odd number of terms.
Finally we can run the dp on these $$$\sqrt{n}$$$ segments to get the answer in $$$O(\sqrt{n})$$$ time. Now, for every query just swap the pokemons and then recompute the (atmost) 2 segments in which the swapped pokemon lie and finally recompute the DP. For each query this can be done in $$$O(\sqrt{n})$$$ time.
My solution, TLE ofcourse - 93717594
Can someone Please explain how to do c2 with segment trees?
https://codeforces.com/blog/entry/82978?#comment-701497
Read the comments above before posting yours.
Why is my code getting runtime error on test 5 of problem c1. I have applied DP using 2d array where dp[i][j] tells answer when i elements are considered with j elements included in subsequence. https://codeforces.com/contest/1420/submission/93757697
I will be obliged if someone helps.
It can happen that $$$n = 3\cdot10^5$$$ in this task. And $$$3\cdot10^5\times3\cdot10^5$$$ is too large to fit into memory on stack, so the program crashes.
When will ratings update?
Whats the reason behind the delay?
For C2, we can use set to avoid categorical discussions.
Can anyone tell me about the "event metho" which author is referring in solution of D? "It should be noted that p(x) and s(x) can be easily supported using the event method. Then, the total runtime will be O(nlogn)."
The idea is as follows. You have segments $$$[l_i; r_i]$$$ and want to calculate (for example) the number of segments that contain specified points $$$x_i$$$. To do this, you create an array of events:
Then, sort such events by time and process them in sorted order. Now it's easy to keep track of number of open segments in the specified points $$$x_i$$$.
I still don't understand the logic behind A Cube Sorting
It is not difficult to see that the answer «NO» in this task is possible when and only when all ai are different and sorted in descending order.
How can one derive such logic
PS — newbie here, want to learn :D
If you know something about bubble sorting, you can think of the worst time complexity of bubble sorting ($$$\frac{n-1 \cdot n}{2}$$$) and its reasons
In 1420B- Rock and lever can you explain what this part of the code is doing?
for (int j=29; j>=0; j--) { int64_t cnt=0; for (int i=0; i<n; i++) { if (a[i]>=(1<<j)&&a[i]<(1<<(j+1))) { cnt++; } } ans+=cnt*(cnt-1)/2; }
PS-Newbie Here
if (a[i]>=(1<<j)&&a[i]<(1<<(j+1))) { cnt++; }
stores the no of ( numbers having their rightmost set bit e.g: 4(binary representation : 001) ,in 4 the rightmost set bit is at index 2(0 indexed) ) .
cnt*(cnt-1)/2
part counts the nos satisfying the condition mention in the question for that count.Hello everyone !! I hope you are having a good day!
i tried to make editorial for this round :- https://www.youtube.com/watch?v=uc6mN7BZVbI&list=PLrT256hfFv5WH3U33DuKUzL9fYnVsTGAj
problem solved. -> A , B , C1 , C2 , D
language of communication -> Hindi
programming language -> C++
in problem c2 let y be the total number of local maximum and minimum we have now, can we change the parity of the y with an update(swapping two element)?
Can someone explain the dp which we have done in ques E. Thanks
Can anyone help me with the problem D. I got WA in test 11. Here is my code:93779028
If I am not wrong you have compressed the values but you cannot compress the values in this question. You have to keep them as it is.
Can you explain why I cannot compress the values? I think the values are not important in this problem.
For example, two segments [1,4] and [2,6] after being compressed will become [1,3] and [2,4], which will not affect the result.
Here are video solutions for all problems, including a description of the weird segtree sol for C2
Very nice Editorial for problem E. Thanks :). Has anyone solved it using flows?
problem D is a nice educational problem thanks :)
Why is my code for B failing on 2nd pretest? I have stored the count of occurrences of each MSBs in a map and then have iterated over it to calculate the final count. Link to submission: https://codeforces.com/contest/1420/submission/93796185
Because when you are adding m(m-1)/2s, m can be up to 10^6, so if you set m as an int, it can overflow.
I today constucted a easy way to do the C2 problem or C1 problem. The ans is essentially the half of sum of absolute value of adjacent indices. (To work it, we have to add zero at start and end of the array). Now the update is really easy, we have to just remove the old absolute values and add the new ones. This can also handle updates like changing the strength of a indice. See the Ac code for implementation details- AC code
Can someone spot why I am getting WA on test 11 in Problem D. Here is my submission. 93837255
I like this step by step style of the editorial. Thanks.
Can some one tell me why my program is getting wa for 99 test case .Why the asnwer should be 0 for 99 test case ?
include<bits/stdc++.h>
using namespace std; typedef long long ll;
define mod 998244353
const int N = 1000001; using namespace std;
// array to store inverse of 1 to N ll factorialNumInverse[N + 1];
// array to precompute inverse of 1! to N! ll naturalNumInverse[N + 1];
// array to store factorial of first N numbers ll fact[N + 1];
// Function to precompute inverse of numbers void InverseofNumber(ll p) { naturalNumInverse[0] = naturalNumInverse[1] = 1; for (int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (p — p / i) % p; } // Function to precompute inverse of factorials void InverseofFactorial(ll p) { factorialNumInverse[0] = factorialNumInverse[1] = 1;
}
// Function to calculate factorial of 1 to N void factorial(ll p) { fact[0] = 1;
}
// Function to return nCr % p in O(1) time ll Binomial(ll N, ll R, ll p) { // n C r = n!*inverse(r!)*inverse((n-r)!) ll ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N — R]) % p; return ans; }
int main(){ ll p = 998244353 ; InverseofNumber(p); InverseofFactorial(p); factorial(p); ll n,k; cin>>n>>k; ll a[n][2]; ll ans=0; vector<pair<int,int>>v; for(ll i=0;i<n;i++){ cin>>a[i][0]>>a[i][1]; if(a[i][0]!=a[i][1] || k!=1){ v.push_back({a[i][0],0}); v.push_back({a[i][1],1}); } else{ if(k==1) ans++; } } sort(v.begin(), v.end());
}
The answer is exactly
998244353
in this testcase, and998244353 % 998244353 == 0
:)Thank you a lot ....I got AC now.I am actually thinking why the answer is 0 and read question for more than 100 times since morning. Thank you :)
In the tutorial of problem E, should $$$z_i$$$ be $$$\sum^i_{j=1}{f_j}$$$? And could you please explain why it takes $$$|z_i-(s+h)|$$$ steps from $$$dp_i$$$ to $$$dp_{i+1}$$$?
Yes, there is a typo in the editorial.
Remember the reasoning above on how many steps it takes to transform the array $$$a$$$ into $$$b$$$. It's $$$\sum\limits_{i=1}^n \left|z_i - \sum\limits_{j=1}^n b_j\right|$$$, as shown above. In our DP, we know the array $$$a$$$ and build an optimal array $$$b$$$ step by step. After deciding that the value of the $$$i$$$-th element of the array $$$b$$$ will be $$$h$$$, we say that $$$\sum\limits_{j=1}^i b_j = s + h$$$. So, we add $$$\left|z_i - \sum\limits_{j=1}^i b_j\right| = \left|z_i - (s + h)\right|$$$ to the number of steps.
Is it now clear for you?
Yes, thanks. I didn't realize $$$dp_i$$$ starts from 0 so I mistook $$$h$$$ as $$$b_{i+1}$$$.
I think there is some inconsistency in the editorial text. $$$s + h$$$ should be of the same "size" as $$$z_i$$$, so there I would rather write $$$z_{i+1}$$$.
Can someone please tell me why I am not getting TLE on my solution to problem E?
It seems like magic. I really don't understand how a not very well optimized code like this is working.
Here is the solution link: 93898124.
Isn't it just $$$O(n^5)$$$? You have very straightforward loops, so it should be pretty fast. Switching to plain arrays might speed it up, but otherwise this looks like an intended solution.
Yes, but $$$80^5 > 32 \times 10^8$$$ and therefore, should not work, unless it is optimized heavily.
There is a small constant in front, rep(i,1,cnt+1) rep(j,i,n+1) is $$$n^2/2$$$, rep(p,0,j) further gives $$$n^3/3$$$. $$$10^8$$$ is quite okay, it is also very simple operations inside the loops.
Can anyone help me with the reason for this solution getting TLE? Problem c2 https://codeforces.com/contest/1420/submission/93901635
Use '\n' instead of endl and use fast I/O.
In editorial of 1420C1 - Pokémon Army (easy version) and 1420C2 - Pokémon Army (hard version).
The outputs of the editorial codes themselves do not match for the same input test cases. For example,
Input
1
4 0
5 2 2 5
Output (C1 Editorial Code)
8
Output (C2 Editorial Code)
10
I know it's a bit late, but the editorial remains as is. So, this should be corrected.
Is the input correct? The numbers in the input must be distinct, according to the statement.
Oh, I'm really sorry for that. Thanks for correcting me.
Can anybody explain how this formula is deduced in solution of problem E?
$$$p(A) = \sum_{1 \le i < j \le k} f_i\cdot f_j = \frac 12 \left( \sum_{1 \le i, j \le k} f_i\cdot f_j - \sum_{i=1}^k f_i^2 \right) = \frac 12 \left( \left(\sum_{i=1}^k f_i \right)^2 - \sum_{i=1}^k f_i^2 \right)$$$
We can get this equation in an alternative way:
$$$\displaystyle\left(\sum\limits_{1 \le i \le k} f_i\right)^2 = \sum\limits_{1 \le i \le k,\ 1 \le j \le k} f_i f_j = \sum\limits_{1 \le i \le k,\ 1 \le j \le k,\ i < j} f_i f_j + \sum\limits_{1 \le i \le k,\ 1 \le j \le k,\ i > j} f_i f_j + \sum\limits_{1 \le i \le k,\ 1 \le j \le k,\ i = j} f_i f_j = $$$
$$$\displaystyle = 2\sum\limits_{1 \le i < j \le k} f_if_j + \sum\limits_{i=1}^k f_i^2 \implies 2\sum\limits_{1 \le i < j \le k} f_if_j = \left(\sum\limits_{1 \le i \le k} f_i\right)^2 - \sum\limits_{i=1}^k f_i^2$$$.
In simple words, we take $$$\left(\sum\limits_{1 \le i \le k} f_k\right)^2$$$, which is a sum of pairwise products. Split these pairwise products onto three parts: where $$$i < j$$$, where $$$i > j$$$ and where $$$i = j$$$. The first two parts are equal to $$$\sum\limits_{1 \le i < j \le k} f_if_j$$$, and the last part is a sum of squares. From this we get that $$$2\sum\limits_{1 \le i < j \le k} f_if_j = \left(\sum\limits_{1 \le i \le k} f_k\right)^2 - \sum\limits_{i=1}^k f_i^2$$$, therefore the original formula is also true.
I did not get this part: "$$$\left(\sum\limits_{1 \le i \le k} f_i\right)^2$$$ = sum of pairwise products". Can you explain how?
Okay, do you agree that
$$$(f_1 + f_2 + f_3)\cdot(f_1 + f_2 + f_3) = f_1(f_1 + f_2 + f_3) + f_2(f_1 + f_2 + f_3) + f_3(f_1 + f_2 + f_3) =$$$
$$$= f_1f_1 + f_1f_2 + f_1f_3 + f_2f_1 + f_2f_2 + f_2f_3 + f_3f_1 + f_3f_2 + f_3f_3$$$?
(So, we got that $$$(f_1 + f_2 + f_3)^2$$$ is a sum of pairwise products of $$$f_1$$$, $$$f_2$$$ and $$$f_3$$$.
You can do this for arbitrary number of elements in the same manner.
Yeah got it. Thanks.
@geopardo in battle lemming soln what does (q-j)*(q-j) mean
As you can read in the editorial, we use the following formula to recalculate the DP:
In my source code
q-j
is $$$h$$$, so(q-j) * (q-j)
is the $$$h^2$$$ addition in the DP. Basically, it's the square length of the next segment.I have an alternative DP solution to problem E. Observe that the answer is at most C(# zero , 2), in stead of counting the good pairs, I count the bad pairs. (The number of bad pairs is the sum of C(len[i] , 2) for each consecutive 0s with length len[i])
Firstly, I considered interval DP, however, we need also keep track with the number of orders, so we have a state at least DP[l <= 80][r <= 80][k <= 80 * 79 / 2], when merging interval, the time complexity is at least O(N^6), so this doesn't seem like a good approach. Then, I consider a left to right solution, let DP[i][j][k][l] = the minimal bad pairs for the first making length of i sequence such that, we have used j orders, and have a length k full of consecutive 0s suffix, and have used l ones. For transition, DP[i][j][k][l] -> DP[i + 1][j][k + 1][l] + k if we put 0 on the (i + 1) th position. DP[i][j][k][l] -> DP[i + 1][abs(pos[l + 1] — (i + 1))][0][l + 1]. where pos[i] is ith one's position in the initial sequence.
Time complexity O(N^5 / 8) Runtime is some thing like O(80 * 80 * 80 * 79 / 2 * 40 * 40) which should be ok for 2 seconds.
My code: https://codeforces.com/contest/1420/submission/95068002
I read this blog while upsolving problem E. I want to thank gepardo for such a clear, detailed and well-written editorial. The hints were accurate, the math formulas nice and understandable, the explanations concise, I can even say I enjoyed reading it.
Recently, I've stumbled upon editorials that aren't very good. They're written in a hurry, and sometimes not even clear or complete. This editorial was the exception, and for that, the author deserves recognition. It's a great example of how problem tutorials should be written.
Thanks :)
So sice editorial... ❤️
My code for problem D is giving me a run time error.
153332275.
Could anyone please tell me what I'm doing wrong here?
Can anyone please explain Solution B.Not able to understand it
See my submission: 169305548.
Let's calculate the first bit that is 1 in every $$$a[i]$$$ from $$$1$$$ to $$$n-1$$$ inclusively going from highest to lowest bit. (function
f
) Let's call it $$$f(a[i])$$$.Observation is: $$$a[i]$$$ & $$$a[j]$$$ $$$>=$$$ $$$a[i]$$$ ^ $$$a[j]$$$ if $$$f(a[i])$$$ = $$$f(a[j])$$$.
Why? If $$$f(a[i])$$$-th bit in $$$a[j]$$$ is 1 then value of that bit when calulating $$$a[i]$$$ & $$$a[j]$$$ will be 1 and when calculating $$$a[i]$$$ ^ $$$a[j]$$$ will be 0. If $$$f(a[i])$$$-th bit in $$$a[j]$$$ is 0 then value of that bit when calulating $$$a[i]$$$ & $$$a[j]$$$ will be 0 and when calculating $$$a[i]$$$ ^ $$$a[j]$$$ will be 1.
It's known that when comparing two numbers, first that have 1 bit is bigger. Because $$$2^n$$$ $$$>$$$ sum of all powers of 2 from $$$0$$$ to $$$n-1$$$ inclusively. (I know there is way to write it using LaTex but I don't know how to do it.)
Hope it helped.
Best Editorial!!