码迷,mamicode.com
首页 > 其他好文 > 详细

线段树

时间:2014-08-19 14:08:24      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   ar   

bubuko.com,布布扣
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;

const int maxn=200005;

int val[maxn+1];

struct node
{
    int total;
    int left;
    int right;
    int mark;//  1  用于延时标记
}tree[maxn*3];

int creat(int Root,int Left,int Right)
{
    tree[Root].mark=0;//  2  初始化
    tree[Root].left=Left;
    tree[Root].right=Right;
    if(Left==Right)
    return tree[Root].total=value[Left];//找到子叶  直接赋值
    int a,b,mid=(Left+Right)>>1;
    a=creat(Root<<1,Left,mid);
    b=creat((Root<<1)+1,mid+1,Right);
    return tree[Root].total=a+b;
}

void update_mark(int Root)//  3  更新root的左右两个子节点mark值
{
    if(tree[Root].mark)
    {
        tree[Root].total=tree[Root].mark*(tree[Root].right-tree[Root].left+1);
        if(tree[Root].left!=tree[Root].right)
        tree[Root<<1].mark=tree[Root<<1|1].mark=tree[Root].mark;
        tree[Root].mark=0;
    }
}

int calculate(int Root,int Left,int Right)
{
    update_mark(Root);//  4  跟新当前root的左右节点
    
    if(tree[Root].left>Right||tree[Root].right<Left)
    return 0;
    
    if(Left<=tree[Root].left&&tree[Root].right<=Right)
    return tree[Root].total;
    
    int a,b;
    a=calculate(Root<<1,Left,Right);
    b=calculate((Root<<1)+1,Left,Right);
    return a+b;
}


int update(int Root,int Left,int Right,int value)
{
    update_mark(Root);// 5
    
    if(tree[Root].left>Right||tree[Root].right<Left)
    return tree[Root].total;
    
    if(Left<=tree[Root].left&&tree[Root].right<=Right)
    {
        tree[Root].mark=value;// 6
        return tree[Root].total=value*(tree[Root].right-tree[Root].left+1);// 7
    }
    
    int a,b;
    a=update(Root<<1,Left,Right,value);
    b=update((Root<<1)+1,Left,Right,value);
    return tree[Root].total=a+b;
}

int main()
{
    int t;
    //freopen("aa.txt","r",stdin);
    scanf("%d",&t);
    for(int kase=1;kase<=t;kase++)
    {
        int n,m;
        scanf("%d %d",&n,&m);
        creat(1,1,n);
        int a,b,c;
        while(m--)
        {
            scanf("%d %d %d",&a,&b,&c);
            update(1,a,b,c);
        }
        printf("Case %d: The total value of the hook is %d.\n",kase,calculate(1,1,n));
    }
    return 0;
}
View Code

 

线段树,布布扣,bubuko.com

线段树

标签:style   blog   http   color   os   io   for   ar   

原文地址:http://www.cnblogs.com/zhanzhao/p/3921797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!