Common BoardSince the requirements became stronger, and time was reduced from 2 sec down to 1 sec, now it is not possible to resolve the task using bruteforce method, python is very slow for such hard requirements. Even I do empty loops the taken time is already about 1.3 sec. from time import time time_before = time() len_lst = 20 for i in range(1, ((2 ** len_lst) // 2) - 1):
for j in range(len_lst): pass
print(time() - time_before) >>> 1.3192360401153564 I think for Python the time should be rolled back to 2 sec. Of cause if I use bruteforce on "C" it takes about 0.2 sec, but Python is not "C". Finally I could resolve the task on Python using DP for 0.65 sec. This problem is easier than rating should be if you know the trick. Invariant: graph G is decomposable if and only if all the connected components of G has even number of edges. A tree is very easy to be decomposed. Creating a tree equivalent to each connected component will lead to the answer. Hope this help, Mick :) It helped me a lot, thank you! I read a proof of the fact that any connected graph with even number of edges is decomposable, but it was quite complicated and didn't allude at any good algorithm underneath. Your idea is much simpler and easier to proof I don`t understant brute-force , who can give your code to me ? mail: k13795263@yahoo.cn Edited by author 23.08.2008 05:40 I have a brute-force code for cheking answers Python 3.8 def summa(a): ans = 0 for i in range(len(a)): ans += a[i] * a[i - 1] return ans def recursion(n, do_etogo): a = True mn = 10 ** 9 mx = 0 mnansn = [] mxansn = [] for i in range(2, n + 1): if i in do_etogo: continue a = False mnans, mxans, mnansm, mxansm = recursion(n, do_etogo + [i]) if mnans < mn: mn = mnans mnansn = [mnansm] elif mnans == mn: mnansn.append(mnansm) if mxans > mx: mx = mxans mxansn = [mxansm] elif mxans == mx: mxansn.append(mxansm) if a: return summa(do_etogo), summa(do_etogo), do_etogo, do_etogo return mn, mx, mnansn, mxansn n = int(input()) print(recursion(n, [1])) i have got WA on test #5. Help me please. Thanks If you got TLE on test>28, try this test 50000 0 0 0 0 ... 50000 points (0,0) 0 0 Thanks man, that really helped I tried the following: For every recognized language find the minimum and the maximum possible lines. Then find the maximum and minimum possible lines for all. For minimum to maximum test if it divides N. This solves the first four tests. Is this the right way? Try to form k languages (or k groups) where k is divider of N. Mine is N^2 solution. I go through the divisors of the number N and check if the array can be split into I phrases by the condition Sorry for my English You mean without even single magic number for single test? Yes. Formally I can write code, that handle particular cases (e.g. patalogical cases having a bunch of repeating ships and rows), but is it somehow better then to find a single seed for the only case, which my solution cannot pass? So, if you can't understand what author of the problem meant, you're not alone :o) He meant the following: chukcha goes from A to B and he covers each K kilometers in H hours. But the speed whithin this interval is not constant: he can cover K minus eps kilometers within first second of H hours and remaining eps kilometers in the remaining time (and visa versa). It leads to the problem itself: what speed distribution along the interval leads to the minimum time to reach destination and what distribution leads to maximum time. Thank you for your explanation. And it turns out that the deer can cover K kilometers in 0.0000000001 second. hehe. Thanks The problem is just from Russia. Pay attention, the Chukchi is running, not an Eskimo, not an Indian, but a Chukchi. And in Russia everything is relative. And the position of the Chukchi is relative. That is, the Chukchi is located somewhere in the Yamal-Nenets district. On the territory within a radius of 100 kilometers from the telephone tower. In 2 hours he will be in an area within a radius of 100 kilometers from another telephone tower. That is, he will reach Moscow in 4 hours, plus or minus 2 hours. Something like this. Translation problems. как понимать _минимальное_ и _максимальное_ время ??? Edited by author 01.11.2009 13:12 да да можно ездить в любом направлении и вообще не доехать до участка вообще не доехать вроде как низя, т.к. "время, за которое чукча сможет доехать от чума до избирательного участка" значит все таки он должен доехать, но все-таки не понятно, что такое максимальное время... ну например для первого теста можно например часов 20 покататься от дома и обратно а за оставшие часа 3 доехать до участа Разве не так? в принципе можно, непонятное условие Чукча едет только по прямой в направлении изб участка. только появляется вопрос что тогда считать минимальным и максимальным временем? и еще не понятно его олени могут только отрезками передвигаться или это просто для вычисления скорости? максимальное и минимальное времена равны ? нет а времена дожны быть целыми числами? половину времени выводить как 0,5 или как 0,3? Edited by author 01.11.2009 13:58 Edited by author 01.11.2009 13:58 0.5 только вот как это вообще получается?? Кто решил дайте какой-нибудь тест с ответом) например на данные 30 12 1 например вход 11 2 1 то мин будет 5,5 это если чукча добравшись до участка отпустил олении бежать дальше а макс будет 6 если он в точе 10 остановился подождал 0,5ч и доехал до участка +0,5 Why he waits 0.5 hour at point 10? Not 1.5 hours, or 150000 hours??? Олени работают как трамвай o_O Главное спрыгнуть в нужный момент? :) So maxtime=mintime=l*h/k??? If deers like trams =) second test is 30 11 1 Dirty Debug? :) my result for 30 11 1 is: 2.72727 3.00000 is this correct ? ответы будут всегда целыми! уловие кривое ответ на тест: 30 11 2 4.000 6.000 ответы будут всегда целыми! уловие кривое ответ на тест: 30 11 2 4.000 6.000 Thanks luckman. I got AC after your explanation. ответы будут всегда целыми! уловие кривое ответ на тест: 30 11 2 4.000 6.000 Who can explain how Chykcha can arrived to end point after 4 hours of traveling? His position must be 11*2 = 24 < 30. He use Nitro at last second? :)) Уважаемые жюри и участники, решившие эту задачу с первой попытки (впрочем и все те, кто решил до обьяснения luckman'a), обьясните пожалуйста, как вы из заданного условия поняли истинную задачу и её решение? Я этого не могу понять. Автору мое недопонимание =))) Я могу понять. Такую задачу я когда то решал на мат-ке. Не сразу вспомнил решение, но улыбнуло) Я могу понять. Такую задачу я когда то решал на мат-ке. Не сразу вспомнил решение, но улыбнуло) Can you give right proof of this crazy solution? Я могу показать, как ехать так, чтобы он приехал за максимальное и минимальное время. Доказать, что это минимальное и, соответственно, максимальное время думаю тоже можно, хотя за это браться не буду. Ну тут всё относительно логично. Первое о чём думаешь - почему дано, что олени пробегают отрезок за одинаковое время, а не дана скорость их движения. Второе - откуда может взяться максимальное время вообще. Ведь можно не бежать к точке назначения. Но раз оно есть, значит олени бегут некоторым логичным образом. Тут в свете первого пункта есть 2 варианта - они бегут по прямой или они бегут по ломаной, образованной вышеупомянутыми отрезками. Но отрезками можно тоже бежать бесконечно долго, по-этому даже если бежать отрезками, то надо бежать кратчайшим путём. Отсюда получается некоторое максимальное время, которое, кстати, является правильным для этой задачи. Но если бежать отрезками, то максимальное и минимальное время совпадают. Тогда зачем их выводить отдельно. Можно, конечно, предположить, что тут подвох, но, всё-таки, чаще всего, в задачах не требуется выводить дублирующиеся данные. По-этому концепция с отрезками отпадает. Остаётся только вариант с прямой. Но тут опять надо придумать откуда возьмётся разное время. Опять таки в голову приходит очень необычно заданная скорость движения. Если подумать, то можно заметить, что не сказано, что олени движутся равномерно. Значит они могут пробегать отрезок как угодно. значит они могут пробежать до любой точки внутри последнего отрезка за эпсилон часов. Значит минимальное время -время, необходимое для пробега всех целых отрезков + эпсилон. А максимальное, соответственно, получится, если в последнем нецелом отрезке ехать в течении почти всего времени со скоростью эпсилон, а потом проехать весь отрезок за эпсилон часов. Но так как результат надо вывести с некоторой точностью, то этим эпсилон можно пренебречь :) Edited by author 01.11.2009 22:38 Edited by author 01.11.2009 22:38 To the ones who see all this russian and are confused about the problem statement: Don't worry, the problem statement is correct and it has a very simple and logical solution. This problem is really hard to understand, so I just solved it, though I still don't understand why my solution is wright. Deers using nitro is fucking confusing... imagine running away from cops in NFS on deer...and from what part of deer's body would the visualization of nitro take place?) Nice proff. So I was right , that animals can use Nitro =) So "deeper" tricks rarely can be meeted in problems. I apologize to the author. я написал решение выходит Чукча реально врубает нитро(при мин) и числа целые))) The problem is abs. adequate. We have bounded information and must'n use brain instead of facts. Answer for problem is best when given information as foundation is used. Это очень неадекватная задача. Может это кому нибудь поможет: Сказано что олени пробегают любой участок длины k за h часов, но ни кто не сказал что они бегут этот участок с одинаковой скоростью. Edited by author 01.11.2009 15:03 author, kill yourself by hitting the wall! Edited by author 01.11.2009 15:08 Alex Tolstov (Vologda STU) +100500 Dear friends! Don't scold the author. He gave us an excellent reason to communicate with each other. The discussion of the problem is the longest and the most interesting during this contest! And while you are trying to understand how the deers can run at infinite speed, the other participants are solving other problems ;) как маршрутка "Оставите на выборах" The problem is just from Russia. Pay attention, the Chukchi is running, not an Eskimo, not an Indian, but a Chukchi. And in Russia everything is relative. And the position of the Chukchi is relative. That is, the Chukchi is located somewhere in the Yamal-Nenets district. On the territory within a radius of 100 kilometers from the telephone tower. In 2 hours he will be in an area within a radius of 100 kilometers from another telephone tower. That is, he will reach Moscow in 4 hours, plus or minus 2 hours. Something like this. Translation problems. Тупейшая задача. Я только что получил AC.Я понимаю задачу так: олени могут пробежать только k километров.k/2 или 0.75*k километров пробежать не могут.Можно себе представить, что олени не бегут, а телепортируются на k километров за h часов, причём всегда в одном и том же направлении.Когда до участка меньше, чем k километров, то чукча может остановиться(min время), а может телепортироваться последний раз(max время). Edited by author 10.09.2011 01:38 why taking the biggiest fraction of remain assure that the church gets the minimized? Please, anybody explain! Im also interested in answer! RUS можно разобрать на первом примере. 1/2, 1/3 1 - (1/2) - (1/3) = (1/6) Пусть следующий элемент в массиве будут равен x. Тогда доля для церкви будет составлять (1/6)- x . Пусть оно будет равно y Следует: x + y = (1/6) Тогда для минимизации y, нужно максимизировать x. Also wondering... anyone can prove it? If you decide not to repeat my mistake, then the 49th check is that the king must bypass the black pawn in order to catch up with the white one, I will not talk further, but just give you an example: 8 a3 d7 e6 Answer:BLACK WINS Try: 2 Correct answer is 2 1 Main idea is to split cube into 8 parts and query/add for each one. Here is my code that have TL6. Any ideas of how to improve it? import java.io.*; public class P1470 { static int [] tree = new int[10000000]; private static int n; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); n = Integer.valueOf(reader.readLine()); while (true) { String line = reader.readLine(); if (line.startsWith("1")) { add(new Ufo(line)); } else if (line.startsWith("2")){ writer.println(query(new Region(line))); } else { break; } } writer.flush(); } private static int query(Region region) { return doQuery(region, new Region(0, 0, 0, n - 1, n - 1, n - 1), 0); } private static int doQuery(Region q, Region r, int node) { if (!r.overlaps(q)) return 0; if (q.contains(r)) { return tree[node]; } int xMid = (r.x1 + r.x2) / 2; int yMid = (r.y1 + r.y2) / 2; int zMid = (r.z1 + r.z2) / 2; return doQuery(q, new Region(r.x1, r.y1, r.z1, xMid, yMid, zMid), node * 8 + 1) + doQuery(q, new Region(xMid + 1, r.y1, r.z1, r.x2, yMid, zMid), node * 8 + 2) + doQuery(q, new Region(xMid + 1, r.y1, zMid + 1, r.x2, yMid, r.z2), node * 8 + 3) + doQuery(q, new Region(r.x1, r.y1, zMid + 1, xMid, yMid, r.z2), node * 8 + 4) + doQuery(q, new Region(r.x1, yMid + 1, r.z1, xMid, r.y2, zMid), node * 8 + 5) + doQuery(q, new Region(xMid + 1, yMid + 1, r.z1, r.x2, r.y2, zMid), node * 8 + 6) + doQuery(q, new Region(xMid + 1, yMid + 1, zMid + 1, r.x2, r.y2, r.z2), node * 8 + 7) + doQuery(q, new Region(r.x1, yMid + 1, zMid + 1, xMid, r.y2, r.z2), node * 8 + 8); } private static void add(Ufo ufo) { doAdd(ufo, new Region(0, 0, 0, n - 1, n - 1, n - 1), 0); } private static void doAdd(Ufo ufo, Region r, int node) { if (!r.contains(ufo)) return; tree[node] += ufo.count; if (r.isPoint()) return; int xMid = (r.x1 + r.x2) / 2; int yMid = (r.y1 + r.y2) / 2; int zMid = (r.z1 + r.z2) / 2; doAdd(ufo, new Region(r.x1, r.y1, r.z1, xMid, yMid, zMid), node * 8 + 1); doAdd(ufo, new Region(xMid + 1, r.y1, r.z1, r.x2, yMid, zMid), node * 8 + 2); doAdd(ufo, new Region(xMid + 1, r.y1, zMid + 1, r.x2, yMid, r.z2), node * 8 + 3); doAdd(ufo, new Region(r.x1, r.y1, zMid + 1, xMid, yMid, r.z2), node * 8 + 4); doAdd(ufo, new Region(r.x1, yMid + 1, r.z1, xMid, r.y2, zMid), node * 8 + 5); doAdd(ufo, new Region(xMid + 1, yMid + 1, r.z1, r.x2, r.y2, zMid), node * 8 + 6); doAdd(ufo, new Region(xMid + 1, yMid + 1, zMid + 1, r.x2, r.y2, r.z2), node * 8 + 7); doAdd(ufo, new Region(r.x1, yMid + 1, zMid + 1, xMid, r.y2, r.z2), node * 8 + 8); } static class Region { int x1, y1, z1, x2, y2, z2; Region(String s) { String[] split = s.split("\\s"); x1 = Integer.valueOf(split[1]); y1 = Integer.valueOf(split[2]); z1 = Integer.valueOf(split[3]); x2 = Integer.valueOf(split[4]); y2 = Integer.valueOf(split[5]); z2 = Integer.valueOf(split[6]); } Region(int x1, int y1, int z1, int x2, int y2, int z2) { this.x1 = x1; this.y1 = y1; this.z1 = z1; this.x2 = x2; this.y2 = y2; this.z2 = z2; } boolean contains(Ufo ufo) { return ufo.x >= x1 && ufo.x <= x2 && ufo.y >= y1 && ufo.y <= y2 && ufo.z >= z1 && ufo.z <= z2; } boolean contains(Region r) { return overlaps(r) && x1 <= r.x1 && x2 >= r.x2 && y1 <= r.y1 && y2 >= r.y2 && z1 <= r.z1 && z2 >= r.z2; } boolean overlaps(Region r) { return r.x1 <= x2 && r.x2 >= x1 && r.y1 <= y2 && r.y2 >= y1 && r.z1 <= z2 && r.z2 >= z1; } boolean isPoint() { return x1 == x2 && y1 == y2 && z1 == z2; } } static class Ufo { int x, y, z, count; Ufo(String s) { String[] split = s.split("\\s"); x = Integer.valueOf(split[1]); y = Integer.valueOf(split[2]); z = Integer.valueOf(split[3]); count = Integer.valueOf(split[4]); } } } Hi, try searching for Fenwick Tree's in 3 Dimensions. How can i improve my O(n ^ 2 * logN) time and O(n * n) memory too pass all tests? int n, y[2004], index = 1, maximum = 1, rati; pair<int, int> x[2004]; map<int, int> s[2004]; int main() { cin >> n; for(int i = 0; i < n; i++){ cin >> x[i].first; x[i].second = i; y[i] = 1; } sort(x, x + n); for(int i = 1; i < n; i++) { for(int j = 0; j < i; j++){ if(y[i] < s[j][x[i].first - x[j].first] + 2 && x[i].first - x[j].first != 0){ y[i] = s[j][x[i].first - x[j].first] + 2; if(maximum < y[i]){ index = i; maximum = y[i]; rati = x[i].first - x[j].first; } } s[i][x[i].first - x[j].first] = s[j][x[i].first - x[j].first] + 1; } } cout << maximum << "\n"; int val = x[index].first, i; cout << x[index].second + 1 << " "; for(i = index - 1; i >= 0; i--) { if(val - x[i].first == rati && rati != 0) { val = x[i].first; cout << x[i].second + 1 << " "; } } return 0; } You can use a hashmap instead of a red-black tree to get AC. Just remember to use the __gnu_pbds::cc_hash_table (header <ext/pb_ds/assoc_container.hpp>) as it's about 3 times faster than the std::unordered_map. Number of zeros in bracket: 0 1 2 3 4 Sequence : (1) (10) (100) (1000) (10000) 1 is found at : T0+1 T1+1 T3+1 T4+1 T5+1 Value of Ti+1 : 0+1 1+1 3+1 6+1 10+1 The i-th triangular number is the sum of the i natural numbers from 1 to i. Ti = i(i+1)/2 i-th '1' is located at (Ti+1)-th position. Let, z = (Ti + 1) = (i(i+1)/2) + 1 -> z = (i^2 + i + 2)/2 -> 2z = i^2 + i + 2 -> (1)x(i^2) + (1)x(i^1) + (-2(z-1)x(i^0) = 0 So, now if we solve for i using quadratic formula, i = (-1 +- squareRoot(8z-7))/2 [do calculation on your own] z = {1,2,4,7,11,...} plugin these values and you will find that squareRoot(8z-7) = an integersquare number for any z. So, a number belongs to z only and if only squareRoot(8z-7) can produce an integer. And here z is the position number where the digits are 1. [code deleted] Edited by author 24.12.2020 19:00 Edited by moderator 14.02.2021 18:16 Бред. В самом деле, достаточно искать символ, который чаще всего встречается.... так не работает работает, не мне одному приходят в голову умные мысли... Please, think about the problem yourself at first! I think you could use this problem to exercise your heuristics and optimization skills and thus I'm sharing a solution that is both easy to think and implement so that somebody less experienced might learn new strategies in optimization problems. ////// Yes, it's a Vehicle Routing Problem, as even confirmed by the author on this forum. Firstly, you can compute —with Dynamic Programming— optimal distance visiting some subset of nodes starting at node 0 and ending at some other node. Let dp[S][last] be the state of such DP, which computes the smallest path cost that visits each vertex of S once and starts at 0 and ends at last. This is a classic TSP DP problem that can be computed in O(N^2 2^n). Note, that you have to use a type shorter than 32-bit to store the DP. The cost of a trip is then dp[S][last] + D(last, 0). Generate a starting solution that performs a trip for each lorry, M trips in total. So far, nothing a beginner cannot do! Perform heuristic search to improve it. I used a Large Neighbourhood Search heuristic. Remove some number of lorries from trips from the CURRENT_SOLUTION and try to insert them one by one again. That is, greedily calculate the cost of insertion, using DP, of each lorry in each trip —or creating a new trip— and choose the lorry and a trip with smallest possible value. Decide if the obtained repaired solution is the new CURRENT_SOLUTION. I implemented this decision using Simulated Annealing, but you can simply do it if the repaired solution has a better cost. If the CURRENT_SOLUTION is better than the BEST_SOLUTION, well, you know what to do! I started from the small number of removed lorries and gradually increased it if after some iterations there weren't an update to the BEST_SOLUTION. This is a gradual increase of Neighbourhood. In fact, my solution is terribly inefficient, and I could use better data representation and save time making some calculations, improved heuristic by adding more complex rules, and perhaps get rid of the DP step in favor of simple random greedy insertions. But, I just decided to keep things simple. 0 0 0 1 0 0 2 1 1 2 2 1 ans Invalid Совет для тех кто решает векторами, лично у меня не получилось сдать задачу векторами, пришлось писать уравнения прямой в пространстве 49 9 9 9 9 9 9 14 14 34 34 34 34 34 42 42 42 42 42 47 49 57 66 68 68 68 68 71 71 71 71 71 74 74 97 97 97 97 97 97 97 100 100 100 100 100 100 100 100 100 100 227 235 264 292 298 322 327 341 820 I have to say ,I'm toooooooo stupid..... wa haha Accpeted congratulations , looking forward another rejudgement hahaha Thanks for the good test ! Are the any other inputs you mined here bit by bit? :) Please share them with us, don't hesitate. What is the best way to collect information for particular test? Time/100ms (if there is window for that), memory/100kB, WA, TLE, RE... what else? What maximum number of bits per try? Let's call it `bitrate`. Serious enough term for further discussion =), isn't it? How to match particular test? Binary search for hash value of the input? Please, reveal your super-duper technology with your fancy-nancy metrics. Edited by author 18.12.2017 22:11 I just use stupid bianry search every veriable and submit many many many times I don't have better ideas and I have only test case 70... Edited by author 19.12.2017 05:09 //6 min 32.43 sec 4 100 71 42 14 4 97 57 47 34 5 100 71 42 42 9 5 100 100 74 9 9 5 100 74 66 49 9 5 100 100 71 42 9 5 100 100 71 42 14 5 100 71 68 68 34 11 97 97 97 97 97 97 68 68 34 34 34 The 83-rd test is almost the same. Can anybody post DP approach, if any exists? Dp[i][diff][c]: amount of pairs of numbers (A, B) of size i where S(A+B)-S(A)-S(B)=diff and we carry c from the sum of A and B Here we consider also number with leading zeroes, we can notice that **diff** is in the range [-460, 900] -maybe we can make it narrower- and that **c** is either 0 or 1. |
|