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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章