Problem K. Expression in Memories

Problem K. Expression in Memories

Problem Description

Kazari remembered that she had an expression s0 before.
Definition of expression is given below in Backus–Naur form.
::= |
::= “+” | “*”
::= “0” |
::= “” |
::= “0” |
::= “1” | “2” | “3” | “4” | “5” | “6” | “7” | “8” | “9”
For example, 1*1+1, 0+8+17 are valid expressions, while +1+1, +1*+1, 01+001 are not.
Though s0 has been lost in the past few years, it is still in her memories.
She remembers several corresponding characters while others are represented as question marks.
Could you help Kazari to find a possible valid expression s0 according to her memories, represented as s , by replacing each question mark in s with a character in 0123456789+* ?

Input
The first line of the input contains an integer T denoting the number of test cases. Each test case consists of one line with a string s (1|s|500,|s|105) . It is guaranteed that each character of s will be in 0123456789+*? .

Output
For each test case, print a string s0 representing a possible valid expression. If there are multiple answers, print any of them. If it is impossible to find such an expression, print IMPOSSIBLE.

Sample Input
5
?????
0+0+0
?+*??
?0+?0
?0+0?

Sample Output
11111
0+0+0
IMPOSSIBLE
10+10
IMPOSSIBLE

题目概述

给出一个字符串,字符串只由”0、1、2、3、4、5、6、7、8、9、*、+、?”组成。
?可以变成0、1、2、3、4、5、6、7、8、9、*、+中任意一个。
我们要做的就是将?变换成其他字符,使这个字符串变成有效表达式,并输出即可。
如果不能使该字符串变成有效表达式,则输出“IMPOSSIBLE”。

输入第一行有一个整数T代表测试样例。
接下来的T行输入字符串s(|s|≤ 500,每个字符串都是由“0、1、2、3、4、5、6、7、8、9、*、+、?”组成的)

思路

我们首先要知道什么是有效表达式

  1. 字符串头和尾一定不能为运算符。
  2. “+0?”或“*0?”的情况时,“?”要变成‘’+“”。
  3. 不能是“+0n”或“*0n”(n为1,2,3,4,5,6,7,8,9)。
  4. 两个运算符不能连在一起。
  5. 其他情况下“?”,可变为1,2,3,4,5,6,7,8,9任一个(不变成“0”是因为怕出现3.的情况)。以为输出任意情况即可。那我们不妨把他都变成“·1”。

isdigit(a):a是字符(char),isdigit()是用来判断,a是不是数字的,如果是返回1,不是返回0

代码
#include<bits/stdc++.h>

using namespace std;

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        char a[1005];
        scanf("%s",a);
        for(int i=0;i<strlen(a);i++)
        {
            if(a[i]=='?')
            {
                if(isdigit(a[i-2])==0&&a[i-1]=='0') a[i]='+';
                //当遇到"+0?"或者"*0?"时?替换为+
                else a[i]='1'; //其他情况?换为1
            }
        }
        int f=0;
        for(int i=0;i<strlen(a);i++) 
        {
            if(isdigit(a[i])==0)  //遇到一个运算符
            {
                if(isdigit(a[i+1])==0)//如果下一位也为运算符,不是有效表达式
                    f=1;
            }
            else if(a[i]=='0')  //遇到0
            {
                if(isdigit(a[i-1])==0&&isdigit(a[i+1])!=0)//如果是"+0n"或"*0n",不是有效表达式
                    f=1;
            } 
        }
        if(isdigit(a[0])==0||isdigit(a[strlen(a)-1])==0)//如果字符串头或尾为运算符,不是有效表达式
            f=1;
        if(f==1) printf("IMPOSSIBLE\n");
        else printf("%s\n",a);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章