【栈】2021年度训练联盟热身训练赛第三场 A.Circuit Math

A.Circuit Math

题目大意

模拟电路的与、或、非运算,输出最后的结果。

解题思路

用栈模拟。

与、或运算需要两个运算数,则从栈里弹出两个数,运算结果压入栈。

非运算弹出一个数,处理后压入栈。

参考代码

#include<stdio.h>
#include<iostream>
#include<vector>
#include<cstring>
#include<cstdio>
#include<climits>
#include<cmath>
#include<algorithm>
#include<queue>
#include<deque>
#include<map>
#include<unordered_map>
#include<set>
#include<stack>
//#define LOCAL  //提交时一定注释
#define VI vector<int>
#define eps 1e-8
#define io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
using namespace std;
typedef long long LL;
typedef double db;
const int inf = 0x3f3f3f3f;
const LL INF = 1e18;
const int N = 50;
#define ls rt << 1
#define rs rt << 1 | 1
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1

inline int readint() {int x; scanf("%d", &x); return x;}

int an(int x, int y) {  //与
    return x && y;
}

int o(int x, int y) {  //或
    return x || y;
}
int no(int x) {  //非
    return x ^ 1;    
}
int val[N];
int main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
//   freopen("output.txt", "w", stdout);
#endif
    int n = readint();
    stack<int> st;
    char c;
    for(int i = 0; i < n; ++i) {
        cin >> c;
        val[i] = (c == 'T' ? 1 : 0);
    }
    while (cin >> c) {
        if (isalpha(c)) {
            st.push(val[c - 'A']);
        }
        else {
            if (c == '*' || c == '+') {
                int a = st.top(); st.pop();
                int b = st.top(); st.pop();
//                cout << "a:" << a << " " << "b:" << b;
                int r = (c == '*' ? an(a, b) : o(a, b));
//                cout << "now a:" << a << endl;
                st.push(r);
            }
            else {
                int a = st.top(); st.pop();
                int r = no(a);
                st.push(r);
            }
        }
    }
    cout << ((st.top()) ? 'T' : 'F');

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值