• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yongchaoD

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

E. C++(栈,icpc网络赛选拔)

题目来源:https://codeforces.com/gym/546939/problem/E
//
题意:给你一串字符串,求“LIBRARY”的调用次数。"REP X FOR N TIMES"表示,表达式 X 循环执行 N 次,若LIBRARY不出现在该表达式内,则计数一次。
//
思路:“这道题赛时干红了,被恶心到了,题读假了,注意保证输入是合法的,说明出现REP后面一定回出现FOR N TIMES。”,用栈,先弹入一个0,如果出现“LIBRAYRY”,栈顶+=1,如果出现了REP,入栈一个0,后面出现“LIBRARY”几次,就栈顶加几次,当后面出现FOR了,必定出现N(合法性),然后上一个弹入的,就*=N,然后加到倒数第二个。当出现多个REP时候,也也是满足for语法的。
//
代码细节:stoi是将字符串数字转为十进制数字。
//
题解:

点击查看代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int Mod = 1e9+7;

signed main() {
    std::string s;
    std::vector<std::string> c;
    while (std::cin >> s && s != "FIN") {
        c.push_back(s);
    }

    std::stack<int> st;
    st.push(0);
    int ans = 0, cnt = 0;

    for (int i = 0; i < (int)c.size(); i++) {
        if (c[i] == "LIBRARY") {
            st.top()++;
        } else if (c[i] == "REP") {
            st.push(0);
        } else if (c[i] == "FOR") {
            int t = std::stoi(c[i + 1]); // 直接使用 c[i + 1] 而不是 c[i + 1].c_str()
            int p = st.top();
            st.pop();
            st.top() += p * t;
            st.top() %= Mod;
        }
    }

    std::cout << st.top() << "\n";
    return 0;
}

posted on 2024-09-04 14:18  yongchaoD  阅读(42)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3