poj 1159 二维线段树 插点求线

来源:互联网 发布:js中中jsonarray怎么用 编辑:程序博客网 时间:2024/06/07 05:59

题意:…

思路:上二维线段树

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <string>#include <math.h>#include <stdlib.h>#include <time.h>using namespace std;const int MAXN = 1050;struct Nodey{    int l,r;    int val;};int n;int locx[MAXN],locy[MAXN];struct Nodex{    int l,r;    Nodey sty[MAXN*3];    void build(int i,int _l,int _r)    {        sty[i].l = _l;        sty[i].r = _r;        sty[i].val = 0;        if(_l == _r)        {            locy[_l] = i;            return;        }        int mid = (_l + _r)>>1;        build(i<<1,_l,mid);        build((i<<1)|1,mid+1,_r);    }    int query(int i, int y1, int y2)    {    //  cout<<i<<" "<<sty[i].l<<" "<<sty[i].r<<endl;        if(y1 == sty[i].l && y2 == sty[i].r)            return sty[i].val;        int mid = (sty[i].r + sty[i].l)/2;        if(y2<=mid) return query(i<<1, y1, y2);        else if(y1>mid) return query(i<<1|1, y1, y2);        else        {            int a = query(i<<1, y1, mid);            int b = query(i<<1|1, mid+1, y2);            return a+b;        }    }}stx[MAXN*3];void build(int i,int l,int r){    stx[i].l = l;    stx[i].r = r;    stx[i].build(1,1,n);    if(l == r)    {        locx[l] = i;        return;    }    int mid = (l+r)>>1;    build(i<<1,l,mid);    build((i<<1)|1,mid+1,r);}int query(int i, int x1, int x2, int y1, int y2){    //cout<<i<<" "<<stx[i].l<<" "<<stx[i].r<<endl;    if(x1 == stx[i].l && x2 == stx[i].r)        return stx[i].query(1, y1, y2);    int mid = (stx[i].l+stx[i].r)/2;    if(x2 <= mid) return query(i<<1, x1, x2, y1, y2);    else if(x1>mid) return query(i<<1|1, x1, x2, y1, y2);    else    {        int a = query(i<<1, x1, mid, y1, y2);        int b = query(i<<1|1, mid+1, x2, y1, y2);        return a+b;    }}void Modify(int x, int y, int val){    int tx = locx[x];    int ty = locy[y];    stx[tx].sty[ty].val+=val;    for(int i=tx; i; i>>=1)        for(int j=ty; j; j>>=1)        {            if(i == tx&&j == ty) continue;            if(i!=tx)            {                stx[i].sty[j].val = stx[i<<1].sty[j].val + stx[i<<1|1].sty[j].val;            }            else            {                stx[i].sty[j].val = stx[i].sty[j<<1].val + stx[i].sty[j<<1|1].val;            }        }}int main(){    //freopen("in.txt","r",stdin);    //freopen("out.txt","w",stdout);    while(true)    {        int cmd;int x1,y1,x2,y2;        scanf("%d", &cmd);        if(cmd == 0)        {            scanf("%d", &x1);            n = x1;            build(1, 1, x1);         }        else if(cmd == 1)        {            scanf("%d %d %d", &x1, &y1, &x2);            Modify(x1+1, y1+1, x2);        }        else if(cmd == 2)        {            scanf("%d %d %d %d", &x1, &y1, &x2, &y2);            int res = query(1, x1+1, x2+1, y1+1, y2+1);            cout<<res<<endl;        }        else break;    }    return 0;}
0 0
原创粉丝点击