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;
}
智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告