题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1051
遍历序列,基于这样的思想,例如 3 2 1 7 5 6 4 开始是3 则1 2 3入栈 并标记,然后判断栈有没有超出给定大小,然后看s.top() == 3 否,若都为true 则走到2,若中间有一项不符则,这个序列式impossible ,然成功遍历一遍,则这个序列式可以的。
1 #include<iostream> 2 #include<vector> 3 #include<stack> 4 using namespace std; 5 int main() 6 { 7 int M,N,K; 8 while(cin>>M>>N>>K) 9 { 10 vector<int> s(N); 11 vector<vector<int>> check(K, s); 12 for(int i=0; i<K; ++i) 13 for(int j=0; j<N; ++j) 14 cin>>check[i][j]; 15 for(int i=0; i<K; ++i) 16 { 17 bool flag(false); 18 /*记录栈中元素*/ 19 stack<int> s; 20 /*用来记录是否在栈中*/ 21 vector<int> inorout(N+1, 0); 22 for(int j=0; j<N; ++j) 23 { 24 for(int k=1; k<=check[i][j]; ++k) 25 if(inorout[k] == 0) 26 { 27 inorout[k]=1; 28 s.push(k); 29 } 30 if(s.size() > M) 31 { 32 cout<<"NO"<<endl; 33 flag=true; 34 break; 35 } 36 if(s.top() == check[i][j]) 37 s.pop(); 38 else 39 { 40 cout<<"NO"<<endl; 41 flag=true; 42 break; 43 } 44 } 45 if(flag == false) 46 cout<<"YES"<<endl; 47 } 48 } 49 return 0; 50 }