1) First test is not sample 2) There are not n strings in input in the question , author said 0 is replaced by 1. but they replace 1 by zero in the 3rd test of sample. now, i am very much confused. My program works with tests like this: 4 0 00 0 10 11 And my program give right answers but WA#1. That my code, whats wrong?? #include <bits/stdc++.h> using namespace std; int n; string ans,q; int main() { cin >> n; while (!cin.eof()) { //while not eof reading getline(cin,q); //read 1 line ans = ""; for (int i = 0; i < q.length(); i++) //remove all except 0 and 1 if (q[i] == '0' || q[i] == '1') ans += q[i]; if (ans.length() < n-1 || ans.length() > n+1) //if its empty continue continue; int pos_sum = 0; for (int i = 0; i < ans.length(); i++) { //count sum of positions if (ans[i] == '1') { pos_sum += i+1; } } if (ans.length() > n) { //if there 1 unnecessary element check all bool fg = false; //elements and remove him for (int i = 0; i < ans.length(); i++) { int loc_pos_sum = 0; if (fg) { cout << ans[i]; continue; } for (int j = 0; j < ans.length(); j++) { if (j == i) continue; if (ans[j] == '1') loc_pos_sum += j+1 - int(j >= i); } if (loc_pos_sum % (n+1) == 0) { fg = true; } else { cout << ans[i]; } } } else if (ans.length() < n) { //if there 1 removed element bool fg = false; //check all positions for him for (int i = 0; i <= ans.length(); i++) { int loc_pos_sum = 0; if (fg) { cout << ans[i]; continue; } for (int j = 0; j < ans.length(); j++) { if (ans[j] == '1') { loc_pos_sum += j+1 + int(j >= i); } } if (loc_pos_sum % (n+1) == 0) { cout << 0; fg = true; } if ((i+1+loc_pos_sum) % (n+1) == 0) { cout << 1; fg = true; } cout << ans[i]; } } else { //if '0' replaced to '1' check all bool fg = false; //elements and replace for (int i = 0; i < ans.length(); i++) { if (ans[i] == '1' && (pos_sum-i-1)%(n+1) == 0 && !fg) { cout << 0; fg = true; } else { cout << ans[i]; } } } cout << "\n"; } return 0; } Edited by author 30.10.2018 16:07 For some inputs multiple answers are possible, e.g.: 4 1011 has two possible answers: 1111 and 1001. However only 1001 seems to be accepted. Either the wording of the problem should be changed or the alternative answers should be accepted. Sorry - I was mistaken about the rules - 1111 is not an answer for 1011. Why 1111 isn't an answer for 1011? Так до сих пор и не выяснилось, что делать с окончанием ввода? Или измените условия так, чтобы окончание ввода оканчивалось явно - например пустой строкой или -1, или же уточните, нужно ли это делать с помощью файла. Перенаправление ввода из файла, например в bash, не воспринимает символ конца файла EOF. А ваш сайт при тесте делает расчет на то, что ввод окончится EOFом. Думаю по этой проблеме так мало успешных попыток Просто по длине слова определяем, какой у нас случай. (Замена, удаление или вставка). Затем для каждой позиции пытаемся внести изменения и смотрим, получается у нас выполнение условия или нет. Удобно завести массив постфиксных сумм для того чтобы быстро пересчитать сумму позиций единиц. Всем привет! Я написал реализацию программы на Java. Проверка выдает Runtime error. Программа принимает n, после чего слушает ввод и после каждого введенного слова выводит ответ. Выглядит это так: 9 0010100011 //мой ввод 001000011 //вывод программы 00010010 //мой ввод 000100101 //вывод программы Ctrl - C Скажите, правильно ли реализовал ввод/вывод данных? Спасибо! Edited by author 30.12.2015 22:15 Да, так можно делать, не ожидать завершения ввода, прежде чем делать вывод. Но без кода не понять, где рантайм. Я точно не уверена, т. к. у меня нет большого опыта в джаве, но возможно, проблема вот здесь while(true) { a = input(); if (a.length() > 0) { System.out.println(toSource(a)); } } Как я вижу, программа никогда не выходит из цикла, и в некоторый момент пытается что-то читать после того, как входные данные заканчиваются. Я исправила while(true) на while(in.hasNextLine) (входные данные не закончены, имеется следующая строка) и class на public class (иначе выдаёт compilation error). Теперь получается WA #1. Честно говоря, непонятно почему, вроде на тестовых данных в других ветках обсуждения нормально проходит. Может кто-то более опытный сможет подсказать. Ну уже хотя бы не Runtime. Спасибо. Ввод верный (его несложно подправить и под не Pascal): const nmax=1111; var a:array[1..nmax] of char; n,i,j,len:longint; ch:char; ..... begin readln(n); while not eof do begin len:=0; read(ch); if(ch='0')or(ch='1') then begin //началось считывание очередного слова len:=1; a[len]:=ch; read(ch); while(ch=' ')or(ch='1')or(ch='0') do begin if(ch='1')or(ch='0') then begin inc(len); a[len]:=ch; end; read(ch); end; Solve(len); readln; //перевод строки end; end; end. 40 минут я сабмитил код который точно проходит первый тест (проверял на трех компиляторах на CF) После, я просто добавил еще одно условие которое я изначально не рассмотрел, это когда в строке ничего менять не надо, или эта строка из нулей и надо добавить 0 или убрать. И ПОЧЕМУ-ТО Я СРАЗУ ПОЛУЧИЛ AC!!! Как это понимать, если эти случаи никак не влияют на ответ на первом тесте ???? В этой задаче первый тест не совпадает с примером из условия How can I know the input is finished? It doesn't get the data from file,I can't use : ifstream in("*.in"); in.eof(); After getting several WA on test1, I realized that I was counting the wrong position. In order to get AC, we should read the sequence from LEFT TO RIGHT. For example, for '11101', the first position is 1, second is 1, third is 1 and the final should be 1. After I reading the sequence from left to right, I finally got AC. "1. Any (but only one) symbol 0 is replaced by 1. " It means When the length=n It needn't to consider 1 is replaced by 0. read problem carefully.!I got wa 6 times because of it..TAT. Hope to help you a little. kiitos thank you. I think it help me very much What about this test? 5 00011 May be your program is O(n^2) you can use an array. f[i] means there are f[i] '1' after s[i]. (I can't speak English well.) No additional array is required. Only several auxiliary variables. Tried several times with different variations of input processing. Can you please give me some hints? Here is my code: http://pastebin.com/beh0mtGh I read some previous topics because my soluton was getting WA1. I tried this test which was Leo's test with some empty lines: 4 0 00 0 0 11 10 1 1 11 011 And then I fixed my program. Edited by author 15.08.2013 16:58 Edited by author 15.08.2013 16:59 1 Any (but only one) symbol 0 is replaced by 1. 2 Any (but only one) symbol is removed. 3 A symbol (0 or 1) is inserted at any position. a word is changed only once through 1 or 2 or 3. so it needn't think about a word is changed by both or three. Are there many possible answers? For example in the test example my program gets the answer: 0000 (do nothing) 0111 (insert 1 at the end) 1010 (change the last 1 in 0; I suspect that this 1 was initially a 0 and now, due to the noisy line, it's a 1) 1101 (erase the last 1) the total sum of positions is 20, which is a multiple of 5 = 4 + 1 Did I get something wrong? I not, which solution should I print? And is it possible not to have any solution? 4 100 1101 1011 001 101 11001 10101 10011 01001 10001 10010 for all case answer 1001 I know that they have some extra line breaks in the tests, so maybe test like 4 100 1101 1011 001 101 11001 10101 10011 01001 10001 10010 would be more helpful! 4 1100 0011 11010 01011 ???? it is correct? yeah .. thank you very much.. it's right .. the test will be like this: 4 1100 0011 ... there will be some spaces btween them.. everyone should be careful ... ^_^ Edited by author 30.08.2005 20:16 Edited by author 30.08.2005 20:16 But I accepted. I didn't check this. But i don't think these tests are right? Can you tell me whether it is right or not? Or the answer. It is known that the original words all HAVE (!!!) the following property: the sum of positions where symbols 1 are located is a multiple of (N+1) or equal to zero. I think nothing need to be added Thank you very much for that test!!! (To JIeHuH*CCCP) Thank you very much! I got AC now... Edited by author 17.10.2007 14:42 Edited by author 17.10.2007 14:42 tx very much :), that helps me much. Thanks a lot, KingPin. Your test really helped me to understnd that i've got an algorithm problem, not while reading)) Accepted finally! you are so KIND that I don't know how to appreciate you! Good Luck to everyone Many thanks, very good tests Thank you very much for this test. It helped me to find 3 mistakes) Although they all were really supid... So finally I got AC. 5 1100 1110 11110 11101 111100 111010 111001 011100 101100 110100 111000 0001 1001 1000 11001 10101 10011 010001 100001 100010 110001 101001 100101 100011 1010 0010 0110 0100 0101 11010 01110 01011 001010 010010 010100 101010 011010 010110 010101 this test is about all cases of n=5 ,the answer is 11100 * 11 10001 * 13 01010 * 15 Take to consideration, that ----------------
4 0 00 0 0 11 10 1 1 11 011 ---------------- is correct test and the answer is as in the base test. It was the first. The second is the funny thing is that I had WA#1 before I remake output: from classic printf to fprintf(stdout,... and fclose(stdout) I don't know what a hell. Edited by author 30.12.2005 14:44 So as you say, if output must be done with stdout, then it comes out that stdin is the best(easiest) way to read information from the input stream... /:) am I right :)). that was my problem. Thanks at all ;) Thx, very much. That makes problem not just simple, but rather stupid. |
|