Friday, April 6, 2018

UVa problem solution 514 - Rails

problem link:

Discuss: in this problem train come from direction A in increasing order and there can many permutation to go direction B. input gives you the permutation to go direction.you can easily check it by using stack.just if top element of stack is less then ith element then push more. if ith element is in stack but not in top then the permutation is impossible




#include<bits/stdc++.h>
using namespace std;
int main()
{

    int n;
    while(cin >>n&&n)
    {
        int a;
        while(cin >>a&&a)
        {
            int i,j,cnt=0,flaga=0,flagb=0,ma,mb,ara[25000];
            stack<int>stk;
            stk.push(0);
            ara[1]=a;
            for(i=2; i<=n; i++)
            {
                cin >>ara[i];
            }
            j=1;
            i=1;
            while(1)
            {
                if(j<=ara[i])
                {
                    stk.push(j);
                    j++;
                    continue;
                }
                if(ara[i]==stk.top())
                {
                    // cout <<stk.top()<<' ';
                    stk.pop();
                    i++;

                }
                if(stk.top()>ara[i])
                {
                    flaga=1;
                    break;
                }
                if(i>n)
                {
                    break;

                }
            }
            if(flaga)
                cout <<"No"<<endl;
            else
                cout <<"Yes"<<endl;
        }
        cout <<endl;
    }
    return 0;

}

No comments:

Post a Comment