Problem:


Score : 500 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.

Process Q queries of the following two types:

Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.)

Type 2: answer the number of different characters occurring in the substring of S between the l_q-th and r_q-th characters (inclusive).

Constraints

N, Q, i_q, l_q, and r_q are integers.

S is a string consisting of lowercase English letters.

c_q is a lowercase English letter.

1 \leq N \leq 500000

1 \leq Q \leq 20000

|S| = N

1 \leq i_q \leq N

1 \leq l_q \leq r_q \leq N

There is at least one query of type 2 in each testcase.

Input

Input is given from Standard Input in the following format:

N
S
Q
Query_1
\vdots
Query_Q

Here, Query_i in the 4-th through (Q+3)-th lines is one of the following:

1 i_q c_q

2 l_q r_q

Output

For each query of type 2, print a line containing the answer.

Sample Input 1

7
abcdbbd
6
2 3 6
1 5 z
2 1 1
1 4 a
1 7 d
2 1 7

Sample Output 1

3
1
5

In the first query, cdbb contains three kinds of letters: b , c , and d, so we print 3.

In the second query, S is modified to abcdzbd.

In the third query, a contains one kind of letter: a, so we print 1.

In the fourth query, S is modified to abcazbd.

In the fifth query, S does not change and is still abcazbd.

In the sixth query, abcazbd contains five kinds of letters: a, b, c, d, and z, so we print 5.



Sample input:
7
abcdbbd
6
2 3 6
1 5 z
2 1 1
1 4 a
1 7 d
2 1 7


Sample output:
3
1
5

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc157/tasks/abc157_e
# セグメント木
# 各文字をビットに対応させる(セグ木を26本持っても良い)
import sys
read = sys.stdin.readline
from functools import reduce


def read_a_int():
    return int(read())


class SqrtDecomposedList:
    def __init__(self, ls, segfunc, identity_element):
        from math import sqrt
        from copy import copy
        self.f = segfunc  # queryのfunction
        self.ide = identity_element
        self.n = len(ls)
        self.ls = copy(ls)
        self.b = int(sqrt(self.n)) + 1
        self.bucket = [self.ide] * (self.b + 1)
        self._build()

    def _build(self):
        for d in range(self.b):
            self.bucket[d] = reduce(
                self.f, self.ls[(d * self.b):((d + 1) * self.b)], self.ide)
        # for i, v in enumerate(self.ls):
        #     self.bucket[i // self.b] = \
        #         self.f(v, self.bucket[i // self.b])

    def __getitem__(self, idx):
        return self.ls[idx]

    def update(self, i, x):
        '''i番目の要素をxに更新する O(√n)'''
        self.ls[i] = x
        s = i // self.b * self.b
        t = s + self.b
        # print(i, self.b, i // self.b, s, t)
        self.bucket[i // self.b] = reduce(self.f,
                                          self.ls[s:t], self.ide)

    def query(self, l, r):
        '''半開区間[l,r)で指定すること O(√n)'''
        if r - l < 2 * self.b:
            return reduce(self.f, self.ls[l:r])
        l_bucket = (l - 1) // self.b + 1
        r_bucket = r // self.b  # 半開区間なのでこれでいい
        ret = reduce(self.f, self.bucket[l_bucket:r_bucket], self.ide)
        ret = self.f(
            reduce(self.f, self.ls[l:(l_bucket * self.b)], self.ide),
            ret)
        ret = self.f(
            reduce(self.f, self.ls[(r_bucket * self.b):r], self.ide),
            ret)
        return ret


def segfunc(x, y):
    # 処理したい内容
    return x | y


def moji_to_bit(a):
    return 1 << (ord(a) - ord('a'))


def bit_to_sum(n):
    return sum([(n >> i) & 1 for i in range(n.bit_length())])


N = read_a_int()
S = read()[:-1]
S_bit = [moji_to_bit(s) for s in S]

# build segment tree
st = SqrtDecomposedList(S_bit, segfunc, 0)

Q = read_a_int()
for q in range(Q):
    com, a, b = read().split()
    if int(com) == 1:
        i, c = int(a) - 1, b
        st.update(i, moji_to_bit(c))
    else:
        l, r = int(a) - 1, int(b)
        print(bit_to_sum(st.query(l, r)))

Submission status: Accepted

Solution code:
class BIT:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


class RangeUpdate:
    def __init__(self, n):
        self.p = BIT(n + 1)
        self.q = BIT(n + 1)

    def add(self, s, t, x):
        t += 1
        self.p.add(s, -x * s)
        self.p.add(t, x * t)
        self.q.add(s, x)
        self.q.add(t, -x)

    def sum(self, s, t):
        t += 1
        return self.p.sum(t) + self.q.sum(t) * t - \
            self.p.sum(s) - self.q.sum(s) * s


def main():
    from string import ascii_lowercase
    dic = {s: i for i, s in enumerate(ascii_lowercase)}
    import sys
    input = sys.stdin.readline
    N = int(input())
    S = [dic[s] for s in input().rstrip()]
    Q = int(input())
    Query = [[i for i in input().split()] for _ in [0]*Q]
    BIT26 = [RangeUpdate(N) for _ in [0]*26]
    for i, j in enumerate(S, start=1):
        BIT26[j].add(i, i, 1)
    answer = []
    for A in Query:
        if A[0] == "1":
            i = int(A[1])
            j = S[i-1]
            BIT26[j].add(i, i, -1)
            j = dic[A[2]]
            S[i-1] = j
            BIT26[j].add(i, i, 1)
        else:
            le = int(A[1])
            ri = int(A[2])
            ans = 0
            cur = 0
            for i in range(26):
                v = BIT26[i].sum(le, ri)
                if 0 < v:
                    ans += 1
                cur += v
                if ri - le + 1 == v:
                    break
            answer.append(ans)
    print(*answer, sep="\n")


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
class BIT:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


class RangeUpdate:
    def __init__(self, n):
        self.p = BIT(n + 1)
        self.q = BIT(n + 1)

    def add(self, s, t, x):
        t += 1
        self.p.add(s, -x * s)
        self.p.add(t, x * t)
        self.q.add(s, x)
        self.q.add(t, -x)

    def sum(self, s, t):
        t += 1
        return self.p.sum(t) + self.q.sum(t) * t - \
            self.p.sum(s) - self.q.sum(s) * s


def main():
    from string import ascii_lowercase
    dic = {s: i for i, s in enumerate(ascii_lowercase)}
    N = int(input())
    S = [s for s in input()]
    BIT26 = [RangeUpdate(N) for i in range(26)]
    for i, s in enumerate(S):
        j = dic[s]
        BIT26[j].add(i+1, i+1, 1)
    Q = int(input())
    for query in range(Q):
        A = [i for i in input().split()]
        if A[0] == "1":
            i = int(A[1])
            c = A[2]
            pre = S[i-1]
            j = dic[pre]
            BIT26[j].add(i, i, -1)
            S[i-1] = c
            j = dic[c]
            BIT26[j].add(i, i, 1)
        else:
            le = int(A[1])
            ri = int(A[2])
            ans = 0
            for i in range(26):
                if 0 < BIT26[i].sum(le, ri):
                    ans += 1
            print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def update(i,x):
    i += d-1
    bit = ord(x)-97
    seg[i] = 0 | (1<<bit)
    while i > 0:
        i = (i-1)//2
        seg[i] = seg[i*2+1]|seg[i*2+2]
def find(a,b,k,l,r):
    if r <= a or b <= l:
        return 0
    if a <= l and r <= b:
        return seg[k]
    c1 = find(a,b,2*k+1,l,(l+r)//2)
    c2 = find(a,b,2*k+2,(l+r)//2,r)
    return c1|c2
n = int(input())
s = input()
q = int(input())
d = 1
while d < n:
    d *= 2
seg = [0]*(2*d-1)
for i in range(n):
    update(i,s[i])
for i in range(q):
    type,a,b = input().split()
    if type == "1":
        update(int(a)-1,b)
    else:
        part = find(int(a)-1,int(b),0,0,d)
        print(bin(part).count("1"))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline

from bisect import bisect_left, insort_left

def main():
    n = int(readline())
    s = list(readline().rstrip())
    q = int(readline())
    
    chk_abc = [[] for i in range(26)]
    for i, si in enumerate(s):
        ci = ord(si) - 97
        chk_abc[ci].append(i)
        
    ans = []
    for _ in range(q):
        cmd, i, j = readline().rstrip().split()
        i = int(i) - 1
        
        if cmd == "1":
            if s[i] == j:
                continue
            c1 = ord(s[i]) - 97
            prev = chk_abc[c1]
            c2 = ord(j) - 97
            prev.pop(bisect_left(prev, i))
            s[i] = j
            insort_left(chk_abc[c2], i)
            
        else:
            j = int(j) - 1
            num = 0
            for chk in chk_abc:
                le = len(chk)
                k = bisect_left(chk, i, 0, le)
                if k == le:
                    continue
                if i <= chk[k] <= j:
                    num += 1
            ans.append(num)

    print(*ans, sep="\n")

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

class SegmentTree():
    def __init__(self, S, n):
        self.size = n
        self.array = [set()] * (2**(self.size + 1) - 1)
        for i, c in enumerate(S):
            self.array[i + 2**self.size - 1] = {c}
        for i in range(2**self.size - 1)[::-1]:
            self.array[i] = self.array[2 * i + 1] | self.array[2 * i + 2]

    def subquery(self, l, r, k, i, j):
        if j <= l or r <= i:
            return set()
        elif l <= i and j <= r:
            return self.array[k]
        else:
            l_set = self.subquery(l, r, 2 * k + 1, i, (i + j) // 2)
            r_set = self.subquery(l, r, 2 * k + 2, (i + j) // 2, j)
            return l_set | r_set

    def query(self, l, r):
        return len(self.subquery(l, r, 0, 0, 2**self.size))

    def update(self, i, c):
        tmp = i + 2**self.size - 1
        self.array[tmp] = {c}
        while tmp > 0:
            tmp = (tmp - 1) // 2
            self.array[tmp] = self.array[2 * tmp + 1] | self.array[2 * tmp + 2]

n = int(input())
S = [ord(c) for c in list(input())]
segtree = SegmentTree(S, 19)
for _ in range(int(input())):
    t, i, c = input().split()
    if t == '1':
        segtree.update(int(i)-1, ord(c))
    if t == '2':
        print(segtree.query(int(i)-1, int(c)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


class SegmentTree():
    # リストSの部分リストからなる集合を葉とするセグメント木
    def __init__(self, S, n):
        self.size = n
        self.array = [set()] * (2**(self.size + 1) - 1)
        for i, c in enumerate(S):
            self.array[i + 2**self.size - 1] = {c}
        for i in range(2**self.size - 1)[::-1]:
            self.array[i] = self.array[2 * i + 1] | self.array[2 * i + 2]

    def subquery(self, l, r, k, i, j):
        # 区間[i,j)の中で区間[l,r)の文字列の集合を返す
        if j <= l or r <= i:
            return set()
        elif l <= i and j <= r:
            return self.array[k]
        else:
            l_set = self.subquery(l, r, 2 * k + 1, i, (i + j) // 2)
            r_set = self.subquery(l, r, 2 * k + 2, (i + j) // 2, j)
            return l_set | r_set

    def query(self, l, r):
        # [l,r)に含まれる文字の種類数
        return len(self.subquery(l, r, 0, 0, 2**self.size))

    def update(self, i, c):
        # 配列のi番目をcに更新する
        tmp = i + 2**self.size - 1
        self.array[tmp] = {c}
        while tmp > 0:
            tmp = (tmp - 1) // 2
            self.array[tmp] = self.array[2 * tmp + 1] | self.array[2 * tmp + 2]


n = int(input())
S = list(input())
S = [ord(s) for s in S]
segtree = SegmentTree(S, 19)
for _ in range(int(input())):
    t, i, c = input().split()
    if t == '1':
        segtree.update(int(i)-1, ord(c))
    if t == '2':
        print(segtree.query(int(i)-1, int(c)))

Submission status: Accepted

Solution code:
from collections import defaultdict
from bisect import bisect_left, bisect_right, insort_left, insort_right
import sys
input = sys.stdin.readline


def main():
    N = int(input())
    S = list(input())
    q = int(input())
    Q = [input() for _ in range(q)]

    dd = defaultdict(list)  # 各アルファベットが出現するインデックスをddに登録
    for i in range(ord('a'), ord('z') + 1):
        dd[chr(i)] = []
    for i, st in enumerate(S):
        dd[st].append(i)

    ans = []
    for q in Q:
        t, a, b = q.split()
        a = int(a) - 1
        if int(t) == 1:
            if S[a] == b: continue
            # 二分探索で該当するインデックスを取得
            id = bisect_left(dd[S[a]], a)
            dd[S[a]].pop(id)  # 取ってくる
            insort_left(dd[b], a)  # 新規に挿入する
            S[a] = b
        else:
            b = int(b) - 1
            cnt = 0
            for l in dd.values():
                # liの中身が存在し，
                # そのアルファベットの最後のインデックスが指定されている最初のindexよりも大きく．
                # a以上の最初のindexがb以下の時は，そのアルファベットの存在は保証される
                if l and a <= l[-1] and l[bisect_left(l, a)] <= b:
                    cnt += 1
            ans.append(cnt)
    print(*ans, sep='\n')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


class SegmentTree():
    # リストSの部分リストからなる集合を葉とするセグメント木
    def __init__(self, S, n):
        self.size = n
        self.array = [set()] * (2**(self.size + 1) - 1)
        for i, c in enumerate(S):
            self.array[i + 2**self.size - 1] = {c}
        for i in range(2**self.size - 1)[::-1]:
            self.array[i] = self.array[2 * i + 1] | self.array[2 * i + 2]

    def subquery(self, l, r, k, i, j):
        # 区間[i,j)の中で区間[l,r)の文字列の集合を返す
        if j <= l or r <= i:
            return set()
        elif l <= i and j <= r:
            return self.array[k]
        else:
            l_set = self.subquery(l, r, 2 * k + 1, i, (i + j) // 2)
            r_set = self.subquery(l, r, 2 * k + 2, (i + j) // 2, j)
            return l_set | r_set

    def query(self, l, r):
        # [l,r)に含まれる文字の種類数
        return len(self.subquery(l, r, 0, 0, 2**self.size))

    def update(self, i, c):
        # 配列のi番目をcに更新する
        tmp = i + 2**self.size - 1
        self.array[tmp] = {c}
        while tmp > 0:
            tmp = (tmp - 1) // 2
            self.array[tmp] = self.array[2 * tmp + 1] | self.array[2 * tmp + 2]


def main():
    n = int(input())
    S = list(input())
    S = [ord(s) for s in S]
    segtree = SegmentTree(S, 19)
    for _ in range(int(input())):
        t, i, c = input().split()
        if t == '1':
            segtree.update(int(i)-1, ord(c))
        if t == '2':
            print(segtree.query(int(i)-1, int(c)))


main()

Submission status: Accepted

Solution code:
class SegmentTree():
    """一点更新、区間取得クエリをそれぞれO(logN)で答えるデータ構造を構築する。
    built(array)   := arrayを初期値とするセグメント木を構築する O(N)。
    update(i, val) := i番目の要素をvalに変更する。
    get_val(l, r)  := 区間[l, r)に対する二項演算の畳み込みの結果を返す。
    """
    def __init__(self, n, op, e):
        """要素数、二項演算、単位元を引数として渡す
        例) 区間最小値 SegmentTree(n, min, 10 ** 18)
            区間和     SegmentTree(n, lambda a, b : a + b, 0)
        """
        self.n = n
        self.op = op
        self.e = e
        self.size = 2 ** ((n - 1).bit_length())
        self.node = [self.e] * (2 * self.size)

    def build(self, array):
        """arrayを初期値とするセグメント木を構築する"""
        for i in range(self.n):
            self.node[self.size + i] = array[i]
        for i in range(self.size - 1, 0, -1):
            self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])

    def update(self, i, val):
        """i番目の要素をvalに変更する"""
        i += self.size
        self.node[i] = val
        while i > 1:
            i >>= 1
            self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])

    def get_val(self, l, r):
        """[l, r)の畳み込みの結果を返す"""
        l, r = l + self.size, r + self.size
        res_l, res_r = self.e, self.e
        while l < r:
            if l & 1:
                res_l = self.op(res_l, self.node[l])
                l += 1
            if r & 1:
                r -= 1
                res_r = self.op(self.node[r], res_r)
            l, r = l >> 1, r >> 1
        return self.op(res_l, res_r)


ALPH = "abcdefghijklmnopqrstuvwxyz"
to_int = {char: i for i, char in enumerate(ALPH)}


n = int(input())
s = input()
q = int(input())
query = [list(input().split()) for i in range(q)]

init = [0] * n
for i, char in enumerate(s):
    init[i] = 1 << to_int[char]

op = lambda a, b: a | b
st = SegmentTree(n, op, 0)
st.build(init)

for i in range(q):
    if query[i][0] == "1":
        _, ind, char = query[i]
        ind = int(ind) - 1
        st.update(ind, 1 << to_int[char])
    else:
        _, l, r = query[i]
        l, r = int(l) - 1, int(r) 
        print(bin(st.get_val(l, r)).count("1"))

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    from bisect import bisect_left, insort_left
    N = int(input())
    S = list(input())
    Q = int(input())
    dic = {chr(i): [] for i in range(ord('a'), ord('z')+1)}
    for i in range(N):
        dic[S[i]].append(i)
    for _ in range(Q):
        query, a, c = input().split()
        if query == "1":
            i = int(a)-1
            if S[i] == c:
                continue
            ind = bisect_left(dic[S[i]], i)
            dic[S[i]].pop(ind)
            insort_left(dic[c], i)
            S[i] = c
        else:
            l, r = int(a)-1, int(c)-1
            ans = 0
            for inds in dic.values():
                if inds and l <= inds[-1] and inds[bisect_left(inds, l)] <= r:
                    ans += 1
            print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

from operator import or_


class SegmentTree:
    def __init__(self, orig, func, unit):
        _len = len(orig)
        self.func = func
        self.size = 1 << (_len - 1).bit_length()
        self.tree = [unit] * self.size + orig + [unit] * (self.size - _len)
        self.unit = unit

        for i in range(self.size - 1, 0, -1):
            self.tree[i] = func(self.tree[i * 2], self.tree[i * 2 + 1])

    def update(self, i, v):
        i += self.size
        self.tree[i] = v
        while i:
            i //= 2
            self.tree[i] = self.func(self.tree[i * 2], self.tree[i * 2 + 1])

    def find(self, l, r):
        l += self.size
        r += self.size
        ret = self.unit
        while l < r:
            if l & 1:
                ret = self.func(ret, self.tree[l])
                l += 1
            if r & 1:
                r -= 1
                ret = self.func(ret, self.tree[r])
            l //= 2
            r //= 2
        return ret


n = readline()
s = readline()
q = int(readline())
li = [1 << ord(x) - 97 for x in s[:-1]]
seg = SegmentTree(li, or_, 0)
ans = []
for _ in range(q):
    f, x, y = readline().split()
    x = int(x)
    if f == '1':
        seg.update(x - 1, 1 << ord(y) - 97)
    else:
        y = int(y)
        z = seg.find(x - 1, y)
        cnt = bin(z).count('1')
        ans.append(cnt)
print(*ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


class SegmentTree:
    def __init__(self, ls: list, segfunc, identity_element):
        '''
        セグ木
        一次元のリストlsを受け取り初期化する。O(len(ls))
        区間のルールはsegfuncによって定義される
        identity elementは単位元。e.g., 最小値を求めたい→inf, 和→0, 積→1, gcd→0
        [単位元](https://ja.wikipedia.org/wiki/%E5%8D%98%E4%BD%8D%E5%85%83)
        '''
        self.ide = identity_element
        self.func = segfunc
        n = len(ls)
        self.num = 2 ** (n - 1).bit_length()  # n以上の最小の2のべき乗
        self.tree = [self.ide] * (2 * self.num - 1)  # −1はぴったりに作るためだけど気にしないでいい
        for i, l in enumerate(ls):  # 木の葉に代入
            self.tree[i + self.num - 1] = l
        for i in range(self.num - 2, -1, -1):  # 子を束ねて親を更新
            self.tree[i] = segfunc(self.tree[2 * i + 1], self.tree[2 * i + 2])

    def update(self, i, x):
        '''
        i番目の要素をxに変更する(木の中間ノードも更新する) O(logN)
        '''
        i += self.num - 1
        self.tree[i] = x
        while i:  # 木を更新
            i = (i - 1) // 2
            self.tree[i] = self.func(self.tree[i * 2 + 1],
                                     self.tree[i * 2 + 2])

    def query(self, l, r):
        '''
        区間[l,r)に対するクエリをO(logN)で処理する。例えばその区間の最小値、最大値、gcdなど
        '''
        if r <= l:
            return ValueError('invalid index (l,rがありえないよ)')
        l += self.num
        r += self.num
        res = self.ide
        while l < r:  # 右から寄りながら結果を結合していくイメージ
            if l & 1:
                res = self.func(res, self.tree[l - 1])
                l += 1
            if r & 1:
                r -= 1
                res = self.func(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/abc157/tasks/abc157_e
# 実家セグ木
# 案1 maxセグ木26本持つ(文字一つを対応させる)
# 案2 文字が出現したかしてないかを26bitの数字で表現して or 演算で区間の結果をセグ木に乗っける
# pythonだとTLEが怖いから案2で

N = read_a_int()
S = read()[:-1]
Q = read_a_int()


def char_to_26bit(c: str):
    num = ord(c) - ord('a')
    return 1 << num  # num bit目だけ1


S_num = []
for s in S:
    S_num.append(char_to_26bit(s))


def segfunc(a: int, b: int):  # 区間操作,二項演算、今だとor(少なくとも1文字がその区間に含まれている)
    return a | b


st = SegmentTree(S_num, segfunc, identity_element=0)


for _ in range(Q):
    com, *tmp = read().split()
    if com == '1':
        i, c = tmp
        st.update(int(i) - 1, char_to_26bit(c))
    else:
        l, r = map(int, tmp)
        print(bin(st.query(l - 1, r)).count('1'))  # bitの立っているところの数を数える

Submission status: Accepted

Solution code:
class SegmentTree:
    """
    0-indexed
    query : [L, R)
    """
    def __init__(self, size, initValue):
        self.size = 1 << (size.bit_length())  # 完全二分木にする
        self.data = [initValue] * (2 * self.size - 1)
        self.initValue = initValue

    def cmpFunc(self, left, right):
        return left | right

    def build(self, rawData):
        self.data[self.size - 1: self.size - 1 + len(rawData)] = rawData
        for i in range(self.size - 1)[:: -1]:
            self.data[i] = self.cmpFunc(self.data[2 * i + 1], self.data[2 * i + 2])

    def update(self, index, value):
        index += self.size - 1
        self.data[index] = value
        while index >= 0:
            index = (index - 1) // 2
            self.data[index] = self.cmpFunc(self.data[2 * index + 1], self.data[2 * index + 2])

    def query(self, left, right):
        L = left + self.size
        R = right + self.size
        ret = self.initValue
        while L < R:
            if R & 1:
                R -= 1
                ret = self.cmpFunc(ret, self.data[R - 1])
            if L & 1:
                ret = self.cmpFunc(ret, self.data[L - 1])
                L += 1
            L >>= 1
            R >>= 1
        return ret

def cToI(s):
    return ord(s) - ord('a')

N = int(input())
S = list(map(cToI, input()))

S = [1 << s for s in S]
tree = SegmentTree(N, 0)
tree.build(S)

Q = int(input())
ans = []
for _ in range(Q):
    q1, q2, q3 = input().split()

    if q1 == '1':
        tree.update(int(q2) - 1, 1 << cToI(q3))
    else:
        ans.append(tree.query(int(q2) - 1, int(q3)))

for a in ans:
    cnt = 0
    while a > 0:
        cnt += a % 2
        a //= 2
    print(cnt)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def segfunc(x,y):
    return x | y

def init(init_val):
    #set_val
    for i in range(n):
        seg[i+num-1]=init_val[i]
    #built
    for i in range(num-2,-1,-1) :
        seg[i]=segfunc(seg[2*i+1],seg[2*i+2])

def update(k,x):
    k += num-1
    seg[k] = x
    while k:
        k = (k-1)//2
        seg[k] = segfunc(seg[k*2+1],seg[k*2+2])

def query(p,q):
    if q<=p:
        return ide_ele
    p += num-1
    q += num-2
    res=ide_ele
    while q-p>1:
        if p&1 == 0:
            res = segfunc(res,seg[p])
        if q&1 == 1:
            res = segfunc(res,seg[q])
            q -= 1
        p = p//2
        q = (q-1)//2
    if p == q:
        res = segfunc(res,seg[p])
    else:
        res = segfunc(segfunc(res,seg[p]),seg[q])
    return res


n = int(input())
s = input()
q = int(input())

li = []
for i in range(n):
    li.append(1 << ord(s[i]) - ord('a'))

#####単位元######
ide_ele = 0

#num:n以上の最小の2のべき乗
num =2**(n-1).bit_length()
seg=[ide_ele]*2*num
init(li)

for _ in range(q):
    q1 = list(input().split())
    if q1[0] == '1':
        update(int(q1[1]) - 1, 1 << ord(q1[2]) - ord('a'))
    else:
        l,r = int(q1[1]), int(q1[2])
        print(bin(query(l-1,r)).count('1'))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4


def main():
    mod = 1000000007                  # 10^9+7
    inf = float('inf')
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():  return int(input())
    def mi():  return map(int, input().split())
    def mi_0(): return map(lambda x: int(x)-1, input().split())
    def lmi(): return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():  return list(input())

    # 各クエリでの O(|alphabet|) が重いため TLE
    # a...z までの出現フラグを bit field で管理することを考える。そうすればある区間での出現文字を管理する数字たちを合わせる際には OR をとるだけて O(1) で高速に処理できる


    class SegTree:
        def __init__(self, size):
            self.size = size
            self.n0 = 2 ** (size - 1).bit_length()
            self.table = [0 for _ in range(2 * self.n0)]
        
        def update(self, k, new_char):
            'update char in a_k to new_char'
            table_k = k + self.n0 - 1
            new_num = 1 << (ord(new_char) - ord('a'))
            if self.table[table_k] != new_num:
                self.table[table_k] = new_num
                while table_k // 2 > 0:
                    table_k //= 2
                    self.table[table_k] = self.table[2 * table_k] | self.table[2 * table_k + 1]
        
        def range_set(self, l, r):
            'return integer that represents character set appeared in a_l to a_r'
            bit_field = 0
            table_l = l + self.n0 - 1
            table_r = r + self.n0 - 1
            if table_l > table_r:
                raise RuntimeError("l should be less than or equals to r. got l:{} and r:{}".format(l, r))
            while table_l < table_r:
                if table_l & 0b1 == 1:
                    bit_field |= self.table[table_l]
                if table_r & 0b1 == 0:
                    bit_field |= self.table[table_r]
                table_l = (table_l + 1)  // 2
                table_r = (table_r - 1) // 2
            if table_l == table_r:
                bit_field |= self.table[table_l]
            return bit_field


    def execute_query(seg_tree, L, buf):
        id = int(L[0])
        if id == 1:
            i = int(L[1])
            char = L[2]
            seg_tree.update(i, char)
        else:
            i, j = map(int, L[1:])
            bit_field = seg_tree.range_set(i, j)
            buf.append(bin(bit_field)[2:].count('1'))

    n = ii()
    s = input()
    q = ii()
    commands = []
    for _ in range(q):
        commands.append(input().split())

    st = SegTree(n)
    for i, char in enumerate(s):
        st.update(i+1, char)
    
    buf = []
    for query in commands:
        execute_query(st, query, buf)
    for elm in buf:
        print(elm)


if __name__ == "__main__":
    main()