ZOJ 3930 Dice Notation【模擬】【字符串】

題目鏈接

http://www.icpc.moe/onlinejudge/showProblem.do?problemId=5690

思路

題目有點長,其實前面都是廢話,直接看樣例都能看懂。

三件事

  1. Expand dice notations.
    The <dice> field like “3d5” should be expanded to “([d5] + [d5] + [d5])“. If only one dice is rolled in this field, simply replaced it with “[dX]“.
  2. Trim whitespaces.
    There should be one and only one space character existed around operators (“+” / “-” / “*” / “/”). No extra whitespaces characters (including “Tab” and “Space”) are allowed in the format string.

  3. End with specific content.
    Add “= [Result]” to the end of the format string.

題目本身很簡單,但有個坑就是,d後面的數,或者直接數字,是有可能出現大數的,比賽時就栽這個坑裏了導致沒過。

AC代碼

#include <iostream>
#include <cstdio>
#include <set>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <string>
#include <cctype>
using namespace std;

int main()
{
    int T;
    cin >> T;
    getchar();
    while (T--)
    {
        string s;
        getline(cin, s);
        int num = 0;
        for (int i = 0; i < s.length(); ++i)
        {
            if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
            {
                printf(" %c ", s[i]);
            }
            else if (isdigit(s[i]))
            {
                int j;
                string out_num;//大數輸出用
                for (j = i; j < s.length() && isdigit(s[j]); ++j)
                {
                    num *= 10;
                    num += s[j] - '0';
                    out_num += s[j];
                }
                j--;
                i = j;
                if (i == s.length() - 1 || s[i + 1] != 'd')
                {
                    printf("%s", out_num.c_str());
                    num = 0;
                }
            }
            else if (s[i] == 'd')
            {
                int j;
                string num2;
                for (j = i + 1; j < s.length() && isdigit(s[j]); ++j)
                {
                    num2 += s[j];
                }
                j--;
                i = j;
                if (num == 1 || num == 0)
                {
                    printf("[d%s]", num2.c_str());
                }
                else
                {
                    printf("(");
                    for (int j = 0; j < num; ++j)
                    {
                        if (j == 0)printf("[d%s]", num2.c_str());
                        else printf(" + [d%s]", num2.c_str());
                    }
                    printf(")");
                }
                num = 0;
            }
            else if (s[i] == '(' || s[i] == ')')
            {
                printf("%c", s[i]);
            }
        }
        printf(" = [Result]\n");
    }
    return 0;
}
發佈了116 篇原創文章 · 獲贊 48 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章