codeforces 1234Distinct Characters Queries [segment tree Solution]

Meaning of the questions:

Below you give you a string of operations

op = 1, into the position pos letter x

op = 2, ask you how many different strings have between l ~ r

solution:

26 letters 01 represents an int type each letter appears a binary OR operation, and showing two sections plus

Then just think of this idea is to modify the single point range query template title

AC Code:

#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);
		}
	}
}

 

Published 31 original articles · won praise 5 · Views 1375

Guess you like

Origin blog.csdn.net/qq_43685900/article/details/102022581