codeforces 1234Distinct Characters Queries[线段树解法]

题意:

给你一个字符串下面你的操作

op = 1,将pos位的字母换成x

op = 2,问你l~r之间有多少个不同的字符串

解法:

26个字母用int类型二进制0 1表示每个字母是否出现 或运算表示两个区间加和

然后只要想到这个思路就是单点修改区间查询模板题

AC代码:

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>

using namespace std;
const int MaxN = 1e5 + 5;

char s[MaxN];
int n;
int l,r,pos;
char x;
int tree[MaxN * 4];

void build(int k,int ll,int rr){
	if(ll == rr){
		tree[k] = 1 << (s[ll] - 'a');
		return ;
	}
	int m = (ll + rr) / 2;
	build(k * 2,ll,m);
	build(k * 2 + 1,m + 1,rr);
	tree[k] = tree[k * 2] | tree[k * 2 + 1];
}

void chan_p(int k,int ll,int rr){
	if(ll == rr){
		s[ll] = x;
		tree[k] = 1 << (x - 'a');
		return ;
	}
	int m = (ll + rr) / 2;
	if(pos <= m) chan_p(k * 2,ll,m);
	else chan_p(k * 2 + 1,m + 1,rr);
	tree[k] = tree[k * 2] | tree[k * 2 + 1];
}

int ask_val(int k,int ll,int rr){
	if(ll >= l && rr <= r) return tree[k];
//	if(ll > r || rr < l) return 0;
	int m = (ll + rr) / 2;
	int ans = 0;
	if(l <= m) ans |= ask_val(k * 2,ll,m);
	if(r > m) ans |= ask_val(k * 2 + 1,m + 1,rr);
	return ans;
}

int main()
{
	scanf("%s",s + 1);
	scanf("%d",&n);
	build(1,1,strlen(s + 1));
	while(n--){
		int op;
		scanf("%d",&op);
		if(op == 1){
			scanf("%d %c",&pos,&x);
			chan_p(1,1,strlen(s + 1));
		}
		else{
			scanf("%d %d",&l,&r);
			int cur = ask_val(1,1,strlen(s + 1)),haha = 0;
	//		cout << cur << "#\n";
			for(int i = 0;i < 26; i++){
				if(cur & (1 << i)) haha++;
			}
			printf("%d\n",haha);
		}
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值