結果
問題 | No.1641 Tree Xor Query |
ユーザー |
![]() |
提出日時 | 2025-03-20 21:20:29 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 250 ms / 5,000 ms |
コード長 | 2,733 bytes |
コンパイル時間 | 167 ms |
コンパイル使用メモリ | 82,364 KB |
実行使用メモリ | 142,632 KB |
最終ジャッジ日時 | 2025-03-20 21:21:22 |
合計ジャッジ時間 | 2,684 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 18 |
ソースコード
import sysdef main():sys.setrecursionlimit(1 << 25)input = sys.stdin.readdata = input().split()ptr = 0N, Q = int(data[ptr]), int(data[ptr+1])ptr += 2C = list(map(int, data[ptr:ptr+N]))ptr += N# Build adjacency listadj = [[] for _ in range(N+1)]for _ in range(N-1):a = int(data[ptr])b = int(data[ptr+1])ptr +=2adj[a].append(b)adj[b].append(a)# Compute in_time and out_time using iterative DFSin_time = [0] * (N +1)out_time = [0] * (N +1)time =0stack = [(1, False, -1)] # node, visited, parentwhile stack:node, visited, parent = stack.pop()if not visited:# Mark in_time when first visitingtime +=1in_time[node] = time# Push back as visitedstack.append( (node, True, parent) )# Push children in reversed order (so that when popped, processed in order)# Collect children (excluding parent)children = []for neighbor in adj[node]:if neighbor != parent:children.append(neighbor)# Push children in reversed orderfor child in reversed(children):stack.append( (child, False, node) )else:# Mark out_time when done with all childrenout_time[node] = time# Fenwick Tree implementation for XORclass FenwickTree:def __init__(self, size):self.n = sizeself.tree = [0]*(self.n +1) # 1-baseddef update(self, idx, delta):# XOR delta to position idxwhile idx <= self.n:self.tree[idx] ^= deltaidx += idx & -idxdef query(self, idx):# Compute XOR from 1 to idxres =0while idx >0:res ^= self.tree[idx]idx -= idx & -idxreturn res# Initialize Fenwick Treeft = FenwickTree(N)for i in range(1, N+1):pos = in_time[i]ft.update(pos, C[i-1])# Process queriesoutput = []for _ in range(Q):T_j = int(data[ptr])x_j = int(data[ptr+1])y_j = int(data[ptr+2])ptr +=3if T_j ==1:pos = in_time[x_j]ft.update(pos, y_j)else:l = in_time[x_j]r = out_time[x_j]xor_r = ft.query(r)xor_l_1 = ft.query(l-1) if l >1 else 0res = xor_r ^ xor_l_1output.append(str(res))print('\n'.join(output))if __name__ == "__main__":main()