写在开头的话
学习了今天的基础知识,让我们来做道题来练练手吧。(题目是别的地方扒来的,参考答案是我自己写的,肯定不是最优解,有更好的方法欢迎评论区交流)
题目一------整数二分


第一题参考答案(Python版)
python
import sys
import bisect
def main():
data = sys.stdin.read().split()
it = iter(data)
n = int(next(it))
q = int(next(it))
A = [int(next(it)) for _ in range(n)]
out_lines = []
for _ in range(q):
t = int(next(it))
l = int(next(it))
r = int(next(it))
x = int(next(it))
if t == 1: # 等于 x 的最左边下标
low = bisect.bisect_left(A, x) + 1 # 全局第一个 >= x 的下标(1‑based)
pos = max(low, l)
if pos <= r and A[pos-1] == x:
out_lines.append(str(pos))
else:
out_lines.append("-1")
elif t == 2: # 等于 x 的最右边下标
high = bisect.bisect_right(A, x) + 1 # 全局第一个 > x 的下标(1‑based)
pos = min(high-1, r)
if pos >= l and A[pos-1] == x:
out_lines.append(str(pos))
else:
out_lines.append("-1")
elif t == 3: # 第一个 >= x 的下标
low = bisect.bisect_left(A, x) + 1
pos = max(low, l)
if pos <= r:
out_lines.append(str(pos))
else:
out_lines.append("-1")
else: # t == 4,第一个 > x 的下标
high = bisect.bisect_right(A, x) + 1
pos = max(high, l)
if pos <= r:
out_lines.append(str(pos))
else:
out_lines.append("-1")
sys.stdout.write("\n".join(out_lines))
if __name__ == "__main__":
main()