HDU 4339 Query

http://acm.hdu.edu.cn/showproblem.php?pid=4339

血与泪,伤与痛,无须多言

线段树找数列中任意起点最多有多少连续的1

View Code
#include <iostream>
#include <string.h>
using  namespace std ;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn=1000001 ;
char s1[maxn],s2[maxn] ;
int tree[maxn<<2] ;
int n ;
void pushup(int l,int r,int rt)
{
    int m=(l+r)>>1 ;
    if(tree[rt<<1]==m-l+1)
        tree[rt]=tree[rt<<1]+tree[rt<<1|1] ;
    else
        tree[rt]=tree[rt<<1] ;
}
void build(int l,int r,int rt)
{
    if(l==r)
    {
        tree[rt]=(s1[l]==s2[l]) ;
        return ;
    }
    int m=(l+r)>>1 ;
    build(lson) ;
    build(rson) ;
    pushup(l,r,rt) ;
}
void update(int a,int p,char c,int l,int r,int rt)
{
    if(l==r)
    {
        if(a==1)
        {
            s1[p]=c ;
            tree[rt]=(s1[l]==s2[l]) ;
        }
        else
        {
            s2[p]=c ;
            tree[rt]=(s1[l]==s2[l]) ;
        }
        return ;
    }
    int m=(l+r)>>1 ;
    if(p<=m)
        update(a,p,c,lson) ;
    else
        update(a,p,c,rson) ;
    pushup(l,r,rt) ;
}
int query(int p,int l,int r,int rt)
{
    if(l==p)
        return tree[rt] ;
    int m=(l+r)>>1 ;
    int ans ;
    if(p<=m)
    {
        ans=query(p,lson) ;
        if(ans==m-p+1) 
            ans+=query(m+1,rson) ;
    }
    else
        ans=query(p,rson) ;
    return ans ;
}
int main()
{
    int t ;
    scanf("%d",&t) ;
    for(int cas=1;cas<=t;cas++)
    {
        scanf("%s%s",s1,s2) ;
        n=min(strlen(s1),strlen(s2)) ;
        build(0,n-1,1) ;
        int Q ;
        scanf("%d",&Q) ;
        printf("Case %d:\n",cas) ;
        while(Q--)
        {
            int op ;
            int a,p ;
            scanf("%d",&op) ;
            if(op==1)
            {
                char c[2] ;
                scanf("%d%d%s",&a,&p,c) ;
                if(p<n)
                    update(a,p,c[0],0,n-1,1) ;
            } 
            else
            {
                scanf("%d",&p) ;
                if(p<n)
                    printf("%d\n",query(p,0,n-1,1)) ;
                else
                    puts("0") ;
            }
        }
    }
    return 0 ;
}
原文地址:https://www.cnblogs.com/xiaohongmao/p/2621880.html