csu 1110 RMQ with Shifts 线段树

题意:求动态rmq


思路:因为要移动的数据很小,不过是移动十几个,所以可以每次一边移动后更新


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


#include 
#include 
#include 
#include 
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;
}


你可能感兴趣的:(数据结构)