[20250908] BOJ / P1 / 트리와 XOR 쿼리 / 권혁준 #846
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🧷 문제 링크
https://www.acmicpc.net/problem/24532
🧭 풀이 시간
60분
👀 체감 난이도
✏️ 문제 설명
정점이 N개이고, 간선에 가중치가 있는 트리가 주어지고, 트리의 루트는 1번 정점이다.
d(x,y)는 x, y를 잇는 경로 상의 가중치를 모두 xor한 값으로 정의한다.
두 쿼리를 수행해보자.
1 x v : x번 노드에서 x번 노드의 부모로 가는 간선의 가중치를 v로 바꾼다.
2 x y : x의 서브트리에 속한 점 a와 y의 서브트리에 속한 점 b에 대해, 모든 d(a,b)의 합을 출력한다.
🔍 풀이 방법
루트에서 어떤 점 x까지의 경로 가중치를 xor한 값을 D[x]라고 하면, d(x,y) = D[x] ^ D[y]가 된다.
xor연산은 각 비트 별로 독립적이라, 비트 개수( = 20)만큼 세그트리를 만들고 각 비트가 켜져있는지 여부를 관리했다.
그러면 2번 쿼리 (x,y)에 대해, k번째 비트에서 x의 서브트리 아래에 켜져있는 비트 개수를 o1, 꺼져있는 비트 개수를 z1이라 하고 똑같이 y의 서브트리에 대해서는 o2, z2라고 하면 답은 (o1z2 + o2z1) * (1<<k)가 된다.
모든 k에 대해 이 값을 더해서 2번 쿼리의 답을 구했다.
1번 쿼리는 x의 서브트리에 대한 모든 값에 기존 가중치 p와 새로 들어온 가중치 v를 xor한 값을 xor해주는 식으로 처리했다.
트리를 펴서 세그트리에 넣기 위해 오일러 경로 테크닉을 사용했고, 구간 쿼리를 빠르게 처리하기 위해 lazy배열을 사용함.
⏳ 회고
lazy 구현을 이상하게 해놓고 왜 틀렸는지 못 찾고 있었음