vee_sharp's blog

By vee_sharp, history, 8 years ago, In English

I am trying to solve SPOJ street parade. But i dont know what is wrong in the following code:

#include<iostream>
#include<algorithm>
#include<stack>
#include<cstdio>
using namespace std;
int main(){
	int n,ne,last;
	cin>>n;
	while(n!=0){
		int ar[n];
		last=0;
        stack <int> s;
        for(int i=0;i<n;i++) 
            cin>>ar[i];
		for(int i=0;i<n;i++){
			if(s.top()==(last+1)){
				s.pop();
				last++;
			}
			else if(ar[i]==(last+1))
				last++;
			else if(!s.empty() && s.top()<ar[i]){
				cout<<"no"<<endl;
				continue;
			}
			else
				s.push(ar[i]);
		}
		cout<<"yes"<<endl;
		cin>>n;
	}
	return 0;
}

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
8 years ago, # |
Rev. 4   Vote: I like it +13 Vote: I do not like it

There are countless errors in that code.

  • The first one is if(s.top()==(last+1)). If the stack is empty it will give RTE.
  • Then when you print "no", you use continue, when you should actually use break. The way you do it, you might print nearly N statements in a single test case.
  • Then, whatever happens, you print "yes", even if you found there's no answer in the loop before.
  • Moreover, you only check once with an if statement if the top element in the stack is the one you need, when you must check it with a while statement because there might be cases when multiple elements are popped at once.

Also, next time post your code in pastebin, ideone or some other paste site instead of pasting it directly in the message. Oh, and please post the link to the problem as well, so we don't have to google it!