社区讨论

求优化,玄关

灌水区参与者 3已保存回复 4

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
4 条
当前快照
1 份
快照标识符
@m27e7cki
此快照首次捕获于
2024/10/13 17:38
去年
此快照最后确认于
2025/11/04 17:16
4 个月前
查看原帖
题目:三目运算
我感觉我逻辑很清晰,可惜优化无从下手,超时了(悲) 代码:
CPP
#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;
}

回复

4 条回复,欢迎继续交流。

正在加载回复...