40pts求调悬关
查看原帖
40pts求调悬关
556649
_zhang楼主2024/8/28 18:32

第一眼看到就觉得是模拟,于是用了栈,我的代码还有救吗?(自测样例2未过

//@todo 40pts
#include <iostream>
#include <stack>
#include <assert.h>
using namespace std;
string s;
int ans1, ans2;
struct pbii { bool x; int y, z; };  // pbii=pair bool int int, y: |, z: &
pbii OR(pbii x, pbii y) {
    cout << "OR " << x.x << ", " << y.x << endl;
    if (x.x == 1) y.y = 1, y.z = 0;
    return (pbii){x.x || y.x, x.y + y.y, x.z + y.z};
}
pbii AND(pbii x, pbii y) {
    cout << "AND " << x.x << ", " << y.x << endl;
    if (x.x == 0) y.y = 0, y.z = 1;
    return (pbii){x.x && y.x, x.y + y.y, x.z + y.z};
}
void func(std::stack<bool> &sta1, std::stack<pbii> &sta2) {
    if (sta1.empty() || sta2.size() < 2) return;
    pbii y = sta2.top(); sta2.pop();
    pbii x = sta2.top(); sta2.pop();
    if (sta1.top()) sta2.push(AND(x, y));
    else sta2.push(OR(x, y));
    sta1.pop();
}
pbii calc(string s) {
    //cout << "calc " << s << ": \n";
    string sub("");
    std::stack<bool> sta1;  //0:|, 1:&
    std::stack<pbii> sta2;  // number
    int in_braket = 0;
    for (int i = 0; i < (int)s.size(); i++) {
        char c = s[i];
        if (c == '(') {
            in_braket++;
        } else if (in_braket) {
            if (c == ')') in_braket--;
            if (!in_braket) {
                sta2.push(calc(sub));
                sub = "";
            } else if (c != ')') sub += c;
        } else if (c == '0') {
            sta2.push({0, 0, 0});
        } else if (c == '1') {
            sta2.push({1, 0, 0});
        } else if (c == '|') {
            while (!sta1.empty()) func(sta1, sta2);
            sta1.push(0);
        } else if (c == '&') {
            while (!sta1.empty() && sta1.top()) func(sta1, sta2);
            sta1.push(1);
        }
    }
    while (!sta1.empty()) func(sta1, sta2);
    //assert(sta2.size() == 1);
    //cout << "-res: " << sta2.top().x << endl;
    return sta2.top();
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> s;
    pbii res = calc(s);
    cout << res.x << "\n" << res.z << " " << res.y << "\n";
    return 0;
}

求大佬指出错误并提供解决方案,本人代码不怎么带注释可能有点晦涩难懂,请见谅,玄关

2024/8/28 18:32
加载中...