D. Distinct Characters Queries

该博客讨论如何解决一种字符串查询问题,其中涉及替换字符和计算给定子串中不同字符的数量。作者建议使用线段树,并通过位运算来维护每个节点的字符集合,以高效地进行区间查询和修改。在每种类型的查询中,对给定子串的唯一字符计数是关键。

You 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.

思路:

        区间查询,区间修改,很明显就是线段树,主要是维护的是什么,首先线段树有个操作叫区间合拼,那么很容易我们就能想到集合操作里面的交集,那么我们可以用位运算,一个字母代表一位,然后取交集就行。

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int n,arr[400100];
char s[100100];
void bulid(int key,int l,int r)
{
	if(l>r)
		return;
	else if(l==r)
	{
		arr[key]=1<<(s[l]-'a');
	}
	else
	{
		int mid = (l+r)/2;
		bulid(key*2,l,mid);
		bulid(key*2+1,mid+1,r);
		arr[key]=arr[key*2]|arr[key*2+1];
	}
}
void udpate(int key,int l,int r,int wei,int value)
{
	if(r<l)
		return;
	if(l==r)
	{
		if(wei==l)
			arr[key]=1<<value;
	}
	else if(l<=wei&&r>=wei)
	{
		int mid = (l+r)/2;
		if(mid>=wei&&l<=wei)
			udpate(key*2,l,(l+r)/2,wei,value);
		if(mid+1<=wei&&r>=wei)
			udpate(key*2+1,(l+r)/2+1,r,wei,value);
		arr[key]=arr[key*2]|arr[key*2+1];
	}
}
int query(int key,int l,int r,int ql,int qr)
{
	if(r<ql||l>qr)
		return 0;
	if(l>=ql&&r<=qr)
	{
		return arr[key];
	}
	else
	{
		int ans=0;
		int mid = (l+r)/2;
		ans|=query(key*2,l,mid,ql,qr);
		ans|=query(key*2+1,mid+1,r,ql,qr);
		return ans;
	}
}
int main()
{
	scanf("%s",s+1);
	int len = strlen(s+1);
	cin>>n;
	bulid(1,1,len);
	for(int i=1;i<=n;i++)
	{
		int mark,wei,l,r;
		char temp;
		cin>>mark;
		if(mark==1)
		{
			cin>>wei>>temp;
			udpate(1,1,len,wei,temp-'a');
		}
		else
		{
			int ans=0;
			cin>>l>>r;
			int ret = query(1,1,len,l,r);
			while(ret)
			{
				if(ret&1)
					ans++;
				ret>>=1;
			}
			cout<<ans<<endl;
		}
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值