Page 6 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 Так до сих пор и не выяснилось, что делать с окончанием ввода? Или измените условия так, чтобы окончание ввода оканчивалось явно - например пустой строкой или -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!!! Как это понимать, если эти случаи никак не влияют на ответ на первом тесте ???? В этой задаче первый тест не совпадает с примером из условия 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? Page 5 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. 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? I know,that put all program is bad,but i can't find and understand my mistake! Output limit#1: #include<iostream> #include<stdio.h> #include<string> #include<string.h> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif string m,m2,m3="0",m4="1"; char c; int a,b,d,i,m1[100],h,length,kk=0; cin>>a; const int s=a+1; l1:while(cin.get(c)){ kk++; if(kk==0)goto l2; cin.get(c); while(c==10){ cout<<c; cin.get(c); } cin.putback(c); l2: cin>>m; length=m.length(); b=0; d=0; for(i=0;i<length;i++) if(m[i]=='1'){ m1[b]=i; b++; d=d+1+i; } if(length==a) for(i=0;i<b;i++) if((d-m1[i]-1)%s==0){ m[m1[i]]='0'; cout<<m<<endl; goto l1; } h=0; if(length<a){ if((d+length+1)%s==0){ cout<<m<<'1'<<endl; goto l1; } else if(d%s==0){ cout<<m<<'0'<<endl; goto l1; } else for(i=0;i<length;i++){ if((d+(b-h))%s==0){ m.insert(i,m3); cout<<m<<endl; goto l1; } else if((d+(b-h)+1+i)%s==0){ m.insert(i,m4); cout<<m<<endl; goto l1; } if(m[i]=='1')h++; } } h=0; if(length>a) for(i=0;i<length;i++){ if(m[i]=='1'){ h++; if((d-i-(b-h)-1)%s==0){ m.erase(i,1); cout<<m<<endl; goto l1; } } else if((d-(b-h))%s==0){ m.erase(i,1); cout<<m<<endl; goto l1; } } cout<<m<<endl; } return 0; } But without cin.get(c); while(c==10){ cout<<c; cin.get(c); } cin.putback(c); i have WA#1! WHY???? P.S. Sorry for bad English. There is one or more solution for this test or it is incorrect? 4 1000 1000 1000 1000 1000 I think at least two: 0000 0000 0000 0000 0000 and 1000 1000 1000 1000 1000 not inverse, just 0 to 1 0000 to 1000. What's wrong? 0 -> 1 - it's mistake to correct message, u need to fix it by changing 1 to 0 back. If you got ac can you test my program: thanks in advance program N1007; const Max=3002; VAR c:char; N,i,j,M,S,L,k,q:integer; W:array[1..Max] of array[0..2001] of byte; D:array[0..2001] of byte; begin Readln(N);i:=0;j:=1; Repeat if j<>0 then inc(i); j:=0; while not eoln(input) do begin read(c); if c in ['0','1'] then begin inc(j); W[i][j]:=ord(c)-48; end; end; if j<>0 then W[I][0]:=J; readln; Until eof(input); m:=i; //if (m=2001)and(n=500) then m:=m div (i-i); for i:=1 to M do begin S:=0; L:= W[i][0]; for j:=1 to L do if W[i][j]=1 then S:=S+j; if (L=N) then begin j:=0; while (S-j*W[i][j]) mod (N+1) <>0 do inc(j); if j<>0 then W[i][j]:=0; for q:=1 to L do write(W[i][q]); writeln; end; if (L<N) then begin k:=0; for j:=L downto 1 do begin if W[i][j]=1 then inc(k); D[j]:=k; end; j:=1; while (((S+D[j]) mod (N+1) <>0) and ((S+D[j]+j) mod (N+1) <>0))and(j<=L) do inc(j); if (S+D[j]) mod (N+1) =0 then k:=0 else k:=1; for q:=1 to j-1 do write(W[i][q]); write(k); for q:=j to L do write(W[i][q]); writeln; end; if (L>N) then begin k:=0; for j:=L downto 1 do begin D[j]:=k; if W[i][j]=1 then inc(k); end; j:=1; while (((S-D[j]-j*W[i][j]) mod (N+1) <>0) )and(j<L) do inc(j); for q:=1 to j-1 do write(W[i][q]);
for q:=j+1 to L do write(W[i][q]); writeln; end; end; Readln; end. Edited by author 19.11.2010 00:03 It was very stupid error: I used: W:array[1..Max] of array[0..2001] of byte; for storing code words (array[1..2001] of byte;) and zero element of same array for lenght of code word. But max length could be great than byte I change byte to integer and got AC. This example shows how not to write programs! )) I had ACed with about 1.6 sec running time! I guess the tests for this problem are not strict enought, because I have used very poor O(n^2) algorithm here. Pages: 6 5 4 3 2 1 Previous |
|