### Блог пользователя gepardo

Автор gepardo, история, 15 месяцев назад, ,

Перед вами разбор задач сегодняшнего контеста. Я постарался расписать решения задач как можно более подробно, но если что-то будет непонятно, смело пишите в комментариях! :)

785A - Антон и многогранники

Подсказка
Разбор
Код C++
Код Java
Код Python

785B - Антон и занятия

Подсказка
Разбор
Код C++
Код Java
Код Python

785C - Антон и сказка

В этой задаче были слабые претесты. Это было сделано для того, чтобы спровоцировать побольше взломов. И да, я предупреждал в анонсе :)

Подсказка
Разбор
Код C++
Код Java
Код Python

785D - Антон и школа - 2

Подсказка
Разбор
Код C++
Код Java

785E - Антон и перестановка

Приношу извининения, что эта задача не была оригинальной. Я постараюсь, чтобы такое больше не повторилось.

Если у вас в этой задаче TL или ML, не стоит думать, что ограничения по времени/памяти слишком узкие. Авторское решение работает за 1.2 секунды и тратит 9 МБ памяти.

Подсказка
Разбор
Код C++
Код Java

Код C++

Альтернативное решение от netman:

Код Java
Разбор задач Codeforces Round #404 (Div. 2)

•
• +186
•

 » 15 месяцев назад, # |   0 Автокомментарий: текст был обновлен пользователем alex256 (предыдущая версия, новая версия, сравнить).
 » 15 месяцев назад, # |   0 Auto comment: topic has been updated by alex256 (previous revision, new revision, compare).
 » 15 месяцев назад, # |   0 Also notice that k can be found using a formula, but such solutions could fail by accuracy, because the formula is using the square root function. Is there any way to get the solution by formula either in c++ or python while still retaining accuracy?
•  » » 15 месяцев назад, # ^ |   +5 use long double throughout
•  » » » 15 месяцев назад, # ^ |   +4 Can you tell why double gives error and not long double ?? I didn't get convincing proof about it.
•  » » » » 15 месяцев назад, # ^ |   0 it's because of how the IEEE 754 standard encodes floating point numbers. double is a 64-bit floating point type which means it has less than 64 bits for the mantissa (meaning it has less than 64 bits of precision; I think it has 53 bits of precision)long double however is typically an 80-bit type which is AFAIK made specifically to have 64 bits for the actual data we care about.even though the problem can be solved by this method, alternative methods that don't require fidgeting with extra precision floating point types are less likely to produce errors so I can't really recommend doing this always.
•  » » 15 месяцев назад, # ^ |   0 I did exactly that :)25530268
•  » » 15 месяцев назад, # ^ |   0
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   0 We need to check x*(x+1)/2 >= k or x*(x+1) >= 2*k. Take initial x = sqrt(2*k). Keep incrementing x by 1 until x*(x+1) >= 2*k. Here's my code 25523814
•  » » 15 месяцев назад, # ^ |   0 For python you can use the decimal module.  if n >= m: _x = ( -1 + decimal.Decimal(1+8*(n-m)).sqrt() )/2 x = _x.to_integral_exact(decimal.ROUND_CEILING) print m+x else: print n The problem with sqrt: http://stackoverflow.com/q/15696267/1614140
•  » » 15 месяцев назад, # ^ |   0 I thick you can get this ... solution
•  » » 15 месяцев назад, # ^ |   0 Can be done using formula but u have to check the error in sqrt fun if it's giving less then increment answer by 1 http://codeforces.com/contest/785/submission/25542801 This is my solution
 » 15 месяцев назад, # |   +2 785A - Anton and Polyhedrons Hint: 404 Not Found  quit interesting:)
 » 15 месяцев назад, # |   +25 Thanks! I like the way the editorial is written :D
 » 15 месяцев назад, # |   +8 Wow, Great Editorial. Equality of all languages.
 » 15 месяцев назад, # |   0 Спасибо за разбор)) хочется отметить хорошее оформление))
 » 15 месяцев назад, # |   +3 Если в задаче C использовать long double (C++), то точности хватает. Тест на котором не хватает double: 999999998765257152 10 (ответ 1414213572)
•  » » 15 месяцев назад, # ^ |   0 long long is enough25534855
 » 15 месяцев назад, # |   +4 This editorial with hints and opening blocks! Something new and beautiful in this edutorial! I've never senn something like this!
 » 15 месяцев назад, # |   +9 the iterative solution of C passes in time limit ... should've taken care about that..
•  » » 15 месяцев назад, # ^ |   +6 It's hard to hack such solutions because of the following: 109 passes the time limit. The constraints cannot be increased because 1018 is an almost maximal range for the constraints.
•  » » » 15 месяцев назад, # ^ | ← Rev. 3 →   +11 Test cases could have been added so that these kind of solutions get TLE. Anyways the contest was really good, so is the editorial. Thanks! :)
•  » » » » 15 месяцев назад, # ^ |   0 Do you really know the test that can cause these solutions to fail? As mentioned above, 10^9*(some really simple operations) fits the TL.
•  » » » » » 15 месяцев назад, # ^ |   0 I was talking about multiple test cases in a single judge input file. One single test will always pass..
•  » » » 15 месяцев назад, # ^ |   0 Or you can lowering the time limit :)
•  » » » 15 месяцев назад, # ^ |   0 alex256 why you searched in 2*10^9 ? How you guess that for 10^18 1 ans will must between them ? What is the proof ?
•  » » » » 15 месяцев назад, # ^ | ← Rev. 2 →   0 If you see a formula given in the editorial and try k = 2·109, you'll see that it's quite enough to be the right binary search range.
•  » » » » » 15 месяцев назад, # ^ |   0 awesome
 » 15 месяцев назад, # |   +1 It is also possible to solve C using linear search: 25518550
 » 15 месяцев назад, # |   0 salute to alex256.. this is the best editorial i've ever seen..i've always wanted to have those "hints" kind of thing
 » 15 месяцев назад, # |   0 Range tree + decard tree = O((n + q) * log n ^ 2) in problem E
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   0 Можешь объяснить свою идею?Я пытался хранить в каждой вершине дерева отрезков декартово. При свапах я сначала удавляю элементы из соответстующих деревьев (пересчитывая инверсии в "соседних" вершинах ДО), а потом добавляю. O(n log n + q log^2 n). Но это не заходит по времени (я пытался запустить на кфе — оно на макстестах работает около 5.5 сек).
•  » » » 15 месяцев назад, # ^ |   +5 Мое решение за использовало похожую идею, только я хранил декартки не внутри ДО, а внутри дерева Фенвика. Код C++#include #include #include #include #include int seed = std::hash()("alex256"); namespace Treaps { std::mt19937 randGen(seed); struct Treap { int x, y; int cnt; Treap *l, *r; }; typedef Treap* pTreap; static Treap buffer[128 * 1024 * 1024 / sizeof(Treap)]; int bufferSize = 0; inline pTreap allocTreap(int x) { pTreap ans = buffer + (bufferSize++); *ans = {x, (int)randGen(), 1, nullptr, nullptr}; return ans; } inline int cnt(pTreap t) { return t ? (t->cnt) : 0; } inline void upd(pTreap t) { if (t) { t->cnt = cnt(t->l) + 1 + cnt(t->r); } } void split(pTreap t, pTreap &l, pTreap &r, int x) { if (!t) { l = r = nullptr; } else if (x < t->x) { split(t->l, l, t->l, x); r = t; } else { split(t->r, t->r, r, x); l = t; } upd(t); } void merge(pTreap &t, pTreap l, pTreap r) { if (!l || !r) { t = l ? l : r; } else if (l->y > r->y) { merge(l->r, l->r, r); t = l; } else { merge(r->l, l, r->l); t = r; } upd(t); } void insert(pTreap &t, pTreap it) { if (!t) { t = it; } else if (it->y > t->y) { split(t, it->l, it->r, it->x); t = it; } else { insert(it->x < t->x ? t->l : t->r, it); } upd(t); } void erase(pTreap &t, int x) { if (t) { if (t->x == x) { merge(t, t->l, t->r); } else { erase(x < t->x ? t->l : t->r, x); } } upd(t); } inline void inc(pTreap& t, int v, int delta) { if (delta > 0) { insert(t, allocTreap(v)); } else if (delta < 0) { erase(t, v); } } int sum(pTreap t, int x) { if (!t) { return 0; } else if (x < t->x) { return sum(t->l, x); } else { return cnt(t->l) + 1 + sum(t->r, x); } } inline int sum(pTreap t, int l, int r) { return sum(t, r) - sum(t, l-1); } }; namespace FenwickTrees { class FenwickTree { private: int n; std::vector v; public: inline void inc(int vx, int vy, int delta) { for (; vx < n; vx |= vx + 1) { Treaps::inc(v[vx], vy, delta); } } inline int sum(int xr, int yl, int yr) { int ans = 0; for (; xr >= 0; xr &= xr + 1, xr--) { ans += Treaps::sum(v[xr], yl, yr); } return ans; } inline int sum(int xl, int xr, int yl, int yr) { return sum(xr, yl, yr) - sum(xl-1, yl, yr); } inline FenwickTree(int n) : n(n), v(n, nullptr) { } }; }; class InvertionProcessor { private: int n; std::vector v; FenwickTrees::FenwickTree tree; int64_t count; inline int invForElement(int el) { return tree.sum(0, el-1, v[el]+1, n-1) + tree.sum(el+1, n-1, 0, v[el]-1); } inline void change(int el, int newVal) { count -= invForElement(el); tree.inc(el, v[el], -1); v[el] = newVal; tree.inc(el, v[el], +1); count += invForElement(el); } public: inline int64_t swap(int l, int r) { int lEl = v[l], rEl = v[r]; change(l, rEl); change(r, lEl); return count; } inline InvertionProcessor(int n) : n(n), v(n), tree(n), count(0) { for (int i = 0; i < n; i++) { tree.inc(i, i, +1); v[i] = i; } } }; using namespace std; int main() { ios_base::sync_with_stdio(false); int n, q; cin >> n >> q; InvertionProcessor proc(n); for (int i = 0; i < q; i++) { int a, b; cin >> a >> b; cout << proc.swap(a-1, b-1) << "\n"; } return 0; } Еще одна идея, как соптимизировать решение и отказаться от декарток: давайте запомним, какие значения могли оказаться в каждой вершине дерева Фенвика и вместо декарток внутри будем использовать деревья Фенвика только по сжатым значениям. Такое решение уже работает достаточно быстро, в отличие от первого. Код C++#include #include #include using namespace std; const int MAX_N = 200100; class FenwickTree { private: int n; vector v; public: inline void add(int i, int delta) { for (; i < n; i |= i+1) { v[i] += delta; } } inline int64_t sum(int i) { i = min(i, n-1); int64_t res = 0; for (; i >= 0; i &= i+1, i--) { res += v[i]; } return res; } inline int64_t sum(int l, int r) { if (l > r) { return 0; } else { return sum(r) - sum(l-1); } } inline void assign(int pN) { n = pN; v.assign(n, 0); } }; inline void sortAndRemoveDuplicates(vector& v) { if (v.empty()) { return; } sort(v.begin(), v.end()); int ptr = 1; int prev = v[0]; for (int i = 1; i < (int)v.size(); i++) { if (v[i] != prev) { prev = v[i]; v[ptr++] = v[i]; } } v.resize(ptr); } class FenwickTree2D { private: int n; vector< vector > vals; vector sums; public: inline void initAdd(int x, int y) { for (; x < n; x |= x+1) { vals[x].push_back(y); } } inline void prepare() { sums.resize(n); for (int i = 0; i < n; i++) { sortAndRemoveDuplicates(vals[i]); sums[i].assign(vals[i].size()); } } inline void add(int x, int y, int delta) { for (; x < n; x |= x+1) { vector &cur = vals[x]; int aY = (int)(lower_bound(cur.begin(), cur.end(), y) - cur.begin()); sums[x].add(aY, delta); } } inline int64_t sum(int x, int l, int r) { x = min(x, n-1); int64_t res = 0; for (; x >= 0; x &= x+1, x--) { vector &cur = vals[x]; int aL = (int)(lower_bound(cur.begin(), cur.end(), l) - cur.begin()); int aR = (int)(upper_bound(cur.begin(), cur.end(), r) - cur.begin()); res += sums[x].sum(aL, aR-1); } return res; } inline int64_t sum(int lx, int rx, int ly, int ry) { if (lx > rx) { return 0; } else { return sum(rx, ly, ry) - sum(lx-1, ly, ry); } } inline void assign(int aN) { n = aN; vals.resize(n); } }; int n, q; pair queries[MAX_N]; int p[MAX_N]; bool good[MAX_N]; FenwickTree2D f; int main() { ios_base::sync_with_stdio(false); int n, q; cin >> n >> q; int64_t cnt = 0; for (int i = 0; i < q; i++) { cin >> queries[i].first >> queries[i].second; queries[i].first--; queries[i].second--; } for (int i = 0; i < n; i++) { p[i] = i; } f.assign(n); for (int i = 0; i < n; i++) { f.initAdd(i, i); } for (int i = 0; i < q; i++) { int a = queries[i].first, b = queries[i].second; f.initAdd(a, p[a]); f.initAdd(b, p[b]); swap(p[a], p[b]); f.initAdd(a, p[a]); f.initAdd(b, p[b]); } f.prepare(); for (int i = 0; i < n; i++) { p[i] = i; f.add(i, i, +1); } for (int i = 0; i < q; i++) { auto invForElement = [&](int q) -> int { return f.sum(0, q-1, p[q]+1, n-1) + f.sum(q+1, n-1, 0, p[q]-1); }; auto change = [&](int q, int newVal) -> void { cnt -= invForElement(q); f.add(q, p[q], -1); p[q] = newVal; f.add(q, p[q], +1); cnt += invForElement(q); }; int a = queries[i].first, b = queries[i].second; int aEl = p[a], bEl = p[b]; change(a, bEl); change(b, aEl); cout << cnt << "\n"; } return 0; } 
•  » » » » 15 месяцев назад, # ^ |   0 У меня зашло и на дереве отрезков, когда я понял, что инверсии слева и справа связаны, и начал считать только одну из них. Но все равно 3.5сек: посылка.А еще у меня где-то там UB, видимо, потому что я ловлю WA1 на c++ 14, на котором мой прошлый код работал быстрее, чем на MSVC10.
 » 15 месяцев назад, # |   0 Ошибка в разборе задачи D: "количество закрывающих скобок до данной". Правильно будет "после"
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   0 Спасибо, исправлю.UPD: Уже исправлено :)
 » 15 месяцев назад, # |   0 help somebody, i cannot understand D proof...
 » 15 месяцев назад, # | ← Rev. 4 →   +8 problem E: — TLE — OK 1310 ms.(what i'm doing wrong?)
•  » » 15 месяцев назад, # ^ |   0 easily solved with avl on segment tree ....
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   0 I also passed with . Are you sure your solution with square root decomposition isn't actually because if it is it actually makes sense that your TLEd.UPD: Your solution really is .
•  » » » 15 месяцев назад, # ^ |   +5 yeah, you are right
•  » » 15 месяцев назад, # ^ |   0 I passed in under 2000ms when i changed to BIT from segment tree with Order statistics tree in
•  » » » 15 месяцев назад, # ^ |   0 How would you use BiT instead?
•  » » » » 15 месяцев назад, # ^ |   0 You need two information to perform the swaps in every query: At any index i, how many a[j] > a[i] such that j [1, i-1]. Let this value be x At any index i, how many a[j] < a[i] such that j [i+1, n]. Let this be y I only maintain the first information using BIT. The second information can be extracted as y = (a[i] - 1) - ((i - 1) - x)25530551
•  » » » » » 15 месяцев назад, # ^ |   0 Does the ordered tree act as multiset? Can we erase single value from ordered tree as we can delete a single value from multiset using iterator.
•  » » 15 месяцев назад, # ^ |   -33 logx has a higher growth rate than sqrt(x) for larger inputs
•  » » » 15 месяцев назад, # ^ |   +8 nooo... its just some hidden constant in pb_ds and segment tree
•  » » 15 месяцев назад, # ^ |   +15 I have a completely different algorithm that runs in time O(n log n + q sqrt(n)). It's here: 25590906 It is much simpler than the one in the editorial.Draw the permutation as a 2-D plot. The key things that you need to be able to do are to (1) count the number of points below and to the left of a query point and (2) insert and delete points into the plot.So we use a sqrt(n) decomposition of the plot into sqrt(n) by sqrt(n) squares of size sqrt(n). For each square we keep the number of points in it. We also keep a hierarchy of squares doubled in size. So there are .5 log n of these levels.To solve a query we first note that there is an ell-shaped part that is that is outside of the squares described above. These can be counted in O(sqrt(n)) time. We maintain the permutation and its inverse. So the horizontal part of the ell (and the vertical too) can be counted row by row. Now to count the number of points in the squares we peel off possibly the top row and column and just count them. Now we move into the next level of boxes that are twice as big. The total time for this count is therefore O(sqrt(n)).Inserting and deleting from the boxes is easy. Just make a pass through the levels. This takes O(log n) time.
 » 15 месяцев назад, # |   +2 This is truly one of the best editorials on CF till date. Giving hints and then the complete idea to the question is a good way to help us improve ourselves. Also, giving reference code in three different languages is a very appreciable effort. Congratulations to the writers of the contest for this excellent editorial and we hope to look more such editorials in the future.
 » 15 месяцев назад, # | ← Rev. 2 →   0 Can anyone help me get rid of that 1e018 in 9th test case in problem C. 25537798 There are other submissions where the same formula is used but have an AC.
 » 15 месяцев назад, # |   0 In problem C why do we have to binary search up to 2e9 not 1e9(it give WA)?Look at my submission with 1e9(25537413) and 2e9(25538410)???
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   +1 for test case n = 1e18 m =1 ans is greater than 1e9 (approx. sqrt(2)*1e9)) put n,m values in the equation you will get maximum possible ans for the problem n — m <= k * (k + 1)/ 2
 » 15 месяцев назад, # |   0 Can someone help me with the proof of — 785D — Anton and School — 2 , I am not getting the explanation given in tutorial . Thanks in advance
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   +2 Where didn't you undestand it? I'll try to explain it better.
•  » » » 15 месяцев назад, # ^ |   0 this part, this formula also means the number of ways to match the string with the sequence of zeros and ones of the same length
•  » » » » 15 месяцев назад, # ^ |   +1 Consider the number of ways to make a sequence of length x + y with x ones and y zeros. Won't it be ?Later, it's explained how to match an RSBS to every such sequence.
•  » » » » » 15 месяцев назад, # ^ |   +5 Is empty RSBS included in the answer?, e.g. for n=3,m=3 and string ((( ))), we include empty RSBS corresponding to 111000.
•  » » » » » » 15 месяцев назад, # ^ |   0 Yes, in the simplified version an empty string is included to the answer. Later in the solution, there won't be empty RSBS, because it will contain the iterated opening bracket.
•  » » » » » » » 15 месяцев назад, # ^ |   0 Got it. Thanx for the nice editorial :)
•  » » » » 15 месяцев назад, # ^ |   0 It's kind of equivalent to stars and bars also.
•  » » » » » 15 месяцев назад, # ^ |   +3 I understand the significance of (x+y)C(x) but I don't know how the author originally came up with it. I had the formula given below in mind, but I don't know how to reduce it. xC1*yC1 + xC2*yC2 + xC3*yC3 +....+ xC(min(x,y))*yC(min(x,y)) I would appreciate it if you could please explain the formula using stars and bars. Thank you!
•  » » » » » » 15 месяцев назад, # ^ |   0 I couldn't think of any intuitive way of explaining the problem from a stars and bars perspective. I'm just noting that its equivalent.
•  » » » » » » 15 месяцев назад, # ^ |   0 write xCi as xC(x-i).Observe that sigma(xCi*yCi) is coefficient of a^x in (1+a)^x * (1+a)^y.Convince yourself that x+yCx -1 is your reduced from.IDK why in editorial -1 is absent.
•  » » » » » » » 15 месяцев назад, # ^ |   +8 In editorial it is mentioned But we also have an additional condition: we must necessarily take the last opening bracketThus we are interested in sigma{ xCi * (y-1)C(i-1) ) } = (x+y-1)Cx[from i=1 to i=min(x,y)]
•  » » » 15 месяцев назад, # ^ |   0 How do you justify the statement " Also opening brackets appear earlier than closing brackers " ??
•  » » » » 15 месяцев назад, # ^ |   +1 I think it's obvious because in the simplified version we deal with the sequence like "((((...((()))))))))...))))" and every its subsequence will contain opening brackets earlier than closing brackets.
•  » » » » » 15 месяцев назад, # ^ |   0 Thanks a lot !! I forgot the earlier explanation of simplified version .
 » 15 месяцев назад, # |   0 Has anyone got AC in E using segment tree with multiset(supporting order stats)? I am getting TLE on #7.
•  » » 15 месяцев назад, # ^ |   0 TheTerminalGuy did, I guess. Here's his code. 25524777
•  » » » 15 месяцев назад, # ^ |   0 3978ms seems quite a risk. The same solution may not pass again.
•  » » » » 15 месяцев назад, # ^ |   +8 My code, 3337 ms.
•  » » » » 15 месяцев назад, # ^ |   0 cin / cout are to blame mostly.
•  » » » » » 15 месяцев назад, # ^ |   +5 I too used cin/cout. I guess the time is due to the find function being called every time before erasing some value. As we have inserted tge value in set we can be sure that it will be present in set and remove it without worrying about runtime error.
 » 15 месяцев назад, # |   +3 Было бы очень здорово, если все авторы оформляли разбор так же, как и вы. Спасибо!
 » 15 месяцев назад, # | ← Rev. 2 →   0 if problem E2 is data structures, it may be not hard to solve =))
 » 15 месяцев назад, # |   0 В задаче Div2C лучше находить ответ между 1 и min(n,2*10^9) вместо 10^9. Хоть на вердикт это не повлияет, но скорость увеличит на тестах, где n небольшое.
 » 15 месяцев назад, # |   +15 My funny task A solution. long sum = 0; for (int n = nextInt(); n > 0; n--) { long x = -next().codePointAt(0); sum -= (((13 * x + 4870) * x + 662555) * x + 39072170) * x + 846175272; } println(sum / 33660); Also fan fact, that all task contains test case with "404" answer.
•  » » 15 месяцев назад, # ^ |   +13 Haha! That is awesome, I had to stare at it for quite a long time to figure out how it worked. Excellent practice, thanks. May I ask how you fit that polynomial function?I know your program was meant to be cool and not short, but anyway it made me think of writing something where the main logic was in a one-line formula, like yours. So here's my "shortest code" submission, 127 non-whitespace characters (http://codeforces.com/contest/785/submission/25567260): #include int t, n; main() { scanf("%d\n", &n); while (n--) { char s[99]; gets(s); t += "4!8D6<"[*s%7]-48; } printf("%d\n", t); } Would love to see shorter solutions .. in any language!
•  » » » 15 месяцев назад, # ^ |   0 25547848 — just one line in python225745756 — just minified your code (without any thinking, only deleting unnessesary code)
•  » » » » 15 месяцев назад, # ^ |   +8 Knew people would make it shorter but not THAT MUCH shorter. :-O :-)
 » 15 месяцев назад, # |   0 in problem B why we are not doing pairwise comparison rather than separate comparison of l and r
 » 15 месяцев назад, # |   +5 Presentation of the editorial is really amazing... I think I'd never seen that before. Thanks a lot.
 » 15 месяцев назад, # | ← Rev. 5 →   0 for question E Can we have a 2D BIT where BIT[x][y] where x will denote block no and y is actual number depending on given input.Then each query is solved in sqrt(N)+log(block)*log(N) and updates also in sqrt(N)+ log(block)*log(N). Correct me if I am wrong..
 » 15 месяцев назад, # |   +5 Very detailed & useful tutorial. Thank you very much!
 » 15 месяцев назад, # |   +19 First time in my whole journey (which is albeit short), I have seen an editorialist with so much creativity and patience taking so much interest in really explaining the solutions in a comment. It's sad how whistle blogs about complaining all about this contest. More power to you, alex256.
•  » » 15 месяцев назад, # ^ |   +1 Thank you :)
 » 15 месяцев назад, # |   0 D is a very nice especially if one derives it without using the identity directly! Thank you for this problem.
 » 15 месяцев назад, # |   0 I tried to solve problemE with segment tree plus ordered multisets but I am getting TLE on test 7.The complexity of build function in my code in O(N * LOGN * LOGN * C). where C is the constant factor in segment tree.(C ≈ 4).http://codeforces.com/contest/785/submission/25568923Is there any way to optimize the build function.
•  » » 15 месяцев назад, # ^ |   +3 What do the query1 and query2 methods do?
•  » » » 15 месяцев назад, # ^ |   0 query1 calculates no of elements greater than val in ranger l to r and query2 calculates no of elements less than val in ranger l to r.
•  » » » » 15 месяцев назад, # ^ |   0 These 2 values are connected.Suppose you have the element x in the position i in the array and you know the answer to one of the queries, e.g. there are ans elements greater than x in [1,i-1]. This necessarily means there are i-1-ans elements smaller than x in [1, i-1]. Since the total amount of elements smaller than x is x-1, there x-1-(i-1-ans) = x-i+ans elements smaller than x in [i+1, N]. Thus, the total amount of inversions is x-i+2*ANS.This thing should reduce the constant of your solution. Also, don't use long long everywhere — this slows down the solution, which already runs pretty close to the TL.
•  » » » » » 15 месяцев назад, # ^ |   0 Thanks for this idea but I want to reduce the complexity of build function which works in O(n * log(n)2 * c) because for 7th test case , even the build function is not able to execute in 4s.
•  » » » » » » 15 месяцев назад, # ^ |   0 Does it? I just ran your build() function of CF for 250000 and it seems to take about 1.3s.
 » 15 месяцев назад, # |   0 Is there any divMod explanations? I don't understand how it works. Thanks
 » 15 месяцев назад, # |   +1 Is there any divMod explanations? I don't understand how it works. Thanks
•  » » 15 месяцев назад, # ^ |   +1 divMod is a function that computes a / b modulo m I don't understand how it works. At first instead of dividing it computes (a * inv(b)) % m where inv(b) is an inverse element for b. Inverse element can be computed using an extended Euclidian algorithm. You can learn more about this here
•  » » » 15 месяцев назад, # ^ |   +5 Thank you! That article is very easy to understand.
 » 15 месяцев назад, # | ← Rev. 2 →   0 why is it low+m and not the midvalue+m? in 785C
•  » » 15 месяцев назад, # ^ |   0 Because I write the binary search in this way. I exit from the binsearch when l=r. So the answer will be stored obviously in l
•  » » » 15 месяцев назад, # ^ |   0 Thanks :)
 » 15 месяцев назад, # | ← Rev. 2 →   0 Can Someone explain me why number of total possible valid sub sequence is x+yCx as explained in Editorial in 4th Question ? I am not able to understand that
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   0 Which part of the editorial you don't understand? I'll try to explain it better.
•  » » » 15 месяцев назад, # ^ |   0 "At first, let's simplify the problem: let our string consists of x + y characters, begins with x characters "(" and ends with y characters ")". How to find the number of RSBS in such string?Let's prove that this number is equal to x+y C x.This is what I am not able to understand. If we take a string that consists of x + y characters, begins with x characters "(" and ends with y characters ")", then how total number of RSBS is (fact(x+y) / fact(x)*fact(y) ) ?
•  » » » » 15 месяцев назад, # ^ |   0 There's a proof in the editorial. What exactly you don't understand in it?
•  » » » » » 15 месяцев назад, # ^ |   0 I didn't understand how did you decide to represent which bracket with 0 and which with 1. and so I am not able to understand the proof. Sorry if this is silly but I seriously do not get it
•  » » » » » » 15 месяцев назад, # ^ |   +6 OK. Let's take ANY sequence of x ones and y zeros. Now write it under the bracket sequence in the following way:Now let's take opening brackets under which we have zero and closing brackets under which we have one (green brackets on the picture).Now, we must prove that number of opening brackets will be equal to number of closing brackets. How to do it? Suppose we have z zeros under opening brackets and, therefore, x - z ones (because we have x opening brackets)under opening brackets. So the rest of ones are under closing brackets. Their count will be x - (x - z) = z (because we have x ones. So we have equal count of opening and closing brackets. So we took an RSBS in this way.Now more understandable?
•  » » » » » » » 15 месяцев назад, # ^ |   +8 Okay.. Now I completely got it.. Now it is much easier to visualize for me for the further part of your tutorial. So thank you so much for tolerating and quickly answering to my silly doubt. Truly appreciate your quick reply to each and every comment. Thank you so much.
•  » » » » » » » 15 месяцев назад, # ^ |   0 Does the difficulty of this task correspond to Div2?
•  » » » » » » » » 15 месяцев назад, # ^ |   0 I think yes, because 94 people in Div. 2 solved it. But I agree that it's harder than Div. 2 D level.
•  » » » » » » » 15 месяцев назад, # ^ |   0 How do we assign 0s and 1s?
•  » » » » » » » » 15 месяцев назад, # ^ |   0 You can choose any of the sequences that contain x ones and y zeros.
 » 15 месяцев назад, # |   0 in the problem:B we have to calculate the max distance between the periods that is the time between end of first period and start of second period but in the editorial why we are calculating int minR1 = infinity, maxL1 = -infinity; int minR2 = infinity, maxL2 = -infinity; for (int i = 0; i < n; i++) { maxL1 = max(maxL1, a[i].first); minR1 = min(minR1, a[i].second); } for (int i = 0; i < m; i++) { maxL2 = max(maxL2, b[i].first); minR2 = min(minR2, b[i].second); }
•  » » 15 месяцев назад, # ^ |   0 maxL1, maxL2 — maximum left ranges in chess variants and programming variantsminR1, minR2 — minimum right ranges in chess variants and programming variantsThen we use them for both cases. In first case we need the distance between minimum right chess range and maximum left programming range. So we simply use maxL2 - minR1. The same in the second case.
 » 15 месяцев назад, # |   0 In problem 785D Anton and School 2 for the case when we have x opening brackets and then y closing, total number of RSBS according to the editorial Should we subtract 1 from it? (case when we have x ones in the beginning and then y zeros as I understand is empty sequence which is not RSBS according to the statement).I was thinking in a bit different way about number of RSBS when we have x opening brackets and then y closing, if we sum over the length of first half we can find that number of RSBS is: But I don't know how to simplify this one. Maybe someone was doing similar things and achieved result?
•  » » 15 месяцев назад, # ^ |   +3 Should we subtract 1 from it? Yes, because in this formula we count an empty string as an RSBS. But in the further problem we don't have to subtract 1, because we always take the last opening bracket, so RSBS won't be empty.
•  » » » 15 месяцев назад, # ^ |   +8 Do you know is there a way to simplify this sum: ?
•  » » » » 15 месяцев назад, # ^ |   0 No, unfortunately I know a normal way how to simplify this to . I came to this simple formula bruteforcing the answer and then found that beautiful proof. So I didn't try to simplifity such expression.
•  » » » » 15 месяцев назад, # ^ |   0 Hi did you find any way to simplify this equation, Even the approach I am thinking boils to this equation
•  » » » » » 15 месяцев назад, # ^ |   0 This may help — Vandermonde's Identity. We can count this as taking i objects from a pile of x objects, and y - i objects from a pile of y objects, where i varies from 0 to Min(x, y). This is basically equivalent to taking a total of y objects total, from a collection of x + y objects. Hence, our summation above can be rewritten as:
•  » » » » 15 месяцев назад, # ^ |   +3 Multiply (1+x)^n1 and (x+1)^n2 See its binomial expansion. You will find the required ans to be coefficient of n1+1 in (1+x)^(n1+n2). Again use binomial to find coefficient. You will get formula given in editorial. Here n1=x, n2=y
 » 15 месяцев назад, # |   +5 I just solved problem E today. I can see somebody here has same approach with me: using Balanced BST (I choose Treap) on segment tree. My second submission run in O((N + Q) × log2(N)) time complexity and I got TLE. Then I reduce my solution to O(N × log(N) + Q × log2(N)) time complexity and got AC by reducing the build tree step to O(N × log(N)) time. More over, each node is a treap can be built in O(N) time. Hope this help someone implement this problem easier.
 » 15 месяцев назад, # | ← Rev. 4 →   -8 Isn't it the algorithm for Problem D?But I am getting Memory limit exceeded on test 6 verdict :( My Code#include #include #include using namespace std; typedef long long int ll; #define M 1000000007 vector dp[200001];// 2D vector to store nCr ll combinatorics_of(int n,int r) //return nCr { if(dp[n][r]!=0) return dp[n][r]; if(n==r) return 1; if(r==1) return n; return dp[n][r]=(combinatorics_of(n-1,r-1)%M+combinatorics_of(n-1,r)%M)%M; } int main() { string s; cin>>s; int l=s.length(); for(int i=0;i
•  » » 15 месяцев назад, # ^ | ← Rev. 3 →   0 But I am getting Memory limit exceeded on test 6 verdict :( Consider how much memory the line vector dp[200001]; consumes. It'll be bytes, which is about 20 GB. It won't fit any time limit. Isn't it the algorithm for Problem D? Yes, it is, but you need a way to find the number of combinations faster. To do this, you can look at my code, which is in the editorial.To do this, you can use a naive formula . To calculate this fast, you can do the following: Precalculate all the factorials under 106 by modulo. Learn how to divide by modulo. Dividing by modulo means multiplying by an inverse element. How to find the inverse element, see the article P. S I recommend you not to place you code directly in the comment. You may place a link to submission instead, or place your code to ideone or pastebin and provide a link to it. Or you can use spoilers, like this: C++ code#include using namespace std; int main() { cout << "Spoilers are good" << endl; return 0; } 
•  » » » 15 месяцев назад, # ^ | ← Rev. 2 →   +8 Thank you so much for the link :)P.S:The comment has been edited as it is recommended.
•  » » » 13 месяцев назад, # ^ |   +8 Thank you so much for the great editorial.For modular multiplicative inverse by extended Euclidean algorithm, we have a statement x = (x % m + m) % m. This will give an element in the range [0,m), right? My doubt here is can the modular inverse be negative. Else we could have written x = (x % m) directly. Sorry if this doesn't make any sense.
•  » » » » 13 месяцев назад, # ^ |   0 No, the modular inverse cannot be negative. When we deal with arithmetics by modulo, we always take integers in the [0;m) range.
 » 15 месяцев назад, # |   0 Hello, can some tell me what is wrong with this solution with C problem? 25806694Thanks in adavanced.
•  » » 15 месяцев назад, # ^ | ← Rev. 2 →   0 In the 7th test case your l > 2e9, so l > r and you don't enter the binary search and just print m+1 (that is l).
 » 15 месяцев назад, # | ← Rev. 2 →   0 why to use the logn time complexity ? This can be done in O(1). We dont need to use the binary search. At the end of mth day the no of grains in the barn is n — m; from the next day it will be like (m — (m+1) , (m — (m+2)), ... , (m — (m+k)) which can be written as k * (k+1)/2. lets formulate the equation n = (k *(k+1))/2. hence k^2 + k — 2*n = 0; the root is (-1 + (sqrt(1 + 4*2*n))/2. let this be s. if(s*s + s < 2*n) then add a day. day = m + s is the answer.
 » 15 месяцев назад, # | ← Rev. 2 →   +16 785D — Anton and School — 2I think this sentence is not correct in solution : number of RSBS in string that begins with x characters "(" and ends with y characters ")" equal to ( x + y)! / ( x! * y! ) it must be : ( ( x + y)! / ( x! * y ! ) ) — 1Why we subtract 1 ?In solution written that : formula also means the number of ways to match the string with the sequence of zeros and ones of the same length, which contains exactly x onesLets look picture in example : ( ( ( ) ) ) ) one combination is 1 1 1 0 0 0 0 If we create string with following algorithm which is written in solution : all the opening brackets that match zeros and all the closing brackets that match ones Resulting string will be empty string. And empty string is not RSBS. And this means we must subtract 1 . But Code work fine. Because in code we write ( x + y-1)! / ( x! * (y-1)! )_ ( explained in solution ). This prevent taking empty string
 » 8 месяцев назад, # |   0 Can someone help me with my solution of Problem E ? Link: https://ideone.com/500vNF I am using segment tree with each node having a set .