P8815 [CSP-J 2022] 逻辑表达式 题解

短路

我们可以使用一个变量来记录当前有没有短路.

设变量短路为 \(dl\). 当 \(dl\)\(0\) 时,说明当前值为 \(0\),且运算符为 &.

\(dl\)\(1\) 时,说明当前值为 \(1\),且运算符为 |.

代码

重点讲完了,细节可以看代码以及注释.

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

string s;
int ansv, ans1, ans2;
int is_dl = -1;

int main() {
	getline(cin, s);
	for (int i = 0; i < s.size(); i++) {
		if (is_dl != -1) { // 没有短路
			if (s[i] == '(') { // 跳掉括号
				int nowp = 1; // 括号个数
				while (nowp > 0) { // 知道没有括号为止
					i++;
					if (s[i] == '(') nowp++;
					if (s[i] == ')') nowp--;
				}
			}
			else if (is_dl == 0 && s[i] == '|') // 非正确短路
				is_dl = -1; // 不判断 & 是因为运算级优先的问题
			else if (s[i] == ')') // 没有运算符或值
				is_dl = -1;
			else if (is_dl == 0 && s[i] == '&') // 成功短路
				ans1++;
			else if (is_dl == 1 && s[i] == '|') // 成功短路
				ans2++;
		}
		else {
            // 记录答案
			if (s[i] == '0' || s[i] == '1') ansv = s[i] - '0';
			if (ansv == 0 && s[i] == '&') { // 短路 0 & ...
				is_dl = 0;
				ans1++;
			}
			else if (ansv == 1 && s[i] == '|') { // 短路 1 | ...
				is_dl = 1;
				ans2++; 
			}
		}
	}
	printf("%d\n%d %d", ansv, ans1, ans2);
	return 0;
}
posted @ 2024-10-23 12:09  Panda_LYL  阅读(21)  评论(0)    收藏  举报