题目传送门:3150: 轮回的轨迹 -- Power OJ
这道题的意思很简单,给你一个长度为N的环形字符串 ,通过操作1、2,修改或查询区间字符种类以及数量,环不环形都不重要,只需要在处理的时候,当给出区间l>r时修改或者查询区间改成[l,n]以及[1,r]就行,这些题目都有提及,就不再讨论。
解题思路:
算法标签就是线段树,这题就是线段树区间修改+区间查询,至于线段树则需要建26颗,可以结构体,二维数组的话(笔者是个苣篛,就没有试过,包括下面代码也是用的结构体),26颗线段树维护的就是对应26个字母的数量,因为题中修改操作就是将数量清零,对应字符数量变成r-l+1(也就是区间长度),而查询操作就是统计两区间各个字符的数量是否相等(每个字符的数量的相等了,对应字符种类还能不一样?对吧)。
AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
#define ll (now<<1|1)
#define rr ll+1
#define mid ((l+r)>>1)
const int N=1e5+5;
int n,m;
char str[N];
struct node{
int cnt[26];
char f;
}tree[4*N],d;
void pushup(int now)
{
for (int i=0; i<26; i++) tree[now].cnt[i]=tree[ll].cnt[i]+tree[rr].cnt[i];
}
void pushdown(int now,int l,int r)
{
if(tree[now].f!='\0')//下放懒标
{
tree[ll].f=tree[rr].f=tree[now].f;
tree[now].f='\0';
memset(tree[ll].cnt, 0, sizeof(tree[ll].cnt));//清零数量
memset(tree[rr].cnt, 0, sizeof(tree[rr].cnt));
tree[ll].cnt[tree[ll].f-'a']=mid-l+1;//使对应字符数量等于区间长度
tree[rr].cnt[tree[rr].f-'a']=r-mid;
}
}
void build_tree(int now=0,int l=1,int r=n)
{
if(l==r) tree[now].cnt[str[l]-'a']++;
else{
build_tree(ll,l,mid);
build_tree(rr,mid+1,r);
pushup(now);
}
}
void update(int idxl,int idxr,char val,int now=0,int l=1,int r=n)//区间修改
{
if (l>=idxl&&r<=idxr)
{
if(tree[now].cnt[val-'a']==r-l+1) return;//如果要修改的区间不用修改了,直接返回
tree[now].f=val;
memset(tree[now].cnt, 0, sizeof(tree[now].cnt));//修改操作
tree[now].cnt[val-'a']=r-l+1;
return;
}
pushdown(now,l,r);
if(idxl<=mid) update(idxl, idxr,val,ll,l,mid);
if(idxr>mid) update(idxl, idxr,val,rr,mid+1,r);
pushup(now);
}
struct node query(int idxl,int idxr,int now=0,int l=1,int r=n)//区间查询
{
if (l>=idxl&&r<=idxr) return tree[now];
else{
pushdown(now,l,r);
if(idxr<=mid) return query(idxl, idxr,ll,l,mid);
else if(idxl>mid) return query(idxl, idxr,rr,mid+1,r);
struct node a=query(idxl, idxr,ll,l,mid);
struct node b=query(idxl, idxr,rr,mid+1,r);
for (int i=0; i<26; i++) {
a.cnt[i]+=b.cnt[i];
}
return a;
}
}
int main()
{
scanf("%d%d",&n,&m);
scanf("%s",str+1);
build_tree();
while(m--)
{
int op,l,r;
char x[2];
scanf("%d",&op);
if(op&1)
{
scanf("%d%d%s",&l,&r,x);
if(l<=r) update(l, r, x[0]);
else{
update(l, n, x[0]);
update(1, r, x[0]);
}
}else{
int ql,qr;
struct node a;
struct node b;
scanf("%d%d%d%d",&l,&r,&ql,&qr);
if(l<=r) a=query(l, r);
else{
a=query(l, n);
b=query(1, r);
for (int i=0; i<26; i++) {
a.cnt[i]+=b.cnt[i];
}
}
if(ql<=qr) b=query(ql, qr);
else{
struct node c=query(ql, n);
b=query(1, qr);
for (int i=0; i<26; i++) {
b.cnt[i]+=c.cnt[i];
}
}
int i;
for (i=0; i<26; i++) {
if(a.cnt[i]!=b.cnt[i]) break;
}
if(i!=26) printf("NO\n");
else printf("YES\n");
}
}
return 0;
}