0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【AtCoder】スタック(stack)の活用

Last updated at Posted at 2024-09-15

ポイント

  • vectorで、push_backやpop_backを使って実装できる
  • 配列の要素番号が、スタックでいう所の層番号に対応している

例題

ABC307D - Mismatched Parentheses

#include <bits/stdc++.h>
using namespace std;

int main() {
  int N; string S;
  cin >> N >> S;
  
  vector<string> A;
  A.push_back("");
  for (char c : S) {
    if (c == '(') A.push_back("(");
    else if (c == ')') {
      if (A.size() == 1) A.back() += c;
      else A.pop_back();
    }
    else A.back() += c;
  }
  
  string ans = "";
  for (string a : A) ans += a;
  cout << ans << endl;
}

ABC328D - Take ABC

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); ++i)

int main() {
  string S; cin >> S;
  
  const string T = "ABC";
  const int M = T.size();
  string ans = "";
  rep(i, S.size()) {
    ans += S[i];
    if (ans.size() < M) continue;
    
    string str = ans.substr(ans.size() - M);
    if (str == T) rep(j, M) ans.pop_back();
  }
  
  cout << ans << endl;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?