线段树

来源:互联网 发布:淘宝图片美工软件 编辑:程序博客网 时间:2024/05/22 04:56
#include"stdlib.h"#include"stdio.h"struct tree{    int val;    int low,high;    tree *lt,*rt;};void build(int left,int right,tree *root)//这棵树是left...right{    root->low=left;root->high=right;    if(left==right)    {        scanf("%d",&root->val);return;    }    int mid=(left+right)/2;    tree *lc,*rc;    lc=(tree*)malloc(sizeof(tree));rc=(tree*)malloc(sizeof(tree));    build(left,mid,lc);                                    //左子树  left...mid    root->lt=lc;    build(mid+1,right,rc);                                 //右子树 mid+1...right    root->rt=rc;    root->val=root->rt->val+root->lt->val;}int query(int l,int r,tree root){    if(l<=root.low&&root.high<=r) return root.val;  //当查询区间已经完全包含了节点的区间说明找到了    int mid=(root.low+root.high)/2;    if(r<=mid) return query(l,r,*root.lt);              //如果全在左子树就到左子树里面去找    else if(l>mid) return query(mid+1,r,*root.rt);       //如果全在右子树就到有字数里面去找    else return query(l,mid,*root.lt)+query(mid+1,r,*root.rt); //如果左右子树都有的话两个树都要查询}//1 2 3 4 1 2 3 4 1 2 3 4 1int main(){    while(1)    {        tree a;        tree *root=&a;        build(1,13,root);        printf("Sum:1...7=%d\n",query(1,7,a));        printf("Sum:3...4=%d\n",query(3,4,a));        printf("Sum:2...12=%d\n",query(2,12,a));    }    return 0;}

0 0
原创粉丝点击