結果

問題 No.1802 Range Score Query for Bracket Sequence
ユーザー NatsubiSoganNatsubiSogan
提出日時 2021-11-20 11:26:31
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 737 ms / 2,000 ms
コード長 1,984 bytes
コンパイル時間 283 ms
コンパイル使用メモリ 86,688 KB
実行使用メモリ 106,376 KB
最終ジャッジ日時 2023-09-12 14:07:28
合計ジャッジ時間 12,113 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 71 ms
71,232 KB
testcase_01 AC 697 ms
105,852 KB
testcase_02 AC 624 ms
105,832 KB
testcase_03 AC 640 ms
106,160 KB
testcase_04 AC 627 ms
106,216 KB
testcase_05 AC 637 ms
106,120 KB
testcase_06 AC 637 ms
106,192 KB
testcase_07 AC 626 ms
106,224 KB
testcase_08 AC 641 ms
106,104 KB
testcase_09 AC 625 ms
106,260 KB
testcase_10 AC 637 ms
105,984 KB
testcase_11 AC 626 ms
106,124 KB
testcase_12 AC 624 ms
106,096 KB
testcase_13 AC 630 ms
106,376 KB
testcase_14 AC 737 ms
106,204 KB
testcase_15 AC 74 ms
71,380 KB
testcase_16 AC 74 ms
71,392 KB
testcase_17 AC 73 ms
71,316 KB
testcase_18 AC 74 ms
71,392 KB
testcase_19 AC 74 ms
71,448 KB
testcase_20 AC 74 ms
71,372 KB
testcase_21 AC 72 ms
71,004 KB
testcase_22 AC 73 ms
71,276 KB
testcase_23 AC 74 ms
71,220 KB
testcase_24 AC 72 ms
71,208 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class BinaryIndexedTree():
	def __init__(self, n: int) -> None:
		self.n = 1 << (n.bit_length())
		self.BIT = [0] * (self.n + 1)

	def build(self, init_lis: list) -> None:
		for i, v in enumerate(init_lis):
			self.add(i, v)

	def add(self, i: int, x: int) -> None:
		i += 1
		while i <= self.n:
			self.BIT[i] += x
			i += i & -i
	
	def sum(self, l: int, r: int) -> int:
		return self._sum(r) - self._sum(l)

	def _sum(self, i: int) -> int:
		res = 0
		while i > 0:
			res += self.BIT[i]
			i -= i & -i
		return res

n, q = map(int, input().split())
s = input()
pos_lis = []
brac_lis = []
for i in range(n):
	if i + 1 < n and s[i] == "(" and s[i + 1] == ")": pos_lis.append(1) # () の ( の方を管理するため
	else: pos_lis.append(0)
	if s[i] == "(": brac_lis.append(1)
	else: brac_lis.append(0)
BIT = BinaryIndexedTree(n)
BIT.build(pos_lis)
for _ in range(q):
	t, *Query = map(int, input().split())
	if t == 1:
		i = Query[0]
		i -= 1
		if brac_lis[i] == 0: # i 文字目が ) のとき
			brac_lis[i] = 1 # ( に変更
			if i - 1 >= 0 and brac_lis[i - 1] == 1: # i - 1 文字目が ( であったとき
				BIT.add(i - 1, -1) # () が 1 つ減るので、i - 1 番目から 1 を引く
			if i + 1 < n and brac_lis[i + 1] == 0: # i + 1 文字目が ) であったとき
				BIT.add(i, 1) # () が 1 つ増えるので、i 番目の場所に記録しておく
		else: # i 文字目が ( のとき
			brac_lis[i] = 0 # ) に変更
			if i + 1 < n and brac_lis[i + 1] == 0: # i + 1 文字目が ) であったとき
				BIT.add(i, -1) # () が 1 つ減るので、i 番目から 1 を引く
			if i - 1 >= 0 and brac_lis[i - 1] == 1: # i - 1 文字目が ( であったとき
				BIT.add(i - 1, 1) # () が 1 つ増えるので、i - 1 番目の場所に記録しておく
	else:
		l, r = Query
		l -= 1; r -= 1
		print(BIT.sum(l, r)) # l 文字目から r 文字目まで見ているが、() の位置は ( の方で管理しているので、a[l]+a[l+1]+...+a[r-1] でいい
0