POJ 3667 线段树

来源:互联网 发布:visio mac版下载 编辑:程序博客网 时间:2024/05/21 22:53

传送门: poj 3667

题解:

优先左边, 区间合并


/*  adrui's submission   Language : C++  Result : Accepted  Favorite : Dragon Balls  Love : yy  Motto : Choose & Quit  Standing in the Hall of Fame*/#include<iostream>#include<cstring>#include<algorithm>using namespace std;const int maxn(50005);//code#define debug 0#define lowbit(x) (x & (-x))#define ls rt << 1#define rs rt << 1 | 1#define M(a, b) memset(a, b, sizeof(a))int  n, m;struct Node{    int l, r;    int lazy;    int la, ra, ans;    void update() {        la = ra = ans = (lazy ? 0 : (r - l + 1));    }}node[maxn << 2];void pushUp(Node &q, Node a, Node b, int l, int r) {        //合并    q.la = a.la;    q.ra = b.ra;    q.ans = max(a.ans, b.ans);    q.ans = max(q.ans, a.ra + b.la);    int mid = (l + r) >> 1;    if (q.la == mid - l + 1) q.la += b.la;    if (q.ra == r - mid)        q.ra += a.ra;}void pushDown(int rt) {    if (node[rt].lazy != -1) {        node[rt << 1].lazy = node[rt << 1 | 1].lazy = node[rt].lazy;        node[rt].lazy = -1;        node[rt << 1].update();        node[rt << 1 | 1].update();    }}void build(int rt, int l, int r) {    node[rt].l = l;    node[rt].r = r;    node[rt].lazy = 0;    node[rt].update();    if (l == r) return;    int mid = (l + r) >> 1;    build(ls, l, mid);    build(rs, mid + 1, r);    pushUp(node[rt], node[rt << 1], node[rt << 1 | 1], l, r);}void updata(int rt, int l, int r, int ul, int ur, int v) {    if (ul <= l && ur >= r) {        node[rt].lazy = v;        node[rt].update();        return;    }    pushDown(rt);    int mid = (l + r) >> 1;    if (ul <= mid) updata(ls, l, mid, ul, ur, v);    if (ur > mid)  updata(rs, mid + 1, r, ul, ur, v);    pushUp(node[rt], node[rt << 1], node[rt << 1 | 1], l, r);}int query(int rt, int l, int r, int len) {          //query    pushDown(rt);    int mid = (l + r) >> 1;     if (node[rt << 1].ans >= len) return query(ls, l, mid, len);//左边有解    else if (node[rt << 1].ra + node[rt << 1 | 1].la >= len) return node[rt << 1].r - node[rt << 1].ra + 1;//合并解    else return query(rs, mid + 1, r, len);//右边解}int main() {#if debug    freopen("in.txt", "r", stdin);#endif //debug    cin.tie(0);    cin.sync_with_stdio(false);    int op, lt, len;    while (cin >> n >> m) {        build(1, 1, n);        while (m--) {            cin >> op;            if (op == 1) {                cin >> lt;                int ans;                if (node[1].ans < lt) ans = 0;//不存在解                else ans = query(1, 1, n, lt);                cout << ans << endl;                if(ans) updata(1, 1, n, ans, ans + lt - 1, 1);            }            else {                cin >> lt >> len;                updata(1, 1, n, lt, lt + len - 1, 0);            }        }    }    return 0;}

教训

查询中间合并的时候求下标得技巧,思维江化…
区间合并还要在熟一点

0 0