hdu 1698 线段树

来源:互联网 发布:中文翻译缅甸语言软件 编辑:程序博客网 时间:2024/05/20 11:23

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

我的思路刚开始是在函数:update函数中

错误的为

:p[step].value=0;p[step*2].value=p[step*2+1].value=p[step].value;

明显错误为 以上所有的值为0了,则应该调换位置,同时我还忽略了p[step]用该是不为0的情况时,才可以这样;

标准代码为:

 if(p[step].value)
        {
            p[2*step].value=p[2*step+1].value=p[step].value;
            p[step].value=0;
        }

我的代码为

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using  namespace std;


#define sizen 110000
struct ele
{
    int left;
    int right;
    int value;
}p[sizen*4];


void build(int L,int R,int step)
{
    p[step].left=L;
    p[step].right=R;
    if(L==R)
        p[step].value=1;
    else
    {
        int Mid=(L+R)/2;
        build(L,Mid,2*step);
        build(Mid+1,R,2*step+1);
        p[step].value=0;
    }
}


void update(int x,int y,int z,int step)
{
    if(p[step].left==x&&p[step].right==y)
        p[step].value=z;
    else
    {
        if(p[step].value)
        {
            p[2*step].value=p[2*step+1].value=p[step].value;
            p[step].value=0;
        }
        int Mid=(p[step].left+p[step].right)/2;
        if(y<=Mid)
            update(x,y,z,2*step);
        else
        if(x>=Mid+1)
            update(x,y,z,2*step+1);
        else
        {
            update(x,Mid,z,2*step);
            update(Mid+1,y,z,2*step+1);
        }
    }
}


int summ(int x,int y,int step)
{
    if(p[step].left==x&&p[step].right==y&&p[step].value!=0)
        return p[step].value*(p[step].right-p[step].left+1);
    else
    {
        int Mid=(p[step].left+p[step].right)/2;
        if(y<=Mid)
            return summ(x,y,2*step);
        else
        if(x>=Mid+1)
            return summ(x,y,2*step+1);
        else
            return summ(x,Mid,2*step)+summ(Mid+1,y,2*step+1);
    }
}


int main()
{
    int T;
    int N,Q;
    int x,y,z;
    int cnt=0;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&N,&Q);
        build(1,N,1);
        while(Q--)
        {
            scanf("%d%d%d",&x,&y,&z);
            update(x,y,z,1);
        }
        printf("Case %d: The total value of the hook is %d.\n",++cnt,summ(1,N,1));
    }
    return 0;
}

0 0
原创粉丝点击