【模拟/atoi函数】Game of Throwns stack

题目链接

分析

类似于大富翁的游戏,区别之处在于可能输入undo进行撤销,undo可以使用栈实现。此外数字与字符串混合输入,可以使用atoi函数或者stringstream重新构造流来实现字符串转整数。

atoi函数(讲解)

sta.push(atoi(str.c_str()));

AC代码

#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
typedef long long ll;

stack<int>sta;

int main()
{
  string str;
  int n, k;
  while (cin >> n >> k)//操作次数
  {
    int sum = 0;
    while (k--)
    {
      cin >> str;
      if (str == "undo")
      {
        int oper_num = 0;
        cin >> oper_num;
        while (oper_num--)
          sta.pop();
      }
      else
        sta.push(atoi(str.c_str()));
    }
    sum = 0;
    while (!sta.empty())
    {
      sum += sta.top();
      sta.pop();
    }
    cout << (sum % n +n)%n << endl;
  }
}

string流

stringstream stringstr;
        stringstr << str;
        int tempNum = 0;
        stringstr >> tempNum;
        sta.push(tempNum);

AC代码

#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
typedef long long ll;

stack<int>sta;

int main()
{
  string str;
  int n, k;
  while (cin >> n >> k)//操作次数
  {
    int sum = 0;
    while (k--)
    {
      cin >> str;
      if (str == "undo")
      {
        int oper_num = 0;
        cin >> oper_num;
        while (oper_num--)
        {
          sta.pop();
        }
      }
      else
      {
        stringstream stringstr;
        stringstr << str;
        int tempNum = 0;
        stringstr >> tempNum;
        sta.push(tempNum);
      }
    }
    sum = 0;
    while (!sta.empty())
    {
      sum += sta.top();
      sta.pop();
    }
    cout << (sum % n +n)%n << endl;
  }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

4 × 1 =