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:
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

class BIT:
    def __init__(self, n):
        self.n = n
        self.nums = [0] * (n+1)
        
    def add(self, i, x):
        n, nums = self.n, self.nums
        i += 1
        while i <= n:
            nums[i] += x
            i += i & -i
    
    def sum(self, i):
        nums = self.nums
        s = 0
        i += 1
        while i:
            s += nums[i]
            i -= i & -i
        return s
    
    def search(self, x):
        n, nums = self.n, self.nums
        s, p = 0, 0
        for i in range(n.bit_length(), -1, -1):
            np = p + (1<<i)
            if np <= n and s+nums[np] < x:
                s += nums[np]
                p = np
        return p


N = ri()
S = rs()
Q = ri()
queries = []
for i in range(Q):
	q = rs().split()
	if q[0] == '1':
		q = (int(q[0]), int(q[1])-1, q[2])
	else:
		q = (int(q[0]), int(q[1])-1, int(q[2])-1)
	queries.append(q)

import collections
h = collections.defaultdict(lambda: BIT(N))

S = list(S)
for i, s in enumerate(S):
	h[s].add(i, 1)
for q in queries:
	if q[0] == 1:
		i, c = q[1], q[2]
		h[S[i]].add(i, -1)
		h[c].add(i, 1)
		S[i] = c
	else:
		l, r = q[1], q[2]
		cnt = 0
		for c, bit in h.items():
			if bit.sum(r) - bit.sum(l-1) > 0:
				cnt += 1
		print(cnt)

Submission status: Accepted

Solution code:
import sys
# import re
import math
import collections
# import decimal
import bisect
import itertools
import fractions
# import functools
import copy
# import heapq
import decimal
# import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===
def main():
    n = ni()
    s = list(input())
    q = ni()

    alphabet_idx = {}
    for i in range(26):
        alphabet_idx[i] = []

    for i, si in enumerate(s):
        alphabet_idx[ord(si) - ord("a")].append(i)

    for _ in range(q):
        qi, a, b = input().split()
        qi, a = int(qi), int(a)

        if qi == 1:
            a -= 1
            if s[a] == b:
                continue
            del_char = ord(s[a]) - ord("a")
            del_idx = bisect.bisect_left(alphabet_idx[del_char], a)
            del alphabet_idx[del_char][del_idx]

            insert_char = ord(b) - ord("a")
            insert_idx = bisect.bisect_left(alphabet_idx[insert_char], a)
            alphabet_idx[insert_char].insert(insert_idx, a)

            s[a] = b

        if qi == 2:
            b = int(b)
            a -= 1
            b -= 1
            ans = 0

            for i in range(26):
                a_idx = bisect.bisect_left(alphabet_idx[i], a)
                if a_idx < len(alphabet_idx[i]):
                    if alphabet_idx[i][a_idx] <= b:
                        ans += 1

            print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
# import re
import math
import collections
# import decimal
import bisect
import itertools
import fractions
# import functools
import copy
# import heapq
import decimal
# import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===
def main():
    n = ni()
    s = list(input())
    q = ni()

    alphabet_idx = {}
    for i in range(26):
        alphabet_idx[i] = []

    for i, si in enumerate(s):
        alphabet_idx[ord(si) - ord("a")].append(i)

    for _ in range(q):
        qi, a, b = input().split()
        qi, a = int(qi), int(a)

        if qi == 1:
            a -= 1
            if s[a] == b:
                continue
            current_char = ord(s[a]) - ord("a")
            del_idx = bisect.bisect_left(alphabet_idx[current_char], a)
            del alphabet_idx[current_char][del_idx]

            insert_idx = bisect.bisect_left(alphabet_idx[ord(b) - ord("a")], a)
            alphabet_idx[ord(b) - ord("a")].insert(insert_idx, a)

            s[a] = b

        if qi == 2:
            b = int(b)
            a -= 1
            b -= 1
            ans = 0

            for i in range(26):
                a_idx = bisect.bisect_left(alphabet_idx[i], a)
                if a_idx < len(alphabet_idx[i]):
                    if alphabet_idx[i][a_idx] <= b:
                        ans += 1

            print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# セグメント木 最新バージョン
#verify
class SegTree():
    # 1-indexed
    def __init__(self, lists, function, basement):
        self.n = len(lists)
        self.K = (self.n-1).bit_length()
        self.f = function
        self.b = basement
        self.seg = [basement]*(2**(self.K+1)+1)
        X = 2**self.K
        for i, v in enumerate(lists):
            self.seg[i+X] = v
        for i in range(X-1, 0, -1):
            self.seg[i] = self.f(self.seg[i << 1], self.seg[i << 1 | 1])

    def update(self, k, value):
        X = 2**self.K
        k += X
        self.seg[k] = value
        while k:
            k = k >> 1
            self.seg[k] = self.f(self.seg[k << 1], self.seg[(k << 1) | 1])

    def query(self, L, R):
        num = 2**self.K
        L += num
        R += num
        vL = self.b
        vR = self.b
        while L < R:
            if L & 1:
                vL = self.f(vL, self.seg[L])
                L += 1
            if R & 1:
                R -= 1
                vR = self.f(self.seg[R], vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)

    def find_max_index(self, L, R, X):
        # [L,R)でX以下の物で最大indexを取得
        return self.fMi(L, R, X, 1, 0, 2**self.K)

    def find_min_index(self, L, R, X):
        # [L,R) でX以下の物で最小のindexを取得する
        return self.fmi(L, R, X, 1, 0, 2**self.K)

    def fMi(self, a, b, x, k, l, r):
        if self.seg[k] > x or r <= a or b <= l:
            return -1
        else:
            if k >= 2**self.K:
                return k-2**self.K
            else:
                vr = self.fMi(a, b, x, (k << 1) | 1, (l + r) // 2, r)
                if vr != -1:
                    return vr
                return self.fMi(a, b, x, k << 1, l, (l + r) // 2)

    def fmi(self, a, b, x, k, l, r):
        if self.seg[k] > x or r <= a or b <= l:
            return -1
        else:
            if k >= 2**self.K:
                return k-2**self.K
            else:
                vl = self.fmi(a, b, x, k << 1, l, (l+r)//2)
                if vl != -1:
                    return vl
                return self.fmi(a, b, x, k << 1 | 1, (l+r)//2, r)
N = int(input())
S = list(input())
Q = int(input())
que = [tuple(input().split()) for i in range(Q)]
alpha = "abcdefghijklmnopqrstuvwxyz"
Data = {alpha[i]: [0]*N for i in range(26)}
for i in range(N):
    Data[S[i]][i] += 1
SEG = {alpha[i]: SegTree(Data[alpha[i]], max, 0) for i in range(26)}
for X, u, v in que:
    if X == "1":
        u = int(u)-1
        NOW = S[u]
        S[u] = v
        SEG[NOW].update(u, 0)
        SEG[v].update(u,1)
    else:
        s, t = int(u)-1, int(v)-1
        res = 0
        for j in range(26):
            res += SEG[alpha[j]].query(s, t+1)
        print(res)

Submission status: Accepted

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

def solve():
    N = int(input())
    S = list(input())
    Q = int(input())
    set_dic = {}

    for i, s in enumerate(S):
        if s not in set_dic:
            set_dic[s] = [i+1]
        else:
            bisect.insort_left(set_dic[s], i+1)

    anslist = []

    for _ in range(Q):
        query1, query2, query3 = input().split()
        if query1 == "1":
            i = int(query2)
            c = query3
            cap = S[i-1]
            if cap == c:
                continue
            set_dic[cap].remove(i)
            if c not in set_dic:
                set_dic[c] = [i]
            else:
                bisect.insort_left(set_dic[c], i)
            S[i-1] = c
        else:
            l = int(query2)
            r = int(query3)
            ansset = set()
            ans = 0
            for eachlist in set_dic.values():
                li = bisect.bisect_left(eachlist, l)
                ri = bisect.bisect_right(eachlist, r)
                if li != ri:
                    ans += 1
            anslist.append(ans)

    for i in anslist:
        print(i)

if __name__ == '__main__':
    solve()

Submission status: Accepted

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


class SegTree():
    # ここでは操作の都合上根元のindexを1とする
    def __init__(self, lists, function, basement):
        self.n = len(lists)
        self.K = (self.n-1).bit_length()
        self.f = function
        self.b = basement
        self.seg = [basement]*2**(self.K+1)
        X = 2**self.K
        for i, v in enumerate(lists):
            self.seg[i+X] = v
        for i in range(X-1, 0, -1):
            self.seg[i] = self.f(self.seg[i << 1], self.seg[i << 1 | 1])

    def update(self, k, value):
        X = 2**self.K
        k += X
        self.seg[k] = value
        while k:
            k = k >> 1
            self.seg[k] = self.f(self.seg[k << 1], self.seg[(k << 1) | 1])

    def query(self, L, R):
        num = 2**self.K
        L += num
        R += num
        vL = self.b
        vR = self.b
        while L < R:
            if L & 1:
                vL = self.f(vL, self.seg[L])
                L += 1
            if R & 1:
                R -= 1
                vR = self.f(self.seg[R], vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)


def main():
    N = int(input())
    S = list(input())
    Q = int(input())
    que = [tuple(input().split()) for i in range(Q)]
    alpha = "abcdefghijklmnopqrstuvwxyz"
    Data = {alpha[i]: [0]*N for i in range(26)}
    for i in range(N):
        Data[S[i]][i] += 1
    SEG = {alpha[i]: SegTree(Data[alpha[i]], max, 0) for i in range(26)}
    for X, u, v in que:
        if X == "1":
            u = int(u)-1
            NOW = S[u]
            S[u] = v
            SEG[NOW].update(u, 0)
            SEG[v].update(u, 1)
        else:
            u, v = int(u)-1, int(v)-1
            res = 0
            for j in range(26):
                res += SEG[alpha[j]].query(u, v+1)
            print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys


class SegTree():
    def __init__(self, lists, function, basement):
        self.n = len(lists)
        self.K = (self.n-1).bit_length()
        self.f = function
        self.b = basement
        self.seg = [basement]*2**(self.K+1)
        X = 2**self.K
        for i, v in enumerate(lists):
            self.seg[i+X-1] = v

        for i in range(2*X-2, 0, -2):
            self.seg[(i-1) >> 1] = self.f(self.seg[i], self.seg[i-1])

    def update(self, k, value):
        X = 2**self.K
        k += X-1
        self.seg[k] = value
        while k:
            k = (k-1) >> 1
            self.seg[k] = self.f(self.seg[(k << 1)+1], self.seg[(k << 1)+2])

    def query(self, L, R):
        num = 2**self.K-1
        L += num
        R += num
        vL = self.b
        vR = self.b
        while L < R:
            if L & 1 == 0:
                vL = self.f(vL, self.seg[L])
                L += 1
            if R & 1 == 0:
                R -= 1
                vR = self.f(self.seg[R], vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)


input = sys.stdin.readline


def main():
    N = int(input())
    S = list(input())
    Q = int(input())
    que = [tuple(input().split()) for i in range(Q)]
    alpha = "abcdefghijklmnopqrstuvwxyz"
    Data = {alpha[i]: [0]*N for i in range(26)}
    for i in range(N):
        Data[S[i]][i] += 1
    SEG = {alpha[i]: SegTree(Data[alpha[i]], max, 0) for i in range(26)}
    for X, u, v in que:
        if X == "1":
            u = int(u)-1
            NOW = S[u]
            S[u] = v
            SEG[NOW].update(u, 0)
            SEG[v].update(u, 1)
        else:
            u, v = int(u)-1, int(v)-1
            res = 0
            for j in range(26):
                res += SEG[alpha[j]].query(u, v+1)
            print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
class SegTree():
    def __init__(self, lists, function, basement):
        self.n = len(lists)
        self.K = (self.n-1).bit_length()
        self.f = function
        self.b = basement
        self.seg = [basement]*2**(self.K+1)
        self.lazy_seg = [basement]*2**(self.K+1)
        X = 2**self.K
        for i, v in enumerate(lists):
            self.seg[i+X-1] = v

        for i in range(2*X-2, 0, -2):
            self.seg[(i-1) >> 1] = self.f(self.seg[i], self.seg[i-1])

    def update(self, k, value):
        # 0-indexでa[k]の値をvalueに変更
        X = 2**self.K
        k += X-1
        self.seg[k] = value
        while k:
            k = (k-1) >> 1
            self.seg[k] = self.f(self.seg[(k << 1)+1], self.seg[(k << 1)+2])


    def query(self, L, R):
        # 0-index で[L,R)
        num = 2**self.K-1
        L += num
        R += num
        vL = self.b
        vR = self.b
        while L < R:
            if L & 1 == 0:
                vL = self.f(vL, self.seg[L])
                L += 1
            if R & 1 == 0:
                R -= 1
                vR = self.f(self.seg[R], vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)

import sys
input=sys.stdin.readline
N=int(input())
S=list(input())
Q=int(input())
que=[tuple(input().split()) for i in range(Q)]
alpha="abcdefghijklmnopqrstuvwxyz"
Data={alpha[i]:[0]*N for i in range(26)}
for i in range(N):
    Data[S[i]][i]+=1
SEG={alpha[i]:SegTree(Data[alpha[i]],max,0) for i in range(26)}
for X,u,v in que:
    if X=="1":
        u=int(u)-1
        NOW=S[u]
        S[u]=v
        SEG[NOW].update(u,0)
        SEG[v].update(u,1)
    else:
        u,v=int(u)-1,int(v)-1
        res=0
        for j in range(26):
            res+=SEG[alpha[j]].query(u,v+1)
        print(res)

Submission status: Accepted

Solution code:
class SegTree():
    def __init__(self, lists, function, basement):
        self.n = len(lists)
        self.K = (self.n-1).bit_length()
        self.func = function
        self.basement = basement
        self.seg = [basement]*(2**(self.K+1))
        X=2**self.K
        for i,v in enumerate(lists):
            self.seg[i+X-1] = v

        for i in range(2*X-2, 0, -2):
            self.seg[(i-1)>>1] = self.func(self.seg[i], self.seg[i-1])

    def update(self, k, value):

        X=2**self.K
        k += X-1
        self.seg[k] = value
        while k:
            k = (k-1)>>1
            self.seg[k] = self.func(self.seg[(k<<1)+1], self.seg[(k<<1)+2])

            

    def query(self, p, q):
        if q <= p:
            return self.basement
        num = 2**self.K
        p += num-1
        q += num-2
        res = self.basement
        while q-p > 1:
            if p & 1 == 0:
                res = self.func(res, self.seg[p])
            if q & 1 == 1:
                res = self.func(res, self.seg[q])
                q -= 1
            p = p>>1
            q = (q-1)>>1
        if p == q:
            res = self.func(res, self.seg[p])
        else:
            res = self.func(self.func(res, self.seg[p]), self.seg[q])
        return res

import sys
input=sys.stdin.readline

N=int(input())
S=list(input())
Q=int(input())
que=[tuple(input().split()) for i in range(Q)]
alpha="abcdefghijklmnopqrstuvwxyz"
Data={alpha[i]:[0]*N for i in range(26)}
for i in range(N):
    Data[S[i]][i]+=1
SEG={alpha[i]:SegTree(Data[alpha[i]],max,0) for i in range(26)}
for X,u,v in que:
    if X=="1":
        u=int(u)-1
        NOW=S[u]
        S[u]=v
        SEG[NOW].update(u,0)
        SEG[v].update(u,1)
    else:
        u,v=int(u)-1,int(v)-1
        res=0
        for j in range(26):
            res+=SEG[alpha[j]].query(u,v+1)
        print(res)

Submission status: Accepted

Solution code:
class SegTree():
    def __init__(self, lists, function, basement):
        self.n = len(lists)
        self.K = (self.n-1).bit_length()
        self.func = function
        self.basement = basement
        self.seg = [basement]*2**(self.K+1)
        self.lazy_seg = [basement]*2**(self.K+1)
        X=2**self.K
        for i,v in enumerate(lists):
            self.seg[i+X-1] = v

        for i in range(2*X-2, 0, -2):
            self.seg[(i-1)>>1] = self.func(self.seg[i], self.seg[i-1])

    def update(self, k, value):
        # 0-indexでa[k]の値をvalueに変更
        X=2**self.K
        k += X-1
        self.seg[k] = value
        while k:
            k = (k-1)>>1
            self.seg[k] = self.func(self.seg[(k<<1)+1], self.seg[(k<<1)+2])

            

    def query(self, p, q):
        # 0-indexで[p,q)の値を取得する
        if q <= p:
            return self.basement
        num = 2**self.K
        p += num-1
        q += num-2
        res = self.basement
        while q-p > 1:
            if p & 1 == 0:
                res = self.func(res, self.seg[p])
            if q & 1 == 1:
                res = self.func(res, self.seg[q])
                q -= 1
            p = p>>1
            q = (q-1)>>1
        if p == q:
            res = self.func(res, self.seg[p])
        else:
            res = self.func(self.func(res, self.seg[p]), self.seg[q])
        return res

import sys
input=sys.stdin.readline
N=int(input())
S=list(input())
Q=int(input())
que=[tuple(input().split()) for i in range(Q)]
alpha="abcdefghijklmnopqrstuvwxyz"
Data={alpha[i]:[0]*N for i in range(26)}
for i in range(N):
    Data[S[i]][i]+=1
SEG={alpha[i]:SegTree(Data[alpha[i]],max,0) for i in range(26)}
for X,u,v in que:
    if X=="1":
        u=int(u)-1
        NOW=S[u]
        S[u]=v
        SEG[NOW].update(u,0)
        SEG[v].update(u,1)
    else:
        u,v=int(u)-1,int(v)-1
        res=0
        for j in range(26):
            res+=SEG[alpha[j]].query(u,v+1)
        print(res)

Submission status: Accepted

Solution code:
class SegmentTree():
    """A segment Tree.

    This is a segment tree without recursions.
    This can support queries as follows:
     - update a single value in O(logN).
     - get the folded value of values in a segment [l, r) in O(logN)
    N is the length of the given iterable value.

    Parameters
    ----------
    iterable : Iterable[_T]
        An iterable value which will be converted into a segment tree
    func : Callable[[_T, _T], _T]
        A binary function which returns the same type as given two.
        This has to satisfy the associative law:
            func(a, func(b, c)) = func(func(a, b), c)
    e : _T
        The identity element of the given func.
        In other words, this satisfies:
            func(x, e) = func(e, x) = x
    """
    
    def __init__(self, iterable, func, e):
        self.func = func
        self.e = e

        ls = list(iterable)
        self.n = 1 << len(ls).bit_length()
        ls.extend( [self.e] * (self.n - len(ls)) )

        self.data = [self.e] * self.n + ls
        for i in range(self.n-1, 0, -1):
            self.data[i] = self.func(self.data[2*i], self.data[2*i+1])

    def replace(self, index, value):
        """replace the old value of the given index with the given new value.

        This replaces the old value of the given index with the given new value in O(logN).
        This is like "list[index] = value".

        Parameters
        ----------
        index : int
            The index of the value which will be replaced.
        value : _T
            The new value with which the old value will be replaced.
        """
        index += self.n
        self.data[index] = value
        index //= 2
        while index > 0:
            self.data[index] = self.func(self.data[2*index], self.data[2*index+1])
            index //= 2
        
    def folded(self, l, r):
        """get the folded value of values in a segment [l, r).

        This get the folded value of values in a segment [l, r) in O(logN).
        If func is add, it returns the sum of values in [l, r).
        In other words, this is eqivalent to "sum(list[l:r])".
        If func is other functions, then this is equivalent to "accumulate(list[l:r], func)".

        Parameters
        ----------
        l : int
            The left edge.
        r : int
            The right edge.

        Returns
        -------
        _T(the same type as the type of the element of the given iterable)
            This is equivalent to func(list[l], func(list[l+1], ... ) ).
            If func is represented as '*', then it's:
            list[l] * list[l+1] * ... * list[r-1] 
        """

        left_folded = self.e
        right_folded = self.e
        l += self.n
        r += self.n
        while l < r:
            if l % 2:
                left_folded = self.func(left_folded, self.data[l])
                l += 1
            if r % 2:
                r -= 1
                right_folded = self.func(self.data[r], right_folded)
            l //= 2
            r //= 2
        
        return self.func(left_folded, right_folded)


from operator import or_

N = int(input())
S = input()

ls = [1 << (ord(c) - ord('a')) for c in S]
segtree = SegmentTree(ls, or_, 0)

Q = int(input())
for _ in range(Q):
    s = input()
    if s[0] == '1':
        i, c = s[2:].split()
        segtree.replace(int(i)-1, 1 << (ord(c) - ord('a')))
    else:
        l, r = map(int, s[2:].split())
        value = segtree.folded(l-1, r)
        print(format(value, 'b').count('1'))

Submission status: Accepted

Solution code:
import sys

input = lambda: sys.stdin.readline().rstrip()


class SegTree:

    def __init__(self, init_val, segfunc, ide_ele):

        n = len(init_val)
        self.ide_ele = ide_ele
        self.segfunc = segfunc
        self.num = 2**(n - 1).bit_length()
        self.seg = [self.ide_ele] * 2 * self.num

        for i in range(n):
            self.seg[i + self.num - 1] = init_val[i]

        for i in range(self.num - 2, -1, -1):
            self.seg[i] = self.segfunc(self.seg[2 * i + 1], self.seg[2 * i + 2])

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

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


def solve():

    N = int(input())
    S = list(input())
    Q = int(input())
    seg = [1 << (ord(s) - ord('a')) for s in S]

    segtree = []
    segfunc = lambda a, b: a | b

    segtree = SegTree(seg, segfunc, 0)

    ans = []
    for i in range(Q):
        a, b, c = input().split()
        a = int(a)

        if a == 1:
            b = int(b) - 1
            al = ord(c) - ord('a')
            segtree.update(b, 1 << al)
        elif a == 2:
            b, c = int(b) - 1, int(c)
            res = segtree.query(b, c)
            res = sum(list(map(int, bin(res)[2:])))
            ans.append(res)

    print('\n'.join(map(str, ans)))


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from bisect import bisect_left
import string 

dic={c:[] for c in string.ascii_lowercase}
N=int(input())
S=list(input())
Q=int(input())
for i in range(len(S)):
  dic[S[i]].append(i+1)

for i in range(Q):
  a,b,c=map(str,input().split())
  if a=='1':
    if S[int(b)-1]==c:
      continue
    b=int(b)
    f=S[b-1]
    d=bisect_left(dic[f],b)
    e=bisect_left(dic[c],b)
    dic[f].pop(d)
    dic[c].insert(e,b)
    S[b-1]=c
  else:
    ans=0
    b,c=int(b),int(c)
    for j in string.ascii_lowercase:
      d=bisect_left(dic[j],b)
      if d<len(dic[j]):
        if dic[j][d]<=c:
          ans+=1
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left,bisect_right
import string 

dic = {c:[] for c in string.ascii_lowercase}

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

for i,c in enumerate(s,start=1):
  dic[c].append(i)
  
for i in range(q):
  p,l,r = map(str,input().split())
  if p =='1':
    j = int(l)
    if r == s[j-1]:
      continue
    c = s[j-1]    
    dic[c].pop(bisect_left(dic[c],j))
    dic[r].insert(bisect_left(dic[r],j),j)
    s[j-1] = r
  else:
    ans = 0
    l = int(l)
    r = int(r)
    for c in string.ascii_lowercase:
      pl = bisect_left(dic[c],l)
      if pl < len(dic[c]):
        if dic[c][pl] <= r:
          ans += 1
    print(ans)

Submission status: Accepted

Solution code:
from sys import stdin

class SegmentTree:
    # 初期化処理
    # f : SegmentTreeにのせるモノイド
    # default : fに対する単位元
    def __init__(self, size, f=lambda x,y : x+y, default=0):
        self.size = 2**(size-1).bit_length() # 簡単のため要素数Nを2冪にする
        self.default = default
        self.dat = [default]*(self.size*2) # 要素を単位元で初期化
        self.f = f

    def update(self, i, x):
        i += self.size
        self.dat[i] = x
        while i > 0:
            i >>= 1
            self.dat[i] = self.f(self.dat[i*2], self.dat[i*2+1])

    def query(self, l, r):
        l += self.size
        r += self.size
        lres, rres = self.default, self.default
        while l < r:
            if l & 1:
                lres = self.f(lres, self.dat[l])
                l += 1

            if r & 1:
                r -= 1
                rres = self.f(self.dat[r], rres) # モノイドでは可換律は保証されていないので演算の方向に注意
            l >>= 1
            r >>= 1
        res = self.f(lres, rres)
        return res
def bc(x):
    return bin(x).count("1")

n = int(stdin.readline().rstrip())
s = stdin.readline().rstrip()
q = int(stdin.readline().rstrip())

lamb_or = lambda x,y : x|y
seg = SegmentTree(n,lamb_or,0)

for i,x in enumerate(s):
    seg.update(i,1 << ord(x)-97)

for _ in range(q):
    c,x,y = [x for x in stdin.readline().rstrip().split()]
    if c == '1':
        x = int(x)
        seg.update(x-1,1 << ord(y)-97)
    elif c == '2':
        x = int(x)
        y = int(y)
        print(bc(seg.query(x-1,y)))

Submission status: Accepted

Solution code:
n = int(input())
stmp = list(input())
Q = int(input())
target = ord("a")
s = [ord(stmp[i])-target for i in range(n)]

class BIT:
	"""
	<Attention> 0-indexed.
	query ... return the sum [0 to m]
	sum ... return the sum [a to b]
	sumall ... return the sum [all]
	add ... 'add' number to element (be careful that it doesn't set a value.)
	search ... the sum version of bisect.right
	output ... return the n-th element
	listout ... return the BIT list
	"""
	
	def query(self, m):
		res = 0
		while m > 0:
			res += self.bit[m]
			m -= m&(-m)
		return res
	
	def sum(self, a, b):
		return self.query(b)-self.query(a)
	
	def sumall(self):
		bitlen = self.bitlen-1
		return self.query(bitlen)
	
	def add(self, m, x):
		m += 1
		bitlen = len(self.bit)
		while m <= bitlen-1:
			self.bit[m] += x
			m += m&(-m)
		return
	
	def __init__(self, n):
		self.bitlen = n+1
		self.bit = [0]*(n+1)

b = [BIT(n) for i in range(26)]
for i in range(n):
	b[s[i]].add(i, 1)

for _ in range(Q):
	q,qtmpa,qtmpb = input().split()
	if q[0] == "1":
		qa = int(qtmpa)
		t = ord(qtmpb)-target
		b[t].add(qa-1, 1)
		b[s[qa-1]].add(qa-1, -1)
		s[qa-1] = t
	else:
		ans = 0
		qta = int(qtmpa)
		qtb = int(qtmpb)
		for i in range(26):
			if b[i].sum(qta-1, qtb) != 0:
				ans += 1
		print(ans)

Submission status: Accepted

Solution code:
class segtree:
    def __init__(self,N):
        self.n=(1<<len(bin(N-1)[2:]))
        self.x=[0 for _ in range(2*self.n)]
    def build(self,seq):
        for i, j in enumerate(seq, start=self.n):
            self.x[i]=1<<j
        for i in range(self.n-1, 0, -1):
            self.x[i]=self.x[i*2]|self.x[i*2+1]
    def update(self, i, c):
        j=i+self.n
        self.x[j]=1<<c
        while j>1:
            j//=2
            self.x[j]=self.x[j*2]|self.x[j*2+1]
    def get(self,l,r):
        ans=0
        l+=self.n
        r+=self.n
        while l<r:
            if l%2==1:
                ans|=self.x[l]
                l+=1
            if r%2==0:
                ans|=self.x[r]
                r-=1
            l//=2
            r//=2
        if l==r:
            ans|=self.x[l]
        cnt=sum(list(map(int, list(bin(ans)[2:]))))
        print(cnt)
        
n=int(input())
s=list(input())
s=[ord(i)-97 for i in s]
seg=segtree(n)
seg.build(s)
#print(seg.x)
for _ in range(int(input())):
    que=list(input().split())
    if que[0]=='1':
        seg.update(int(que[1])-1, ord(que[2])-97)
    elif que[0]=='2':
        seg.get(int(que[1])-1,int(que[2])-1)