Problem Link
Done using stack
Logic is to take an test array and make operations to make an series of 1,2,3,4...........
if possible!!!!
Code::
#include <iostream>
#include<stack>
#define MAX 1001
using namespace std;
int main() {
int n;
stack<int> s;
cin>>n;
while(n!=0)
{
int arr[MAX]={0},test[MAX]={0};
while(!s.empty()) s.pop(); // clear the stack
for(int i=1;i<=n;i++) cin>>arr[i];
int j=0;
int num=1;
for(j=1;j<=n;j++)
{
if(arr[j]==num) // checked in array if number is present
{
test[num++]=arr[j];
continue;
}
while(!s.empty() && s.top()==num) //checked at the top of stack if num is present
{
test[num++]=s.top();
s.pop();
}
s.push(arr[j]);
}
while(s.size()!=0) // making the stack empty at the last
{
test[num++]=s.top();
s.pop();
}
int flag=0;
for(int k=1;k<=n;k++) // checking whether array can be modified in the way given
{
//cout<<test[k];
if(test[k]!=k) { flag=1; break; }
}
if(flag==0) cout<<"yes"<<endl;
else cout<<"no"<<endl;
cin>>n;
}
// your code goes here
return 0;
}
Done using stack
Logic is to take an test array and make operations to make an series of 1,2,3,4...........
if possible!!!!
Code::
#include <iostream>
#include<stack>
#define MAX 1001
using namespace std;
int main() {
int n;
stack<int> s;
cin>>n;
while(n!=0)
{
int arr[MAX]={0},test[MAX]={0};
while(!s.empty()) s.pop(); // clear the stack
for(int i=1;i<=n;i++) cin>>arr[i];
int j=0;
int num=1;
for(j=1;j<=n;j++)
{
if(arr[j]==num) // checked in array if number is present
{
test[num++]=arr[j];
continue;
}
while(!s.empty() && s.top()==num) //checked at the top of stack if num is present
{
test[num++]=s.top();
s.pop();
}
s.push(arr[j]);
}
while(s.size()!=0) // making the stack empty at the last
{
test[num++]=s.top();
s.pop();
}
int flag=0;
for(int k=1;k<=n;k++) // checking whether array can be modified in the way given
{
//cout<<test[k];
if(test[k]!=k) { flag=1; break; }
}
if(flag==0) cout<<"yes"<<endl;
else cout<<"no"<<endl;
cin>>n;
}
// your code goes here
return 0;
}
No comments:
Post a Comment