Distinct Characters Queries(树状数组)

ou are given a string s consisting of lowercase Latin letters and q queries for this string.

Recall that the substring s[l;r] of the string s is the string slsl+1…sr. For example, the substrings of “codeforces” are “code”, “force”, “f”, “for”, but not “coder” and “top”.

There are two types of queries:

1 pos c (1≤pos≤|s|, c is lowercase Latin letter): replace spos with c (set spos:=c);
2 l r (1≤l≤r≤|s|): calculate the number of distinct characters in the substring s[l;r].
Input
The first line of the input contains one string s consisting of no more than 105 lowercase Latin letters.

The second line of the input contains one integer q (1≤q≤105) — the number of queries.

The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.

Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.

Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6


```cpp
#include
#include
#include
using namespace std;
const int M=1e5+10;
char s[M];
int book[M][30];
int n,m,k;
int lowbit(int x)
{
	return x&(-x);
}
void build(int x,int c)
{
	while(x<=k)
	book[x][c]++,x+=lowbit(x);
}
void update(int x,int p,int c)
{
	int xx=x;
	while(xx<=k)
	book[xx][p]--,xx+=lowbit(xx);
	while(x<=k)
	book[x][c]++,x+=lowbit(x);
}
int query(int a,int b)
{
	int dp[30]={0};
	while(b>0)
	{
		for(int i=0;i<26;i++)
		dp[i]+=book[b][i];
		b-=lowbit(b);
	}
	while(a>0)
	{
		for(int i=0;i<26;i++)
		dp[i]-=book[a][i];
		a-=lowbit(a);
	}
	int ans=0;
	for(int i=0;i<26;i++)
	if(dp[i]>0)
	ans++;
	return ans;
}
int main()
{
	while(~scanf("%s",s+1))
	{
		memset(book,0,sizeof book);
		k=strlen(s+1);
		for(int i=1;i<=k;i++)
		build(i,s[i]-'a');
		scanf("%d",&m);
		while(m--)
		{
			scanf("%d",&n);
			if(n==1)
			{
				int x;
				char w[10];
				scanf("%d%s",&x,w);
				update(x,s[x]-'a',w[0]-'a');
				s[x]=w[0];
			}
			else
			{
				int a,b;
				scanf("%d%d",&a,&b);
				printf("%d\n",query(a-1,b));
			}
		}
	}
	return 0;
}

你可能感兴趣的:(Distinct Characters Queries(树状数组))