Common Board Edited by author 10.01.2016 23:58 input: 7 1 1000 2 500 501 999 3 499 502 800 4 400 503 700 output: 4 6 4 2 1 or 4 7 5 3 1 Chto za xren Test 5? Does anybody know what the hell is Test 5? Check if you comparing right prices for 2-rooms apartment when person lives single. #include <stdio.h> #include <stdlib.h> #include <math.h> #define MAX 16500 void prime(int n) { int i,j,temp,count=0; for(i=2;i<=MAX;i++) { temp=0; for(j=2;j*j<=i;j++) { if(i%j==0) { temp=1; break; } } if(temp==0) { count++; } if(count==n) { printf("%d\n",i); break; } } } int main() { int n,t,i; scanf("%d",&t); while(t--) { scanf("%d",&n); prime(n); } return 0; } Why i got this TLE. I think my idea is not wrong but why its occur? I don't understand. Pleas help me..... Edited by author 06.09.2015 20:29 Your algorithm is not wrong, but it cost too much time. Try "sieve of Eratosthenes". You can search it on wiki. Правильное решение (Accepted): using System; namespace _1086_Криптография { class Program {
static void Main(string[] args) { // считываем количество выводимых чисел int n = int.Parse(Console.ReadLine()); // создаем массив и считуем в него порядочные номера простых чисел int[] hip = new int[n]; for (int i = 0; i < n; i++) { hip[i] = int.Parse(Console.ReadLine());
} // определим максимальный элемент масива // можно исользовать цикл int[] hip1 = new int[n]; Array.Copy(hip, hip1, n); Array.Sort(hip1); // зададим массив упорядоченых простых чисео с запасом int[] val = new int[hip1[hip1.Length - 1]+2]; // зададим начальный ряд простых чисел val[0] = 2; val[1] = 3; val[2] = 5; val[3] = 7; // определяем простые числа делением на предыдущие простые числа // метод итераций построен на do while int k = 4; int i1 = 8; do { int reid = 0; for (int i = 0; i < k; i++) { if (i1 % val[i] == 0) {reid = 1; break; } } if (reid == 0) { val[k] = i1; k++; } i1++;
} while (k < hip1[hip1.Length - 1]+1); // вывод заданых простых чисел for (int i = 0; i < hip.Length; i++) { Console.WriteLine(val[hip[i]-1]); } } } } Edited by author 08.01.2016 17:23 Edited by author 08.01.2016 17:23 i have WA #2 #include <iostream> #include <stdio.h> using namespace std; int main() { int n, m; cin >> n >> m; int win = 0; for(int i = 0; i < m; i++) { int a; cin >> a; n -= a; if(i % 2 == 0) win = 2; else win = 1; }
cout << win << endl;
return 0; } First of all. If you get WA#1, check how you scan input stream, cause they've put some trash in file. I used the following idea. The whole number with base k divisible by ( k - 1 ), if sum( div( digit[ i ] ) ) is divisible by ( k - 1 ). Where digit[ i ] is k-based digit in input number ( char from input stream ); div( digit[ i ] ) is a remainder of division digit[ i ] * k by ( k - 1 ). Let see digit on i-th position, for example, it's A. So in decimal implementation it's equal to A * k ^ i. A * k ^ i = A * k^i - A * k^(i-1) + A * k^(i-1) = A * k^(i-1) * ( k - 1 ) + A * k^(i-1) A * k^(i-1) * ( k - 1 ) is divisible by ( k - 1 ), so we have to check only A * k^(i-1). If we repeat the same logic to this expression (i - 2) times, we see, that we have to check division A * k / ( k - 1 ). I tried my best to explain the main idea, sorry if it can't be understood. You don't need your "div()". Isn't it okay to just find the digital sum of the given number and add 1? Thank you. And we even can go a step further. Now see, A * k = A * k - A + A = A(k - 1) + A, So what we need to examine is just whether sum( digit[i]) is divisible by ( k - 1). input1 sd5=#124'ashds'#12#154'sah'; input 2 sd5:=#123+#12; output1: sd5=<span class=string>#124</span><span class=string>'ashds'</span><span class=string>#12</span><span class=string>#154</span><span class=string>'sah'</span>; I got WA1 and I don't understand why. Give me some tests please. Test #1 describe into problem statement. 10 3 3 4 5 1 What it means, we have range [0, 10] and start position in 3. And have 3 shifts. First shift we can go from 3 to [-1, 7] as -1 not in range we have only [7] positions. Second shift we can go to positions [2, 12] as 12 not in range we have only [2] position. Third shift we can go to positions [1, 3] as all of them in range we have 2 possible final states 1 and 3, minimal of them 1 and maximal 3. Answer will be 1 3. Another test: 100 50 4 1 2 4 8 Possible positions on steps: 0) [50] 1) [49, 51] 2) [47, 49, 51, 53] 3) [43, 45, 47, 49, 51, 53, 55, 57] 4) [35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65] Answer will be 35 65 What does it mean: "clockwise order"? How do you define clockwise order in notconvex polygon? For example: in picture like a snail what roundabout way is turned in the clockwise direction and what is not? Sorry for bad Enlish... Hi. Can you remember, what was the problem with test 14? how could it have been passed??? and with 0.031 because of the test cases are to easy.... you can use (next_permutation) easyly... Can anyone give me some tricky tests? 5 RGRBG 7 RBGBRGB 6 RGBGRB 4 RRBG Can I get some test inputs please? Input: 1 1 2 Output: -2 why? Because 1-1-2=-2 But in problem description "You are not allowed to use unary minus and parentheses in the expression", so 1-1-2 is not correct Edited by author 21.10.2015 16:37 Unary minus and usual minus are different things... [code deleted] Edited by moderator 24.11.2019 13:46 5 2 1 answer: 5-2-1 = 2 your program would say 3 For 5 2 1, it's -9. Numbers can be placed in any order. input numbers are nondecressing order so you can't put 5 2 1 const Nmax=111111; var path:array[1..Nmax] of char; N,M,K,pic,d,dmax,i,L,now:longint; ch:char; ans1,ans2,ans3:int64;
begin readln(N,M,K); L:=0; read(ch); while(ch='u')or(ch='d')or(ch='r')or(ch='l')or(ch='f')or(ch='b') do begin inc(L); path[L]:=ch; read(ch); end;
pic:=1; d:=1; dmax:=1; now:=1; for i:=1 to L do begin if(path[i]='l') then begin if(now=1) then begin inc(d); if(dmax<d) then dmax:=d; end else begin dec(now); if(now=1) then begin d:=1; if(dmax<d) then dmax:=d; end; end; end; if(path[i]='r') then begin if(now=N) then pic:=N else begin inc(now); d:=0; if(now>pic) then pic:=now; end; end; end;
ans1:=1; i:=2; while(i<=N)and(pic<N) do begin if(i-1>=dmax) then inc(pic); if(i-1>=dmax)and(pic<=N) then inc(ans1); inc(i); end;
pic:=1; d:=1; dmax:=1; now:=1; for i:=1 to L do begin if(path[i]='d') then begin if(now=1) then begin inc(d); if(dmax<d) then dmax:=d; end else begin dec(now); if(now=1) then begin d:=1; if(dmax<d) then dmax:=d; end; end; end; if(path[i]='u') then begin if(now=M) then pic:=M else begin d:=0; inc(now); if(now>pic) then pic:=now; end; end; end;
ans2:=1; i:=2; while(i<=M)and(pic<M) do begin if(i-1>=dmax) then inc(pic); if(i-1>=dmax)and(pic<=M) then inc(ans2); inc(i); end;
pic:=1; d:=1; dmax:=1; now:=1; for i:=1 to L do begin if(path[i]='b') then begin if(now=1) then begin inc(d); if(dmax<d) then dmax:=d; end else begin dec(now); if(now=1) then begin d:=1; if(dmax<d) then dmax:=d; end; end; end; if(path[i]='f') then begin if(now=K) then pic:=K else begin d:=0; inc(now); if(now>pic) then pic:=now; end; end; end;
ans3:=1; i:=2; while(i<=K)and(pic<K) do begin if(i-1>=dmax) then inc(pic); if(i-1>=dmax)and(pic<=K) then inc(ans3); inc(i); end;
write(ans1*ans2*ans3); end. Рассуждения такие: 1)как только достигнуто значение верхней границы,то все последующие шаги бессмысленны,т.к. пути совпадут; 2)пока первые i точек попадают в минимум у 1-ой точки (т.е. можно построить график зависимости номера шага от его значения,причем за пределы значений нельзя выходить и потому строим график в этом случае параллельным оси шага),их всех(кроме 1-ой точки) не засчитываем,все оставшиеся(если есть) и дают ответ; 3)всё перемножаем. Сложновато как-то... моя var-секция выглядит так: var x, y, z: int64; curlr, minlr, maxlr: longint; curdu, mindu, maxdu: longint; curbf, minbf, maxbf: longint; c: char; begin ... UPD: да, и ещё, рекомендую всё-таки while not eoln do begin read(ch); ... вместо read(ch); while(ch='u')or(ch='d')or(ch='r')or(ch='l')or(ch='f')or(ch='b') ... Потому что этот второй цикл означает, что в какой-то момент будет произведена попытка считать ещё один символ, когда всё уже считано. У меня этот код при тестировании на файле иногда работает, а иногда выдаёт рантайм 201. Но если в конце второй строки делать Enter, переход на новую, то конечно проблем не возникнет, но ведь в тестах этого не гарантируется. UPD: Вот простейший тест, на котором валится. Почему именно неправильно работает, не скажу, слишком сложные вычисления какие-то. 8 1 1 llllrrrr 4 (правильно.) 8 1 1 llllrrrrrrrr 1 (правильно.) 8 1 1 rrrrllllllll 4 (неправильно.) Edited by author 04.01.2016 20:59 Изменил прогу,всё равно WA. Jane Soboleva (SumNU),я правильно рассуждаю?:я ищу 3 максимума-dmax-максимальное время,когда мы были в 1,maxb-максимальное смещение(вправо от 1) до dmax,maxa-максимальное смещение вправо уже после dmax. Т.е. если строить график пути,то r означает поднятие по оси OY,а l-спуск.Тогда мы как бы начинаем в 1 и с шагом 1 то увеличиваем ординату,то уменьшаем,причем попав в 1 мы не можем идти вниз,а потому движемся вправо,то же и с N.В итоге я ищу максимальную высоту до "ямы" длиной dmax и после. Потом рассматриваю точки i>=dmax+1,т.к. все точки меньшие попадают в яму и потому все пути совпадут.Остальные точки смещены на dmax от графика первой точки и потому они дают новые пути,если не проходят через N(ровно одна из них может проходить),т.к. значения возрастают и потому пути снова совпадут. Не уверена~ К сожалению, я сейчас не в состоянии сказать, насколько эти рассуждения правильные. У меня алгоритм был такой: я поместила робота в условную точку (0, 0, 0) бесконечного параллелепипеда, а потом просто двигаю его согласно заданной строке, параллельно отмечая самое дальнее расстояние в каждом из измерений, которое он достигает в процессе. То есть, к примеру, после rrlllll будет minlr = -3 и maxlr = 2, и расстояние = maxlr - minlr = 5 (2 - -3). И так я считаю для каждого из трёх измерений. После всего этого я получаю три таких расстояния, и вычитаю их из соответствующей им размерности измерения, а потом все эти три числа перемножаю. Вот и всё. Ну и единственный нюанс — надо проследить, чтобы каждый из трёх множителей не опустился ниже единицы, то есть хотя бы одна позиция должна остаться. Например, у нас по left/right размерность 5, и у нас lrrrrrrrr, получатся minlr -1, maxlr 7, 7 - -1 = 8, 5 - 8 = -3, -3 меньше 1, поэтому вместо -3 мы подставляем 1 при умножении. Edited by author 05.01.2016 01:39 Спасибо за идею! Правда я не совсем понял корректность,но решил по-своему: как и ты(или Вы?) нашёл максимальное смещение влево и вправо,а потом осознал,что нас интересуют такие i,что 1-minlr<=i<=N-maxlr(это получается из системы i+maxlr<=N-кол-во i,не выходящих за правую границу и i-minlr>=1-за левую;все пути остальных i совпадут в конечной точке,а если же таких i нет=> все они выходят по крайней мере за одну границу и ответ 1). Кстати,из таблицы рейтинга решений видно,что ученик превзошёл учителя))) Edited by author 05.01.2016 13:38 Можно на ты :) Поздравляю!~ Да, в этот раз решение уже более похожее на моё. Насчёт памяти — у меня даже на задачу A+B не получается тратить меньше 140кб сейчас, хотя у некоторых, я вижу, выходит около 80 и меньше. Возможно, надо просто отключать или менять какие-то директивы компилятора, но я с этим не заморачивалась. 6 one 7 4 5 two 6 3 10 three 5 10 9 four 7 6 7 five 2 5 8 six 3 3 3 I think : one, two, three, four, five. Edited by author 18.03.2009 20:44 one two three four five test is incorrect, two and six have equal second parameter My submission get AC when i use Visual C++ 2013 and get TLE using G++ 4.9 C++11... Why? Probably because slow input/output. It is guaranteed that the most often appeared letter is the right answer. Only one letter is needed. Пишу на Dev-C++ примет ли мой код? и почему-то пишет Compilation Eror. вот код: # include <iostream> # include <windows.h> using namespace std; int main() { int a, b; cout << "Enter your numbers "; cin >> a >> b; cout << "Answer is " << a+b << endl;
system("pause"); return 0; } Во-первых, лишних надписей вроде enter numbers, answer и тд не нужно — проверяющая программа увидит их и сочтёт за ошибку. Выводить нужно только те данные, которые требуются по условию. cin>>a>>b; cout<<a+b; — этого достаточно. system("pause") тоже не нужен. Отредактируйте и можно снова отправить. Если снова compilation error, попробуйте другие сишные компиляторы, там их куча в списке. И ещё рекомендую прочесть руководство http://acm.timus.ru/help.aspx?topic=judge(и там же есть раздел по c/c++) #include <iostream> using namespace std; int main() { int a,b; cin >>a; cin >>b; cout<<a+b; return 1; } > why runtime error (non-zero exit code)? > return 1; LOL thanks you so muck! your mean is wrong in "return 1;" so display "Compilation error" Every solution send to this page must return 0 as exit code, otherwise you will get "Runtime Error". search wikipedia for FERMAT'S LAST THEOREM and you will come to know everything about this problem.(1349 Farm) Edited by author 01.11.2011 15:24 I have discovered a truly marvellous proof of this, which this margin is too narrow to contain Thanks you are a saviour. I was applying all my mathematics to get those triplets for n > 2. |
|