Common Board| Show all threads Hide all threads Show all messages Hide all messages | | fails at test 28 | Gautr | 1014. Product of Digits | 7 Jan 2021 07:38 | 1 | I don't know the problem use std::io; use std::io::BufReader; use std::io::BufRead; fn minimal_product_digit(n: i64) -> i64{ if n == 0 {return 10}; if n < 10 { return n};
let f : Vec<i64> = vec![2,3,5,7]; let mut aux = n; let mut ret : Vec<i64> = Vec::new(); for i in f{ if aux % i== 0 { loop{ aux/=i; ret.push(i); if aux % i != 0 { break; } } } }; if ret.is_empty() || aux > 1 { return -1; }
match ret.iter().fold(0,|acc,elem| if *elem == 3{acc + 1} else {acc}) { 1 => { let index = ret .iter().position(|&x| x == 3).unwrap(); if index > 0{ ret.remove(index); let k = ret.get_mut(index - 1).unwrap(); *k = 6; ret.sort();
} } _ => () } let mut v : Vec<i64> = Vec::new(); for i in ret{ match i { 2 | 3=> match v.last_mut(){ None => v.push(i), Some(last) if i ==3 && *last == 2 => v.push(i), Some(last) => { let valor = *last; if (valor * i) < 10{ *last = valor*i } else{ v.push(i); } } } _ => v.push(i) } } v.sort(); v.iter().fold(0, |acc, elem| acc * 10 + elem) } fn main() { let mut line = String::new(); let mut stdin = BufReader::new(io::stdin()); stdin.read_line(&mut line).unwrap(); let lim = line.trim().parse::<i64>().unwrap(); println!("{:?}",minimal_product_digit(lim)); } | | When some n you can place one circle on the center not? | Temirlan | 1984. Dummy Guy | 6 Jan 2021 20:58 | 1 | When n > 5 I guess, you can place one or more circles to free place within polygon? I assume that answer for 5 and 6 is same | | No subject | TROFI | 1370. Magician | 6 Jan 2021 17:10 | 1 | Edited by author 06.01.2021 17:11 | | Read carefully the statement | Deepesson | 1844. Warlord of the Army of Mages | 5 Jan 2021 02:06 | 1 | One doesn't have to execute their actions followed by the other. For instance: Sandro can execute 7 consecutive actions and after that Zagamius could execute 20. So basically, their turns don't need to be consecutive. Misinterpretation will lead to WA#4 or WA#5. Edited by author 05.01.2021 02:08 | | Remark on the problem statement | InstouT94 | 1422. Fireflies | 4 Jan 2021 22:32 | 2 | It is not said in the condition that the points have different coordinates. Can points have the same coordinates? There are no duplicate points in tests. | | Hint | Yerdaulet | 2002. Test Task | 3 Jan 2021 20:40 | 1 | Hint Yerdaulet 3 Jan 2021 20:40 in some cases, there are more than 1 current user | | Solution is very intuitive. | Mahilewets | 2095. Scrum | 2 Jan 2021 20:06 | 2 | Count numbers X and Y of quiet days for vacations given by intervals [1;r] and [1;l-1]. The answer to the problem would be ANS=X-Y. How to count X and Y? In the first step, we eliminate every 2th. That is, CNT_0=r and and CNT_1=r//2 In the second step, CNT_2=CNT_1//3. And so on. Until CNT > 0. Last non-zero CNT is the answer. Yes, but you should prove that the number of steps is short enough. Here is some sketch of the proof. After deleting all 2nd numbers we are with $\frac{n}{2}$ numbers, after erasing all 3rd numbers we are with $\frac{2}{3}\cdot \frac{n}{2} = \frac{n}{3}$ numbers, after erasing all 4th numbers we are with $\frac{3}{4}\cdot \frac{n}{3} = \frac{n}{4}$ numbers and so on, after erasing every $k$-th number we are left with $\frac{n}{k}$ numbers, and we stop when $\frac{n}{k} < (k+1)\implies k \approx \sqrt{n}$, so after $O(\sqrt{n})$ steps the algorithm stops. Edited by author 02.01.2021 20:07 Edited by author 02.01.2021 20:07 Edited by author 02.01.2021 20:09 | | WA #7 | Deepesson | 1476. Lunar Code | 2 Jan 2021 00:25 | 3 | WA #7 Deepesson 2 Jan 2021 00:01 The 7th test case is: 2 5 1 And my program outputs 348. I've tried to brute-force, and I got the same result. Did I misunderstand the problem? What should be the output for this test case? Ok, the answer is 780, but I don't know why. Ok, I'm stupid. Here's a function that checks if a matrix respects the Lunar Condition. bool lunar_check() { for(int i = 0; i != N-1;++i) { int count = 0; for(int j = 0; j != M;++j) { count += (matrix[j][i]==0&&matrix[j][i+1]==1); } if(count>K) return false; } return true; } I hope that nobody else's have problems reading the statement. ;-; | | Case #4 | Deepesson | 1476. Lunar Code | 1 Jan 2021 22:45 | 1 | Input: 1 40 1 Output: 1099511627776 | | This problem is very hard(easy),I cannot(can) solve it! | Accepted | 1000. A+B Problem | 1 Jan 2021 04:46 | 2 | we can use the netflow algorithm(+ operator) to solve this problem. #include <cstdio> #include <cstring> #include <algorithm> #define MAXN 5 using namespace std; const int INF=1<<30; int n,m,flow[MAXN][MAXN],pre[MAXN],cur[MAXN],gap[MAXN],d[MAXN],g[MAXN],l[MAXN][MAXN]; int Maxflow_Isap(int s,int t,int n) { memset(d,-1,sizeof(d)); memset(pre,-1,sizeof(pre)); memset(gap,0,sizeof(gap)); gap[s]=n; int u=pre[s]=s,v,maxflow=0; while (d[s]<n) { v=n+1; for (int i=cur[u];i<=g[u];i++) if (flow[u][l[u][i]] && d[u]==d[l[u][i]]+1) { v=l[u][i];cur[u]=i;break; } if (v<=n) { pre[v]=u;u=v; if (v==t) { int dflow=INF;u=s; for (int i=v;i!=s;i=pre[i]) dflow=min(dflow,flow[pre[i]][i]); maxflow+=dflow; for (int i=v;i!=s;i=pre[i]) { flow[pre[i]][i]-=dflow; flow[i][pre[i]]+=dflow; } } } else{ int mindist=n; for (int i=1;i<=g[u];i++) if (flow[u][l[u][i]]) mindist=min(mindist,d[l[u][i]]); if (!--gap[d[u]]) return maxflow; gap[d[u]=mindist+1]++;cur[u]=1; u=pre[u]; } } return maxflow; } void setsize(int x,int y,int c) { flow[x][y]=c; l[x][++g[x]]=y; l[y][++g[y]]=x; } int main() { scanf("%d%d",&n,&m); setsize(1,2,n); setsize(2,4,n); setsize(1,3,m); setsize(3,4,m); printf("%d\n",Maxflow_Isap(1,4,4)); return 0; } Thank you for this code, I'm curious to know, is there any shorter form of this i can use for a contest? | | It is not possible to find solution using bruteforce for python. | master8282 | 1005. Stone Pile | 1 Jan 2021 03:21 | 2 | Since 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. | | Hint | Mickkie | 2132. Graph Decomposition. Version 2 | 30 Dec 2020 19:37 | 2 | Hint Mickkie 29 May 2020 00:50 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 | | brute-force | lian lian | 1535. The Hobbit or There and Back Again | 29 Dec 2020 20:15 | 2 | 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])) | | WA #5, HELP ME PLEASE! ! ! ! | zhiganov_v | 1351. Good Gnusmas – Dead Gnusmas | 28 Dec 2020 22:49 | 1 | i have got WA on test #5. Help me please. Thanks | | Hint | OpenGL | 1514. National Park | 28 Dec 2020 19:50 | 2 | Hint OpenGL 3 Aug 2009 20:02 If you got TLE on test>28, try this test 50000 0 0 0 0 ... 50000 points (0,0) 0 0 Re: Hint Md sabbir Rahman 28 Dec 2020 19:50 Thanks man, that really helped | | what is the way to the solution? | TinyJanssen | 1889. Airport Announcements | 28 Dec 2020 16:44 | 3 | 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 | | Has anyone passed using only randomization without cheating ? | Manciu Ion | 1394. Ships. Version 2 | 27 Dec 2020 23:43 | 5 | You mean without even single magic number for single test? 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? | | Explanation of problem statement | SkidanovAlex | 1740. Deer is Better! | 27 Dec 2020 14:14 | 4 | 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. 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. | | кривое условие | Rybinsk SAAT (Nechaev, Kiselev, Mirzoyan) | 1740. Deer is Better! | 27 Dec 2020 14:04 | 50 | кривое условие Rybinsk SAAT (Nechaev, Kiselev, Mirzoyan) 1 Nov 2009 13:12 как понимать _минимальное_ и _максимальное_ время ??? 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 =) 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 greedy is right? | Edric Mao | 1108. Heritage | 27 Dec 2020 11:43 | 5 | 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? |
|
|