PAT 1051
输入
5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2
输出
YES
NO
NO
YES
NO
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
int main()
{
int m,n,k;
scanf("%d %d %d",&m,&n,&k);
for(int i=0;i<k;i++)
{
bool flag = false;
stack<int> s;
queue<int> q;
for(int j=1;j<=n;j++)
{
int temp;
scanf("%d",&temp);
q.push(temp);
}
for(int j=1;j<=n;j++)
{
s.push(j);
if(s.size() >m )
{
break;
}
while( !s.empty()&& !q.empty() && s.top() == q.front() )
{
s.pop();
q.pop();
}
}
if(s.empty() && q.empty())
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}
改用cin和cout,用时更短,前面是9ms,现在是0ms,内存方面有少量增加,前面是384KB,后面是412KB。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
using namespace std;
int main()
{
int n,m,k;
cin>>n>>m>>k;
for(int i=0;i<k;i++)
{
stack<int> s;
queue<int> q;
for(int j=1;j<=m;j++)
{
int temp;
cin>>temp;
q.push(temp);
}
for(int j=1;j<=m;j++)
{
s.push(j);
if(s.size()>n)
{
break;
}
while(!s.empty() && !q.empty()
&& s.top()==q.front() )
{
s.pop();
q.pop();
}
}
if( s.empty() && q.empty() )
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
return 0;
}