|
|
back to boardWhat is test #4 (crash on it) and mistake in the code? Posted by virus 28 Jan 2009 16:36 I have crash (access violation) on test #4. I can't imagine where this code can give a crash! Could you explain me where this stupid mistake is? #include<iostream> using namespace std; struct Node { char ch; Node *next; Node *prev; } *first=0,*last=0; int n=0; void add(char c) { ++n; if(!last) { first=new Node; first->ch=c; first->next=0; first->prev=0; last=first; } else { last->next=new Node; last->next->ch=c; last->next->next=0; last->next->prev=last; last=last->next; } } void cleanup() { while(first) { Node *p=first; first=first->next; delete p; } first=last=0; } void move() { Node *p=last; last=last->prev; last->next=0; first->prev=p; p->next=first; p->prev=0; first=p; } bool check_correct() { int balance=0; Node *p=first; while(p) { if(p->ch=='(') ++balance; else --balance; if(balance<0) return 0; p=p->next; } if(!balance) return 1; return 0; } int count() { int cnt=0,balance=0; Node *p=first; while(p) { if(p->ch=='(') ++balance; else --balance; if(!balance) ++cnt; p=p->next; } return cnt; } int main() { char c; while(cin.get(c)) { if((c=='(')||(c==')')) add(c); else break; } int i; bool b=0; for(i=0;i<n;++i) { b=check_correct(); if(b) break; move(); } if(b) cout<<count(); else cout<<0; cleanup(); return 0; } Well, I've rewritten this algorithm using STL, now I have TLE #11, but it's slow STL. But the main thing I found is that this algorithm is totally correct. So I just have to find a mistake in the code. Where it could be? On my tests everything works perfectly. Help, please! Edited by author 28.01.2009 20:22 Re: What is test #4 (crash on it) and mistake in the code? Checking balance consumes O(n) time, you run it n times. So, your solution is O(n^2) -- of course, it's TL. |
|
|