Fork me on GitHub

UVA 12532 Interval Product

线段树水题,忽略每个数的大小,只记住他们的正负即可,规规矩矩的代码。不过这是我第一次完全自己写的一次A的代码了。纪念一下。。。

 

#include <iostream>
#include <cstdio>
using namespace std;
#define N 100010

int tree[4*N];
int x;
char ans[100005];

void build(int l,int r,int rt)
{
    if(l == r)
    {
        cin>>x;
        if(x>0)
            tree[rt] = 1;
        else if(x == 0)
            tree[rt] = 0;
        else
            tree[rt] = -1;
        return;
    }
    int mid = (l+r)/2;
    build(l,mid,2*rt);
    build(mid+1,r,2*rt+1);
    tree[rt] = tree[2*rt]*tree[2*rt+1];
}

void change(int l,int r,int pos,int val,int rt)
{
    if(l == r)
    {
        if(val<0)
            tree[rt] = -1;
        else if(val == 0)
            tree[rt] = 0;
        else
            tree[rt] = 1;
        return;
    }
    int mid = (l+r)/2;
    if(pos<=mid)
        change(l,mid,pos,val,2*rt);
    else
        change(mid+1,r,pos,val,2*rt+1);
    tree[rt] = tree[2*rt]*tree[2*rt+1];
}

int query(int l,int r,int aa,int bb,int rt)
{
    if(aa>r||bb<l)
        return 0;
    if(aa<=l&&bb>=r)
        return tree[rt];
    int mid = (l+r)/2;
    if(bb<=mid)
        return query(l,mid,aa,bb,2*rt);
    if(aa>mid)
        return query(mid+1,r,aa,bb,2*rt+1);
    return query(l,mid,aa,bb,2*rt)*query(mid+1,r,aa,bb,2*rt+1);
}
int main()
{
    int n,k,i,j;
    int ka;
    char ss[5];
    int aa,bb;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        ka = 0;
        memset(ans,0,sizeof(ans));
        build(1,n,1);
        for(i=0;i<k;i++)
        {
            scanf("%s %d %d",ss,&aa,&bb);
            if(ss[0] == 'C')
            {
                change(1,n,aa,bb,1);
            }
            else
            {
                int res = query(1,n,aa,bb,1);
                if(res > 0)
                    ans[ka++] = '+';
                else if(res < 0)
                    ans[ka++] = '-';
                else
                    ans[ka++] = '0';
            }
        }
        printf("%s\n",ans);
    }
    return 0;
}
View Code

 

 

posted @ 2013-12-13 13:21  whatbeg  阅读(317)  评论(0编辑  收藏  举报