二屆太原理工大學程序設計新生賽決賽 C Nitori and Stack-Tech

題目鏈接

Nitori擅長製作各種各樣精巧的道具。

這一天,Nitori找來n個不同的零件放在桌子上,將它們排列成一排,接着她便拿出一個被她稱爲“棧”的神奇道具,這個道具可以將無數多個零件放進去,並且也可以按照與放入順序相反的順序將零件取出來(即後放入的零件必須先取出來),並且她還可以只取出一部分後繼續放入其它的零件,而不必一次性全部取完。

Nitori十分喜愛這個叫做“棧”的道具,今天,她想用“棧”將桌上的零件調整一下排列順序,她會把桌上的零件從左到右依次放入“棧”中,並且在任意時刻,她都可以將若干個先前放進棧中的零件取出(需要按照“棧”的後入先出順序),並從左到右在桌子上擺放出來。

她想知道是否可能將桌上物品的排列s,通過上述操作,轉化爲另一種排列t。

輸入描述:
第一行輸入一個正整數n,表示n個零件。
第二行輸入一個長度爲n,由不同小寫字母組成的字符串s,表示初始從左到右排列的n種零件。
第三行輸入一個長度爲n,由不同小寫字母組成的字符串t,表示Nitori希望得到的排列。

數據規範:
1≤n≤26.

  • 所有字符串保證只含有小寫字母。
    輸出描述:
    如果能夠通過“棧”將排列s變成t,則輸出"Yes",反之輸出"No"。(不包含雙引號,大小寫任意)
    示例1
    輸入

1
a
o

輸出

No

示例2
輸入

1
c
c

輸出

Yes

示例3
輸入

7
abcedfh
aecbfdh

輸出

Yes

說明
如果使用u表示入棧,使用o表示出棧,則此組數據可通過操作:
uouuuooouuoouo
從s排列得到t排列。

棧的簡單應用,先把字符存到push,pop兩個數組裏,兩個指針,i,j,然第一個字符串從第i個元素開始依次進棧,如果此時棧頂元素等於pop的數組第j個元素,出棧,依次進行下去。

#include <iostream>
#include <stack>
using namespace std;
bool isPopSeries(char push[],char pop[],int length)
{
    if(!push||!pop||length<=0)
        return false;
    stack<char> temp;
    int pushNum=0;
    int i = 0;
    while(i < length)
    {
        while(temp.empty()||temp.top()!=pop[i])
        {
            if(pushNum < length)
                temp.push(push[pushNum++]);
            else
                return false;
        }
        if(!temp.empty()&&temp.top()==pop[i])
        {
            temp.pop();
            i++;
        }
    }
    return true;
}
  
int main()
{
    int n;
    char pushArray[100],popArray[100];
    cin>>n;
    getchar();
    gets(pushArray);
    gets(popArray);
    if(isPopSeries(pushArray,popArray,n))
        cout<<"Yes"<<endl;
    else
        cout<<"No"<<endl;
    system("pause");
    return 0;
}

還有這個版本的

#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
#define pb push_back
using namespace std;
typedef long long ll;
const int maxn = 1e2+10;
int sum,n;
char push[maxn],pop[maxn],a[maxn],b[maxn];
bool check()
{
    int i=0,j=0;
    stack<char> mystack;
    while(i < n)
    {
        mystack.push(push[i]);
        i++;
        while(!mystack.empty() && mystack.top() == pop[j])
        {  
                mystack.pop();
                j++;   
        }
         
    }
    if( mystack.empty() && j==n)
        return true;
    return false;
}
 
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>push[i],a[i]=push[i];
    for(int i=0;i<n;i++)
        cin>>pop[i],b[i]=pop[i];
    sort(a,a+n);
    sort(b,b+n);
    for(int i=0;i<n;i++)
    {
        if(a[i]!=b[i])
        {
            cout<<"No"<<endl;
            return 0;
        }
    }
    if(check())
    cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
    //system("pause");
    return 0;
 
 
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章