CF60A Where Are My Flakes? 题解

Content

有人发现他的麦片不见了,原来是室友把它藏在了 \(n\) 个盒子中的一个,另外还有 \(m\) 个提示,有两种:

  • \(\texttt{To the left of }x\):麦片在第 \(x\) 个盒子的左边(不含 \(x\))。
  • \(\texttt{To the right of }x\):麦片在第 \(x\) 个盒子的右边(不含 \(x\))。

我们假设这些提示都是真的。求这个人需要检查多少个盒子,或者麦片根本就不存在 😦。

数据范围:\(1\leqslant n\leqslant 1000,0\leqslant m\leqslant 1000\)

Solution

我们发现,通过提示我们可以确定需要找麦片的盒子区间。具体如下:

  • 如果给的提示是 \(\texttt{To the left of }x\),并且右边界没有 \(x\) 小,那么根据题意,将右边界 \(r\) 更新为 \(x-1\)

  • 否则,如果给的提示是 \(\texttt{To the right of }x\),并且左边界没有 \(x\) 大,那么根据题意,将左边界 \(l\) 更新为 \(x+1\)

最后判断左边界是否大于右边界,如果没有大于右边界,那么答案就是 \(r-l+1\)。例如,需要找麦片的盒子区间为 \([1,3]\),那么答案就是 \(3-1+1=3\)

Code

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;

int n, m, l, r, x;
string s[7];

int main() {
	scanf("%d%d", &n, &m);
	l = 1, r = n;
	for(int i = 1; i <= m; ++i) {
		cin >> s[1] >> s[2] >> s[3] >> s[4];
		scanf("%d", &x);
		if(s[3] == "left")	r = min(r, x - 1);
		else if(s[3] == "right")	l = max(l, x + 1);
	}
	if(l > r)	printf("-1");
	else	printf("%d", r - l + 1);
}
posted @ 2021-12-21 20:20  Eason_AC  阅读(60)  评论(0)    收藏  举报