Common BoardFor some reason I get TLE with G++ 4.9 and AC with Visual C++ 2013 with exactly the same code. I tried to use scanf/printf instead of cin/cout, but had no difference. On my machine this code works <100ms for every n with G++. Can anyone explain why I get TLE with G++? Thanks! #include <string> #include <queue> #include <iostream> using namespace std; int main() { int n; cin >> n; queue<string> result; result.push("a"); result.push("b"); result.push("c"); char abc[] = {'a', 'b', 'c'}; for (int i = 1; i < n; i++) { while (true) { string &s = result.front(); if (s.size() > i) { break; } char last = s[s.size() - 1]; if (s.size() > 1) { char lbo = s[s.size() - 2]; for (int k = 0; k < 3; k++) { char c = abc[k]; if (last != c && lbo != c) { result.push(s + c); } } } else { for (int k = 0; k < 3; k++) { char c = abc[k]; if (last != c) { result.push(s + c); } } } result.pop(); } if ((i + 1) * result.size() > 100000) { cout << "TOO LONG"; return 0; } } while (!result.empty()) { cout << result.front() << endl; result.pop(); } return 0; } Because s+c is a temporary object You are creating temporary objects and throwing them away O(N) times Looks like G++ failed to notice that it is unnecessary to create and destroy objects And MSVC noticed that and replaced with something more effective no bitwise shit needed, no storing 17 bits for indexes and no such stuff! just use unsigned stack* [1000] for the stacks (store elements in a dynamic array, reallocating memory for each push), and unsigned top[1000] for the index of the top element. with this i got AC with 663 KB! good luck! Looks like solve the problem in such a manner is no longer possible Because ,as of 2017, there is no Intel C++ compiler And every other compiler fails to allocate memory effective Probably when reallocating there are empty spaces which count as memory used And Intel Compiler was able to get rid of such spaces. После того как наконец сдал, хочется сказать, что на самом деле OP очень переусложнил задачу, динамическая память не нужна. Достаточно статического выделения. Которое к слову очень быстро работает -- за 31 мс. Я много раз ловил WA#8. Здесь предлагали тест на WA#8. Тест у меня работал хорошо. Ошибка, как выяснилось, была в том, что я перепутал переменную с названием block_size с переменной block_cnt. Edited by author 26.07.2017 16:19 Одно из решений использовало сдвиг O(N) ячеек массива каждую операцию Ценой диких оптимизаций удалось довести его до TLE#16 (только на Clang, любой другой компилятор C++ позволял получить только TLE#12) Edited by author 26.07.2017 16:21 As stated in the statement, after spraying or aromatizing of fruit it may become to have fractional value. 25th test is the first case where you need to aromatize one flower and dearomatize another in such way that both of them have fractional value, but their sum is integer. Edited by author 07.11.2009 05:19 I've changed my algorithm, but have got WA25->WA19. Who knows what does it mean? Nevermind, I had a stupid bug with bitmasks (I'm wondering how it could pass 19-25 tests). Thank you very much, this was a non-obvious test. Try this test: 100000 99999 0 1 2 1000000 2 3 1000000 ... 99999 100000 1000000 Answer: 10049708502000000 Good Luck! Thanks! HINT for solvers: In the test above, you can get an overflow. Change min(⌈(1 + T/100)* ti⌉, 100500*ti) to long long my_ceil(long long tnow, long long f1, long long t) { if(h1+tnow-f1>h2*h1) return h2*t; //return min(ceil(t+(tnow-f1)*t/100.0), h2*t); if(((tnow-f1)*t) % h1==0) return t+((tnow-f1)*t)/h1; else return t+((tnow-f1)*t)/h1 + h3; } //h1=100; h2=100500; h3=1; where tnow=time now, f1=last cleaning time for this rib, s2=start time of next cleaning Edited by author 26.07.2017 14:10 Solution looks like bruteforce with a precalc, not a dynamic programming one. Or precalc counts as DP? Or DP is just a clever bruteforce? Edited by author 25.07.2017 20:10 Are you calculating something like "maximal sum subarray" ? That is where it is DP. If you are doing Kadane algorithm You are doing essentially that thing dp[i] = max(0, dp[i-1] + matrix [i]) answer = max(dp[i]) I think the dataset for this problem is weak. I got AC without checking for cycles. Input: 3 3 1 3 3 2 2 1 1 3 2 Correct output: NO But my code ( http://ideone.com/ZljGZ5 ) returns YES and it got Accepted. Edited by author 25.07.2017 14:17 Edited by author 25.07.2017 14:18И не только мне, как показывает форум. Можно решить это с помощью алгоритма Дейкстры. Моё время на Clang C++14 равно 2.7 сек. На Visual C++2013 вообще TLE#8. Стало понятно от чего кайф Из-за того что я еле-еле успел в time limit Ожидания были, что случится memory limit с большой вероятностью, поэтому я взял сразу Visual C++ Give me some tests. PLEASE. 1 0 And what is the correct answer for this test? a=int(input()) tasks_left=12-a if tasks_left*45<=240: print('TRUE') else: print('FALSE') Because you should output "YES" /"NO" , not "TRUE" /"FALSE" Edited by author 21.07.2017 10:33 but it doesnt work. a=int(input('input solved task:')) tasks_left=12-a if tasks_left*45<=240: print('YES') else: print('NO') Thanks. Now it's work. i've changed from a=int(input('input solved task:')) to a=int(input()) 144 ->185 29756 ->29929 800000000 ->1001578525 41088 ->51365 123456 ->123457 1369 ->0 369 ->0 1024 ->1285 58 ->59 21414 ->0 2000000000 ->2500015625 961 ->0 1870 ->1871 23432 ->35151 P.S. use long long (else WA7) http://ideone.com/KOHykO Examples and my examples work. ideome works How to look at all stdin ??? Edited by author 28.07.2017 03:35 ?????abxxxab????? abab output: 3 answer: 4 I use very simple algo, prompt other algo please. Edited by author 10.08.2011 15:32 Segment tree with range update, obviously. And even Fenwick tree with range increment. (Petr described such a Fenwick tree in his blog) #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { long int n,k,val,fact=1,coeff=0;
char ch[24],*num,*excl;
gets(ch);
num=strtok(ch," "); n=atoi(num);
excl=strtok(NULL,NULL); k=strlen(excl);
while(coeff*k<n) { val=n-coeff*k; fact=fact*val; coeff++; }
if(n%k!=0) fact=fact*(n%k); else fact=fact*k;
printf("%ld",fact);
return 0; } Hi! I am getting runtime error(access violation) although the solution seems to work for different set of inputs. Please help me out! http://ideone.com/1tNjl7I have corrected your solution. Even if fix Access violation, You are just WA#5 (Because of a logic error) Edited by author 21.07.2017 00:59 Hi Mahilewets! Thanks a lot! I did correct the "Runtime error" but was getting a "Wrong answer" error due to the error in logic in the while condition. Your's is the right one. Just a query though(pardon my ignorance as I am new to this kind of stuff). How do you find the test cases for each problem apart from the one already given? Если вы используете DFS в итеративной форме, то вы можете получить TLE#4. Если вы перепишите DFS в рекурсивную форму и будете компилировать на Visual C++, то получите AC за менее чем 0.1 секунды. Алгоритм свой я оцениваю как O(N*N*N) по времени, Поскольку я N раз запускаю DFS по графу в котором O(N*N) ребер (В графе проведено ребро от джедая который может победить джедая X в схватке к джедаю Х) It may take around ten minutes if you precalc in Python. It takes just few moments to precalc in C++. Maybe special Python libraries for calculations would be OK. Don't forget about case n=1 answer: a b c 10 6 8 2 1 2 2 4 5 5 2 5 4 6 5 9 4 10 5 Ansver: 1366 Парень, я не знаю, где ты это взял, но тебе ОГРОМНОЕ спасибо! С помощью твоих данных нашел ошибку и сдал программу. Спасибо. My program do this test case is correct, but i get WA on 10 test. Pls, anybody write this test! my program pass this too, but I came up with the test which leads to error: 8 8 8 2 7 3 3 4 4 5 4 6 3 6 1 7 2 8 3 answer must be 1424. Задача заставила подумать. Как уже описано на форуме, нужно научиться считать количество единиц, которые встречаются в числах от 1 до X и подбирать X бинарным поиском. И вот мне этот подсчет долго не давался. Итог такой. Считать можно рекурсивно. Для этого нужно воспользоваться тем, что для чисел вида X=999...999 искомое количество единиц равно (log10(X)+1) *10^log10(X). Этот факт я заметил эксперимнтально. То есть я имею в виду count_ones (99)=20 count_ones (999)=300 count_ones (9999)=4000 и так далее. Отсюда и вытекает способ . Вычисляем сначала для X с зануленными разрядами кроме самого главного, затем прибавляем значение функции от X с зануленным главным разрядом . Я приведу пример для небольшого числа. Пусть X=666. Тогда посчитаем отдельно для 0-99, умножим на 6, прибавим к ответу; затем отдельно для 100-200, прибавим это к ответу , затем рекурсивно для 600-666 то есть просто для 0-66. |
|