SCP-J C题求优化,悬关

学术版

DGFLSzfd @ 2024-10-13 16:46:13

三目运算,我感觉我逻辑很清晰,可惜优化无从下手,超时了(悲)

#include <bits/stdc++.h>
using namespace std;
int f(const string &S, int &pos, int x) 
{
    int result=0;
    while (pos<S.length() and isdigit(S[pos])) 
    {
        result=result*10+(S[pos]-'0');
        pos++;
    }
    if (pos == S.length() || S[pos] != 'x') 
    {
        return result;
    }//算尽了 

    //嵌套了下一个三目 
    bool greater=(S[pos + 1] == '>');
    pos += 2;  

    int con = 0;
    while (isdigit(S[pos])) 
    {
        con=con*10+(S[pos]-'0');
        pos++;
    }
    pos++;

    int truee = f(S, pos, x);
    pos++;
    int falsee = f(S, pos, x);
    if ((greater and x > con) or (!greater and x < con)) 
    {
        return truee;
    } 
    else 
    {
        return falsee;
    }
}

int main() 
{
    int m,q;
    cin >>m>>q;
    string S;
    cin>>S;
    while(q--) 
    {
        int x;
        cin>>x;
        int pos=0; 
        cout<<f(S,pos,x)<<endl;
    }
    return 0;
}

by Manki233 @ 2024-10-13 16:48:54

@DGFLSzfd 不要都遍历一次,用栈记录,跳过一部分


by DGFLSzfd @ 2024-10-13 16:50:02

@Manki233 细说?!


|