목차

XOR

ps
링크acmicpc.net/…
출처BOJ
문제 번호12844
문제명XOR
레벨플래티넘 3
분류

구간 쿼리

시간복잡도O(n+mlogn)
인풋사이즈n<=500,000, m<=500,000
사용한 언어Python
제출기록99700KB / 5536ms
최고기록5536ms
해결날짜2021/05/06
태그

48단계

풀이

코드

코드 1 - 두개의 펜윅트리

"""Solution code for "BOJ 12844. XOR".

- Problem link: https://www.acmicpc.net/problem/12844
- Solution link: http://www.teferi.net/ps/problems/boj/12844
"""

import sys
from teflib import fenwicktree


def main():
    N = int(sys.stdin.readline())
    A = [int(x) for x in sys.stdin.readline().split()]    
    fenwick1 = fenwicktree.XorFenwickTree(N + 1)
    fenwick2 = fenwicktree.XorFenwickTree(A + [0])
    M = int(sys.stdin.readline())
    for _ in range(M):
        query = [int(x) for x in sys.stdin.readline().split()]
        if query[0] == 1:
            _, i, j, k = query
            fenwick1.update(i, k)
            fenwick1.update(j + 1, k)
            if not i % 2:
                fenwick2.update(i, k)
            if j % 2:
                fenwick2.update(j + 1, k)
        else:
            _, i, j = query
            res = fenwick2.query(0, j + 1) ^ fenwick2.query(0, i)
            if not i % 2:
                res ^= fenwick1.query(0, i)
            if j % 2:
                res ^= fenwick1.query(0, j + 1)
            print(res)


if __name__ == '__main__':
    main()

코드 2 - 세그먼트 트리 + 레이지 프로파게이션

"""Solution code for "BOJ 12844. XOR".

- Problem link: https://www.acmicpc.net/problem/12844
- Solution link: http://www.teferi.net/ps/problems/boj/12844
"""

import operator
import sys
from teflib import segmenttree


def main():
    N = int(sys.stdin.readline())  # pylint: disable=unused-variable
    A = [int(x) for x in sys.stdin.readline().split()]
    lazy_segtree = segmenttree.LazySegmentTree(
        A,
        merge=operator.xor,
        update_value=lambda v, p, size: (v ^ p) if size % 2 else v,
        update_param=operator.xor,
        should_keep_update_order=False)
    M = int(sys.stdin.readline())
    for _ in range(M):
        query = [int(x) for x in sys.stdin.readline().split()]
        if query[0] == 1:
            _, i, j, k = query
            lazy_segtree.range_update(i, j + 1, k)
        else:
            _, i, j = query
            print(lazy_segtree.query(i, j + 1))


if __name__ == '__main__':
    main()