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:
# coding: utf-8
import sys
from bisect import bisect_left, bisect_right, insort_left
from collections import defaultdict

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 各アルファベットのindexのリストを作り,bisect_left()
N = ir()
S = list(sr())
dic = defaultdict(list)
for i, s in enumerate(S):
    dic[s].append(i)

Q = ir()
for _ in range(Q):
    a, b, c = sr().split()
    if a == '1':
        b = int(b) - 1
        if S[b] == c:
            continue
        dic[S[b]].remove(b)
        insort_left(dic[c], b)
        S[b] = c
    else:
        b = int(b) - 1; c = int(c) - 1
        kind = 0
        for x in range(26):
            word = chr(ord('a')+x)
            if len(dic[word]) == 0:
                continue
            i = bisect_left(dic[word], b)
            j = bisect_right(dic[word], c)
            if i != j:
                kind += 1
        print(kind)

# 07

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6) #再帰関数の上限
import math
from copy import copy, deepcopy
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque 
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする

def input(): return sys.stdin.readline()[:-1]
def printl(li): print(*li, sep="\n")
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds

class segtree():#seg=segtree(A),単位元とsegfuncを指定すること
    def __init__(self,A,ide=0):#単位元とsegfuncを指定すること
        n=len(A)
        num=2**(n-1).bit_length()#n以上の最小の2のべき乗
        seg=[ide]*(2*num-1)
        segfunc=self.segfunc
        self.ide,self.n,self.num,self.seg = ide, n, num, seg
        for i in range(n): seg[i+num-1]=A[i]#setvalue
        for i in range(num-2,-1,-1):seg[i]=segfunc(seg[2*i+1],seg[2*i+2])#build
    
    def segfunc(self,x,y):return x|y #seg木の基本関数
    
    def update(self,k,x):#Aのk番目の要素をxに置き換える,計算量log(N)
        k += self.num-1
        seg,segfunc=self.seg,self.segfunc
        seg[k] = x
        while k:
            k = (k-1)//2
            seg[k] = segfunc(seg[k*2+1],seg[k*2+2])
    
    def query(self,p,q):#区間[p,q)の累積segfuncを求める,計算量log(N)
        if q<=p: return self.ide
        num,segfunc,seg=self.num,self.segfunc,self.seg
        p += num-1; q += num-2
        res=self.ide
        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,q = p//2, (q-1)//2
        if p == q: res = segfunc(res,seg[p])
        else: res = segfunc(segfunc(res,seg[p]),seg[q])
        return res 

def main():
    mod = 10**9+7
    alpha2num = lambda c: 2**(ord(c) - ord('a'))
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    S=input()
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    A=list(map(alpha2num, list(S)))
    #print(A)
    #exit()
    seg=segtree(A)
    #print(A)
    Q=int(input())
    for i in range(Q):
        t, a,b =input().split()
        if t=='1':
            a=int(a)
            seg.update(a-1,alpha2num(b))
        else:
            a,b=int(a),int(b)
            x=seg.query(a-1,b)
            count=0
            for i in range(26):
                count+= (x>>i & 1)
            print(count)






if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#segtree ライブラリ
#BITライブラリの作成
#リストの要素を1,0で長さをｎとした時に使える
class BIT:
    def __init__(self,n):
        self.n=n
        self.data=[0]*(n+1)
    def to_sum(self,i):
        s=0     
        while i>0:
            s+=self.data[i]
            i-=(i& -i)
        return s
    def add(self,i,x):
        while i<=self.n:
            self.data[i]+=x
            i+=(i & -i)
    def get(self,i,j):
        return self.to_sum(j)-self.to_sum(i-1)
n=int(input())
s=list(input())
q=int(input())
que=[]

for i in range(q):
    p=list(input().split())
    que.append(p)
alpha="abcdefghijklmnopqrstuvwxyz"
segtree={alpha[i]:BIT(n) for i in range(26)}  
for i in range(n):
    segtree[s[i]].add(i+1,1)
for q in que:
    x,y,z=q[0],q[1],q[2]
    if int(x)==1:
        #y文字目をzに変更する
        y=int(y)  
        for i in range(26):
            if segtree[alpha[i]].get(y,y)==1:
                segtree[alpha[i]].add(y,-1)
                break
        segtree[z].add(y,1)
    else:
        ans=0
        for i in range(26):
            if segtree[alpha[i]].get(int(y),int(z))>0:
                ans+=1
        print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    #inf = 10**17
    #mod = 10**9 + 7

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

    def init(arr):
        for i in range(n):
            seg[i+num-1] = {arr[i]}
        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].clear()
        seg[k] = {x}
        while k:
            k = (k-1)//2
            seg[k].clear()
            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 = list(input().rstrip())
    for i in range(n):
        s[i] = ord(s[i]) - 97

    ide_ele = set()

    num =2**((n-1).bit_length())

    # セグ木初期化
    seg=[ide_ele]*2*num
    init(s)

    q = int(input())
    for _ in range(q):
        a,b,c = input().rstrip().split()
        if a == '1':
            b = int(b)
            c = ord(c) - 97
            update(b-1, c)
        else:
            b = int(b)
            c = int(c)
            print(len(query(b-1, c)))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

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


def enc(a):
    return ord(a) - ord('a')


N = int(input())
S = input()
bits = [Bit(N) for i in range(26)]

for i, s in enumerate(S):
    bits[enc(s)].add(i + 1, 1)


for _ in range(int(input())):
    t, l, r = input().split(" ")
    if t == '1':
        i = int(l)
        before = -1
        for before in range(26):
            if bits[before].sum(i) - bits[before].sum(i - 1) == 1:
                break
        after = enc(r)
        bits[before].add(i, -1)
        bits[after].add(i, 1)
    else:
        l, r = map(int, [l, r])
        ans = 0
        for c in range(26):
            if bits[c].sum(r) - bits[c].sum(l - 1) > 0:
                ans += 1
        print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
#from heapq import heappop, heappush
from collections import defaultdict
#from itertools import combinations
sys.setrecursionlimit(10**7)
import math
class SegTree():
    '''
    input idx: 1-
    '''
    def __init__(self, n, init_val=0):
        self.n = n
        self.init_val = init_val
        self.n_leaf = 2 ** math.ceil(math.log2(n))
        self.bins = [init_val] * (self.n_leaf * 2)

    def val_append(self, A):
        '''
        :param A:
        :return:
        '''
        if len(A) != self.n:
            raise ValueError('The number of input should be same with n_leaf')
        for i,a in enumerate(A):
            self.bins[self.n_leaf+i]=a
        self._calc()
        return None

    def _calc(self):
        '''
        Calculate all bins based on values of leaves
        '''
        i = self.n_leaf - 1
        while i > 0:
            self.bins[i] = self._criteria(self.bins[i*2], self.bins[i*2+1])
            i -= 1
        return None

    def _criteria(self, x, y):
        '''
        Define criteria between 2 nodes
        '''
        return x | y

    def eval_between(self, x, y):
        '''
        x, y : node-idx(1-)
        '''
        l, r = x + self.n_leaf - 1, y + self.n_leaf - 1
        ret = self._criteria(self.bins[l], self.bins[r])
        while l < r:
            if l % 2 == 1:
                ret = self._criteria(self.bins[l], ret)
                l += 1
                continue

            if r % 2 == 0:
                ret = self._criteria(self.bins[r], ret)
                r -= 1
                continue
            l = l//2
            r = r//2
            ret = self._criteria(self.bins[l], ret)
            ret = self._criteria(self.bins[r], ret)

        return ret

    def update(self, node, pro):
        '''
        Replacement of the value in a leaf
        '''
        current = node + self.n_leaf - 1
        self.bins[current] = pro
        current //= 2
        while current > 0:
            self.bins[current] = self._criteria(self.bins[current*2+1], self.bins[current*2])
            current //= 2
        return None

def run():
    N = int(input())
    S = list(input())
    Q = int(input())
    queries = [sysread().split() for _ in range(Q)]

    bins = [0] * N# a: ord('a') - 97
    for i,s in enumerate(S):
        id = ord(s) - 97
        bins[i] = 1<<id

    segtree = SegTree(N)
    segtree.val_append(bins)

    for type, i,c in queries:
        if type == '1':
            c = 1 << (ord(c) - 97)
            segtree.update(int(i), c)
        else:
            i,c = int(i), int(c)
            tmp = segtree.eval_between(i,c)
            print(bin(tmp).count('1'))

if __name__ == "__main__":
    run()

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right, insort_left

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

d = {}
flag = {}
for i in list('abcdefghijklmnopqrstuvwxyz'):
	d.setdefault(i, []).append(-1)
	flag.setdefault(i, []).append(-1)
for i in range(n):
	d.setdefault(s[i], []).append(i)
for i in range(q):
	q1,q2,q3 = map(str,input().split())
	if q1 == '1':
		q2 = int(q2) - 1
		if s[q2] != q3:
			insort_left(flag[s[q2]],q2)
			insort_left(d[q3],q2)
			s[q2] = q3
	else:
		ans = 0
		q2 = int(q2) - 1
		q3 = int(q3) - 1
		if q2 == q3:
			print(1)
			continue
		for string,l in d.items():
			res = 0
			if d[string] != [-1]:
				left = bisect_left(l,q2)
				right = bisect_right(l,q3)
			else:
				left = 0
				right = 0
			if string in flag:
				left2 = bisect_left(flag[string],q2)
				right2 = bisect_right(flag[string],q3)
			else:
				left2 = 0
				right2 = 0
			if left != right:
				if right - left > right2 - left2:
					res = 1
			ans += res
			#print(string,l,res)
		print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right, insort_left
import sys
readlines = sys.stdin.readline
def main():

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

	d = {}
	flag = {}
	for i in list('abcdefghijklmnopqrstuvwxyz'):
		d.setdefault(i, []).append(-1)
		flag.setdefault(i, []).append(-1)
	for i in range(n):
		d.setdefault(s[i], []).append(i)
	for i in range(q):
		q1,q2,q3 = map(str,input().split())
		if q1 == '1':
			q2 = int(q2) - 1
			if s[q2] != q3:
				insort_left(flag[s[q2]],q2)
				insort_left(d[q3],q2)
				s[q2] = q3
		else:
			ans = 0
			q2 = int(q2) - 1
			q3 = int(q3) - 1
			if q2 == q3:
				print(1)
				continue
			for string,l in d.items():
				res = 0
				if d[string] != [-1]:
					left = bisect_left(l,q2)
					right = bisect_right(l,q3)
				else:
					left = 0
					right = 0
				if string in flag:
					left2 = bisect_left(flag[string],q2)
					right2 = bisect_right(flag[string],q3)
				else:
					left2 = 0
					right2 = 0
				if left != right:
					if right - left > right2 - left2:
						res = 1
				ans += res
				#print(string,l,res)
			print(ans)
if __name__ == '__main__':
	main()

Submission status: Accepted

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

    def total(self, i):
        res = 0
        while i:
            res += self.data[i]
            i -= i & -i
        return res

    def add(self, i, val):
        while i <= self.n:
            self.data[i] += val
            i += i & -i


N = int(input())
bit = BIT(N)
for i, c in enumerate(input()):
    ind = ord(c) - ord("a")
    bit.add(i + 1, 1 << (ind * 20))
Q = int(input())
for _ in range(Q):
    parts = input().split()
    if parts[0] == "1":
        ind = int(parts[1])
        nval = 1 << ((ord(parts[2]) - ord("a")) * 20)
        val = bit.total(ind) - bit.total(ind - 1)
        bit.add(ind, nval - val)
    else:
        l, r = map(int, parts[1:])
        val = bit.total(r) - bit.total(l - 1)
        mask = (1 << 20) - 1
        ans = 0
        while val:
            if val & mask:
                ans += 1
            val >>= 20
        print(ans)

Submission status: Accepted

Solution code:
import sys
import bisect
input = sys.stdin.readline
sys.setrecursionlimit(10**6)


def main():

    n = int(input())
    s = list(input().strip())
    q = int(input())
    alpha = g = [[] for _ in range(26)]
    orda = ord('a')
    for i in range(n):
        alpha[ord(s[i])-orda].append(i)
    for i in range(q):
        a, b, c = map(str, input().split())
        if a == '1':
            b = int(b)-1
            if c != s[b]:
                alpha[ord(s[b])-orda].remove(b)
                s[b] = c
                bisect.insort(alpha[ord(c)-orda], b)
        else:
            ans = 0
            for i in range(26):
                if len(alpha[i]) > 0:
                    it = bisect.bisect_left(alpha[i], int(b)-1)
                    if it < len(alpha[i]) and alpha[i][it] < int(c):
                        ans += 1
            print(ans)


main()

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left, bisect_right, insort

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
S = list('-' + sr())
d = [[] for _ in range(26)]
for i in range(1, N+1):
    s = S[i]
    o = ord(s) - ord('a')
    insort(d[o], i)

Q = ir()
for _ in range(Q):
    q, a, b = sr().split()
    if q == '1':
        a = int(a)
        if S[a] == b:
            continue
        prev = ord(S[a]) - ord('a')
        d[prev].pop(bisect_left(d[prev], a))
        next = ord(b) - ord('a')
        insort(d[next], a)
        S[a] = b
    else:
        a = int(a); b = int(b)
        ans = 0
        for alpha in range(26):
            if bisect_right(d[alpha], b) - bisect_left(d[alpha], a) >= 1:
                ans += 1
        print(ans)

# 17

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left, bisect_right, insort

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
S = list('-' + sr())
d = [[] for _ in range(26)]
for i in range(1, N+1):
    s = S[i]
    o = ord(s) - ord('a')
    insort(d[o], i)

Q = ir()
for _ in range(Q):
    q, a, b = sr().split()
    if q == '1':
        a = int(a)
        if S[a] == b:
            continue
        prev = ord(S[a]) - ord('a')
        d[prev].pop(bisect_left(d[prev], a))
        next = ord(b) - ord('a')
        insort(d[next], a)
        S[a] = b
    else:
        a = int(a); b = int(b)
        ans = 0
        for alpha in range(26):
            if bisect_right(d[alpha], b) - bisect_left(d[alpha], a) >= 1:
                ans += 1
        print(ans)

Submission status: Accepted

Solution code:
#ABC157-E Simple String Queries
"""
英小文字26字が含まれるか否かを、2**26のint型で管理するセグ木。
これをbitwise-segment treeと言うらしい。
解法：
葉はその英小文字のbitで管理する。
segfuncにはx|yを登録することで、区間クエリをとった時に
2進数表記で1が出てくる回数が答えになる。
"""
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

#input
n = int(readline())
s = readline().rstrip().decode('utf-8')
lst1 = [0]*n
kijun = ord("a")
for i in range(n):
    res = ord(s[i])-kijun
    lst1[i] = 1<<res #A:1,B:10,C:100,D:1000

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

def init(init_val): #渡されたリストでsegを初期化
    #set_val
    for i in range(len(init_val)):
        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): #segの要素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): #区間[p,q)での、segfuncに準じた値を返す
    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

#####単位元######
"""
最小値のセグ木 → 10**9　(最小値の更新に影響しないため)
　　和のセグ木 → 0　(上の単位元の説明を参照)
　　積のセグ木 → 1　(上の単位元の説明を参照)
　　gcdのセグ木 → 0　(gcdを更新しない値は0)
"""
ide_ele = 0

#num:n以上の最小の2のべき乗
num =2**(n-1).bit_length()
seg=[ide_ele]*2*num #単位元の配列(計算結果に影響を及ぼさない配列)を作成

init(lst1)

#query
q = int(readline())
for i in range(q):
    kind,a,b = readline().rstrip().decode('utf-8').split()

    if kind == "1": #a文字目をbに変更
        res = ord(b)-kijun
        update(int(a)-1,1<<res)

    else: #[a,b]の区間に含まれる文字の種類を出力
        ans = 0
        a,b = int(a)-1,int(b)-1
        res = query(a,b+1)
        for i in range(26):
            if res >> i &1:
                ans += 1
        print(ans)

Submission status: Accepted

Solution code:
# import numpy as np

from operator import or_

class segtree:

    def __init__(self, n,operator,identity):
        nb = bin(n)[2:]
        bc = sum([int(digit) for digit in nb])
        if bc == 1:
            self.num_leaves = 2**(len(nb)-1)
        else:
            self.num_leaves = 2**(len(nb))

        self.array = [identity for i in range(self.num_leaves * 2)]
        self.identity = identity
        self.operator =operator
        self.n = n

    def build(self,init_arr):
        for i in range(self.n):
            self.array[i+self.num_leaves] = init_arr[i]
        for i in range(self.num_leaves):
            pt = self.num_leaves-1-i
            self.array[pt] = self.operator(self.array[pt*2],self.array[pt*2+1])


    def update(self,x,val):
        actual_x = x+self.num_leaves
        # self.array[actual_x] = self.operator(self.array[actual_x],val)
        self.array[actual_x] = val
        while actual_x > 0 :
            actual_x = actual_x//2
            self.array[actual_x] = self.operator(self.array[actual_x*2],self.array[actual_x*2+1])

    def get(self,q_left,q_right,arr_ind=1,leaf_left=0,depth=0):
        width_of_floor = self.num_leaves//(2**depth)
        leaf_right = leaf_left+width_of_floor-1

        if leaf_left > q_right or leaf_right < q_left:
            return  self.identity

        elif leaf_left >= q_left and leaf_right <= q_right:
            return self.array[arr_ind]

        else:
            val_l = self.get(q_left,q_right,2*arr_ind,leaf_left,depth+1)
            val_r = self.get(q_left,q_right,2*arr_ind+1,leaf_left+width_of_floor//2,depth+1)
            return self.operator(val_l,val_r)

    def find(self, l, r):
        #findの方が高速
        l += self.num_leaves
        r += self.num_leaves+1
        ret = self.identity
        while l < r:
            if l & 1:
                ret = self.operator(ret, self.array[l])
                l += 1
            if r & 1:
                r -= 1
                ret = self.operator(ret, self.array[r])
            l //= 2
            r //= 2
        return ret







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

tree = segtree(n, or_, 0)
buf = [0 for i in range(n)]

for i in range(n):
    c = ord(s[i]) - 97
    buf[i] = 1<<c


for i in range(26):
    tree.build(buf)




s = list(s)

for i in range(q):
    ty, i, c = input().split()

    if ty == "1":
        i = int(i)
        t = ord(c) - 97
        tree.update(i-1,1<<t)


    else:
        i = int(i)
        c = int(c)
        i -= 1
        c -= 1
        tp = 0
        hoge = tree.get(i,c)
        print(sum(map(int,bin(hoge)[2:])))

Submission status: Accepted

Solution code:
# import numpy as np

from operator import or_

class segtree:

    def __init__(self, n,operator,identity):
        nb = bin(n)[2:]
        bc = sum([int(digit) for digit in nb])
        if bc == 1:
            self.num_leaves = 2**(len(nb)-1)
        else:
            self.num_leaves = 2**(len(nb))

        self.array = [identity for i in range(self.num_leaves * 2)]
        self.identity = identity
        self.operator =operator
        self.n = n

    def build(self,init_arr):
        for i in range(self.n):
            self.array[i+self.num_leaves] = init_arr[i]
        for i in range(self.num_leaves):
            pt = self.num_leaves-1-i
            self.array[pt] = self.operator(self.array[pt*2],self.array[pt*2+1])


    def update(self,x,val):
        actual_x = x+self.num_leaves
        # self.array[actual_x] = self.operator(self.array[actual_x],val)
        self.array[actual_x] = val
        while actual_x > 0 :
            actual_x = actual_x//2
            self.array[actual_x] = self.operator(self.array[actual_x*2],self.array[actual_x*2+1])

    def get(self,q_left,q_right,arr_ind=1,leaf_left=0,depth=0):
        width_of_floor = self.num_leaves//(2**depth)
        leaf_right = leaf_left+width_of_floor-1

        if leaf_left > q_right or leaf_right < q_left:
            return  self.identity

        elif leaf_left >= q_left and leaf_right <= q_right:
            return self.array[arr_ind]

        else:
            val_l = self.get(q_left,q_right,2*arr_ind,leaf_left,depth+1)
            val_r = self.get(q_left,q_right,2*arr_ind+1,leaf_left+width_of_floor//2,depth+1)
            return self.operator(val_l,val_r)

    def find(self, l, r):
        #findの方が高速
        l += self.num_leaves
        r += self.num_leaves+1
        ret = self.identity
        while l < r:
            if l & 1:
                ret = self.operator(ret, self.array[l])
                l += 1
            if r & 1:
                r -= 1
                ret = self.operator(ret, self.array[r])
            l //= 2
            r //= 2
        return ret







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

tree = segtree(n, or_, 0)
buf = [0 for i in range(n)]

for i in range(n):
    c = ord(s[i]) - 97
    buf[i] = 1<<c


for i in range(26):
    tree.build(buf)




s = list(s)

for i in range(q):
    ty, i, c = input().split()

    if ty == "1":
        i = int(i)
        t = ord(c) - 97
        tree.update(i-1,1<<t)


    else:
        i = int(i)
        c = int(c)
        i -= 1
        c -= 1
        tp = 0
        hoge = tree.find(i,c)
        print(sum(map(int,bin(hoge)[2:])))

Submission status: Accepted

Solution code:
n = int(input())
_s = input()
q = int(input())
query = [input() for _ in range(q)]

def bitsum(_bit, i):
    s = 0
    while i > 0:
        s += _bit[i]
        i -= i & (-i)
    return s

def bitadd(_bit, i, x):
    while i <= n:
        _bit[i] += x
        i += i & (-i)
    return _bit

al = [chr(ord('a') + i) for i in range(26)]
al_to_idx = dict()
for i in range(26):
    al_to_idx[al[i]] = i

s = list(_s)

# init
import math
n_ = int(math.log(n) / math.log(2)) + 1
bit = [[0] * (2 ** n_ + 1) for _ in range(26)]
for i in range(n):
    idx = al_to_idx[s[i]]
    bit[idx] = bitadd(bit[idx], i + 1, 1)
# print(bit)

for i in range(q):
    _query = query[i].split(' ')
    if _query[0] == '1':
        # decrement old
        idx = al_to_idx[s[int(_query[1]) - 1]]
        bit[idx] = bitadd(bit[idx], int(_query[1]), -1)

        s[int(_query[1]) - 1] = _query[2]
        # print(s)

        # increment
        idx = al_to_idx[_query[2]]
        bit[idx] = bitadd(bit[idx], int(_query[1]), 1)

    else:
        _ans = 0
        for idx in range(26):
            _bit = bit[idx]
            c = bitsum(_bit, int(_query[2])) - bitsum(_bit, int(_query[1]) - 1)
            if c != 0:
                _ans += 1
        print(_ans)

Submission status: Accepted

Solution code:
import sys
from copy import copy, deepcopy
input = sys.stdin.readline
'''
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
for CASES in range(int(input())):
'''
inf = 100000000000000000  # 1e17
mod = 998244353

'''
# example input


'''


def replace(pos, char):
    x = pos
    old_char = A[x]
    while x <= n:
        tr[x][old_char] -= 1
        x += x & (-x)
    x = pos
    while x <= n:
        tr[x][char] += 1
        x += x & (-x)
    A[pos] = char


def query(pos, char):
    x = pos
    sum = 0
    while x != 0:
        sum += tr[x][char]
        x -= x & (-x)
    return sum


n = int(input())
S = input().strip()
A = [27] * (n + 1)
'''
for i in range(len(S)):
    A.append(ord(S[i])-ord('a'))
'''
tr = [[0] * 30 for i in range(len(S) + 10)]
for i in range(len(S)):
    replace(i + 1, ord(S[i]) - ord('a'))
q = int(input())
for i in range(q):
    QUERY = list((input().split()))
    if int(QUERY[0]) == 1:
        replace(int(QUERY[1]), ord(QUERY[2]) - ord('a'))
    else:
        sum = 0
        for char in range(ord('a'), ord('z') + 1):
            num = query(int(QUERY[2]), char - ord('a')) - \
                query(int(QUERY[1]) - 1, char - ord('a'))
            if num >= 1:
                sum += 1
        print(sum)

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, ceil
        from copy import copy
        self.f = segfunc  # queryのfunction
        self.ide = identity_element
        self.n = len(ls)
        self.ls = copy(ls)
        self.b = ceil(sqrt(self.n))
        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)))