线段树 位运算
传送门
题目
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.
题目思路
用线段树处理数据,然后用位运算去表示字母,如a是01 , b是10,c是100;以此类推
#include
using namespace std;
const int maxn = 1e5+10;
int tree[maxn*4];
char s[maxn];
int len , k;
int op,pos1,pos2;void pushup(int root)
{tree[root] = tree[root<<1] | tree[root<<1|1];
}void build(int root ,int l , int r)
{
// cout <<"1"<if(l == r){
// if(root==11)cout <tree[root] = 1<<(s[l]-'a');
// cout << tree[root]<return;}int mid = (l+r)/2;build(root<<1,l,mid);build(root<<1|1,mid+1,r);pushup(root);
}void updata(int root,int l ,int r,int p,int c)
{if(l==r){tree[root] = 1<<c;return;}int mid = (l+r)/2;if(p>mid) updata(root<<1|1,mid+1,r,p,c);else updata(root<<1,l,mid,p,c);pushup(root);
}int query(int root,int l ,int r,int ql,int qr)
{
// cout <<"1"<if(qr<l || ql > r) return 0;if(ql<=l&&r<=qr)return tree[root];int mid = (l+r)/2;int res = 0;res |= query(root<<1,l,mid,ql,qr);res |= query(root<<1|1,mid+1,r,ql,qr);return res;
}
int main()
{std::ios::sync_with_stdio(false);
// cout << (1<<3)<
// freopen("in.txt","r",stdin);memset(tree,0,sizeof(tree));char ch;cin >> s+1;len = strlen(s+1);cin >> k;build(1,1,len);while(k--){cin >> op;if(op==1){cin >> pos1 >> ch;updata(1,1,len,pos1,ch-'a');}else{cin >> pos1 >> pos2;int ans = 0;;int res = query(1,1,len,pos1,pos2);while(res){if(res&1)ans++;res >>= 1;}cout << ans <<endl;}}
cout <
// for(int i=1;i<=14;i++)
// cout << tree[i]<<" ";
// cout <
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
