您的位置:首页 > 产品设计 > UI/UE

hdu 4339 Query(单点更新+二分查找)

2013-10-09 20:46 337 查看
题意:

给两个字符串,s1,s2

之后进行m次操作

分为两种操作:

操作1:把要求的串的指定位置给位某个字符串,

操作2:找到某个j 使得 for all k (i<=k and k<i+j) s1[k] equals s2[k].

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4339

思路:

刚开始想用结构体(对应的s1,s2上的字符)来存,可是这样更新和之后的查找不好整~

那么怎么存呢,

直接比较就好了啊,

相同的就变成0,不同为1,

之后对于操作2,找j,那就是在区间中找到第一个1就是答案,找的过程,我用的二分,

不过由于忽略了一种情况,一直wa

就是在找的过程,两个字符串完全相同,把二分的返回答案初始化没做好~~~

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 1000010
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

int n,m;
char s1[maxn];
char s2[maxn];
int sum[maxn<<2];

void PushUp(int rt){
sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}

void build(int l,int r,int rt){
if(l == r){
if(s1[l] == s2[l]) sum[rt] = 0;
else sum[rt] = 1;
return;
}
int m = (l + r)/2;
build(lson);
build(rson);
PushUp(rt);
}

void update(int num,int pos,char c,int l,int r,int rt){
if(l == r){
if(num == 1){
s1[pos] = c;
if(s1[pos] == s2[pos]) sum[rt] = 0;
else sum[rt] = 1;
}
else{
s2[pos] = c;
if(s1[pos] == s2[pos]) sum[rt] = 0;
else sum[rt] = 1;
}
return ;
}
int m = (l + r)/2;
if(pos <= m) update(num,pos,c,lson);
else         update(num,pos,c,rson);
PushUp(rt);
}

int query(int L,int R,int l,int r,int rt){
if(L <= l && r <= R){
return sum[rt];
}

int m = (l + r)/2;
int ret = 0;
if(L <= m)  ret += query(L,R,lson);
if(m <  R)  ret += query(L,R,rson);
return ret;
}

int search(int pos){
int left = pos,right = n ,ans = n + 1;
while(left <= right){
int mid = (left + right)/2;
int temp = query(pos,mid,1,n,1);
if(temp >= 1){
ans = mid;
right = mid - 1;
}
else{
left = mid + 1;
}
}
return ans;
}
int main()
{
int T,op;
scanf("%d",&T);
for(int ncase = 1;ncase <= T;ncase ++){
scanf("%s %s",s1+1,s2+1);
int ls1 = strlen(s1+1);
int ls2 = strlen(s2+1);
n = max(ls1,ls2);
build(1,n,1);

scanf("%d",&m);
printf("Case %d:\n",ncase);
while(m--){
scanf("%d",&op);
int num,pos;
char s[10];
if(op==1){
scanf("%d %d %s",&num,&pos,s);
pos ++;
update(num,pos,s[0],1,n,1);
}
else{
scanf("%d",&pos);
pos ++;
if(s1[pos] != s2[pos]) printf("0\n");
else{
int ans = search(pos) - pos;
printf("%d\n",ans);
}
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线段树 HDU