白駿10828:スタック
10828スタック
質問する
に答える
これはスタックを実装する基本的な問題である.
基本的なC++STLスタックの使い方を理解します.
Pythonはスタックをリストとして実装する.
また、input()への書き込みはタイムアウトします.
sys.stdin.readline()に書き込む必要があります.
C++コード
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
int N;
cin >> N;
stack<int> S;
while(N--) {
string M;
cin >> M;
if(M == "push") {
int dt;
cin >> dt;
S.push(dt);
}
else if(M == "pop") {
if(S.empty()) {
cout << -1 << endl;
}
else {
cout << S.top() << endl;
S.pop();
}
}
else if(M == "size") {
cout << S.size() << endl;
}
else if(M == "empty") {
cout << S.empty() << endl;
}
else if(M == "top") {
if(S.empty()) {
cout << -1 << endl;
}
else {
cout << S.top() << endl;
}
}
}
return 0;
}
Pythonコード
import sys
S = []
N = int(sys.stdin.readline())
for i in range(N):
command = sys.stdin.readline().split()
if command[0] == "push":
dt = command[1]
S.append(dt)
elif command[0] == "pop":
if len(S) == 0:
print(-1)
else:
print(S.pop())
elif command[0] == "size":
print(len(S))
elif command[0] == "empty":
if len(S) == 0:
print(1)
else:
print(0)
elif command[0] == "top":
if len(S) == 0:
print(-1)
else:
print(S[-1])
Reference
この問題について(白駿10828:スタック), 我々は、より多くの情報をここで見つけました https://velog.io/@imchanyang/백준-10828-스택テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol