2018杭电多校: Problem K. Expression in Memories

题目描述

Kazari remembered that she had an expression s0 before.
Definition of expression is given below in Backus–Naur form.
<expression> ::= <number> | <expression> <operator> <number>
<operator> ::= "+" | "*"
<number> ::= "0" | <non-zero-digit> <digits>
<digits> ::= "" | <digits> <digit>
<digit> ::= "0" | <non-zero-digit>
<non-zero-digit> ::= "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+* ?

输入

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+*? .

输出

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.

样例输入

5
?????
0+0+0
?+*??
?0+?0
?0+0?

样例输出

11111
0+0+0
IMPOSSIBLE
10+10
IMPOSSIBLE

解题:模拟

#include <bits/stdc++.h>
#define LL long long;
using namespace std;
const int N = 1e5;
bool flag[1005];
string s;
bool issign(char key){
    if (key=='+' || key=='*') return true;
    return false;
}
bool isnumber(char key){
    if (key>='0' && key<='9')
        return true;
    return false;
}
bool ok(){
    memset(flag,0,sizeof flag);
    int len = s.size();
    for (int i = 0;i < len;i++)
        if (s[i]=='?')
            flag[i] = 1;
    for (int i = 0;i < len;i++)
        if (s[i]=='?')
            s[i] = '1';
    for (int i = 0;i < len;i++){
        if (s[i]=='0' && (i==0 || !isnumber(s[i-1])) && i<len-1 && isnumber(s[i+1])){
            if (!flag[i+1]) return false;
            s[i+1] = '+';
        }
 
    }
    if (issign(s[0]) || issign(s[len-1])) return false;
    for (int i = 0;i < len-1;i++)
        if (issign(s[i]) && issign(s[i+1]))
            return false;
    return true;
}
 
int main(){
    ios::sync_with_stdio(0),cin.tie(0);
    int T;
    cin >> T;
    while (T--){
        cin >> s;
        if (!ok()){
            cout<<"IMPOSSIBLE"<<endl;
        }else{
            cout<<s<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40911499/article/details/81357248