CCF CSP刷题—二十四点

【题目描述】
定义每个游戏由4个从1-9的数字和三个四则运算符组成,保证数字运算符将数字两两隔开,不存在括号和其他字符,运算顺序按照四则运算顺序进行。其中加法用符号‘+’表示,减法用符号‘-’表示,乘法用小写字母’x’表示,除法用符号’/‘表示,在游戏里除法为整除,例如2/3=0,3/2=1,4/2=2。
【输入格式】
从标准输入读入数据。
第一行输入一个整数n,从第二行开始到第n+1行包含一个长度为7的字符串,为上述的24点游戏,保证数据格式合法。
【输出格式】
输出到标准输出。
包含n行,对于每个游戏,如果其结果为24则输出字符串Yes,否则输出字符串No。
【输入样例1】
10
9+3+43
5+455
7-9-9+8
56/54
3+5+7+9
11+9-9
19-5/9
8/5+69
67-36
6*4+4/5
【输出样例1】
Yes
No
No
Yes
Yes
No
No
No
Yes
Yes
代码:

#include<iostream>
#include<string>
using namespace std;

int main() {
 int n = 0;
 cin >> n;
 char ** forlumn = new char*[n];
 for (int i = 0; i < n; i++) {
  forlumn[i] = new char[7];
 }
 for (int i = 0; i < n; i++) {
  cin >> forlumn[i];
 }
 char * ch = new char[7];
 int * result = new int[n];
 int temp = 0;
 int a = 0;
 int b = 0;
 int * num = NULL;
 char * cal = NULL;
 int x = 0;
 int y = 0;
 for (int i = 0; i < n; i++) {
  ch = forlumn[i];
  num = new int[4];
  x = 0;
  cal = new char[3];
  y = 0;
  for (int j = 0; j < 7; j = j + 2) {
   if (ch[j + 1] != 'x' && ch[j + 1] != '/' && j!=6) {
    if (ch[j] != 't') {
     num[x] = ch[j] - '0';
     x++;
    }
    else {
     num[x] = temp;
     x++;
    }
    cal[y] = ch[j + 1];
    y++;
   }
   else if (j == 6) {
    if (ch[j] != 't') {
     num[x] = ch[j] - '0';
     x++;
    }
    else {
     num[x] = temp;
     x++;
    }
   }
   else if (ch[j + 1] == 'x') {
    if (ch[j] != 't')
     a = ch[j] - '0';
    else
     a = temp;
    b = ch[j + 2] - '0';
    temp = a * b;
    ch[j + 2] = 't';
   }
   else if (ch[j + 1] == '/') {
    if (ch[j] != 't')
     a = ch[j] - '0';
    else
     a = temp;
    b = ch[j + 2] - '0';
    temp = a / b;
    ch[j + 2] = 't';
   }
   
  }
  x = 0;
  result[i] = num[x];
  x++;
  for (int k = 0; k < y; k++) {
   if (cal[k] == '+') {
    result[i] += num[x];
    x++;
   }
   else if (cal[k] == '-') {
    result[i] = result[i] - num[x];
    x++;
   }
  }
  if (result[i] == 24)
   cout << "Yes" << endl;
  else
   cout << "No" << endl;
  system("pause");
  delete[]num;
  delete[]cal;
 }
 return 0;
}

bool isNum(char c) {
 if (c >= '0'&&c <= '9') {
  return true;
 }
 return false;
}

开始只能得50分,改了好久发现,题目中的乘法要用小写字母‘x’…

猜你喜欢

转载自blog.csdn.net/qq_36795903/article/details/89676585