csu 1110 RMQ with Shifts 線段樹

題意:求動態rmq


思路:因爲要移動的數據很小,不過是移動十幾個,所以可以每次一邊移動後更新


題目鏈接:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1110


#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
using namespace std;
#define lson l, m, rt << 1
#define rson m+1, r, rt << 1 | 1

const int maxn = 111111;
int minn[maxn<<2];

void pushup(int rt)
{
    minn[rt] = min(minn[rt << 1], minn[rt << 1 | 1]);
}

void build(int l, int r, int rt)
{
    if(l == r)
    {
        scanf("%d", &minn[rt]);
        return;
    }
    int m = (l+r) >> 1;
    build(lson);
    build(rson);
    pushup(rt);
}

int query(int L, int R, int l, int r, int rt)
{
    if(L <= l && R >= r)
        return minn[rt];
    int m = (l+r) >> 1;
    int res = 0x3f3f3f3f;
    if(m >= L) res = min(res, query(L, R, lson));
    if(m < R) res = min(res, query(L, R, rson));
    return res;
}

void update(int l, int r, int rt, int loc, int val)
{
    if(l == r)
    {
        minn[rt] = val;
        return;
    }
    int m = (l+r) >> 1;
    if(m >= loc) update(lson, loc, val);
    else update(rson, loc, val);
    pushup(rt);
}

int main()
{
    int n, q, cnt;
    char s[35];
    int a[30];
    scanf("%d%d", &n, &q);
    build(1, n, 1);
    while(q--)
    {
        scanf("%s", s);
        if(s[0] == 'q')
        {
            int l = 0, r = 0, i;
            for(i = 6; s[i] != ','; i++)
                l = l*10 + s[i]-'0';
            for(i++; s[i] != ')'; i++)
                r = r*10 + s[i]-'0';
            printf("%d\n", query(l, r, 1, n, 1));
        }
        else
        {
            cnt = 0;
            int i = 6;
            while(s[i] != ')' && s[i] != '\0')//把shift的數存到a數組
            {
                int num = 0;
                while(s[i] != ',' && s[i] != ')')
                {
                    num = num * 10 + s[i] - '0';
                    i++;
                }
                i++;
                a[cnt++] = num;
            }
            int tmp = query(a[0], a[0], 1, n, 1);//這幾行都是在循環移動
            for(int i = 0; i < cnt-1; i++)
            {
                int c = (i+1)%cnt;
                int rr = query(a[c], a[c], 1, n, 1);
                update(1, n, 1, a[i], rr);
            }
            update(1, n, 1, a[cnt-1], tmp);
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章