UVA 12299 - RMQ with Shifts(線段樹)

來源:互聯網
上載者:User

標籤:style   http   color   os   io   for   代碼   ar   

UVA 12299 - RMQ with Shifts

題目連結

題意:給定一個數組,兩種操作,每次query操作輸出區間最小值,每次shift操作把選中位置每個位置向左移一位,最左的到最後去

思路:線段樹,shift操作中位置個數不會超過30個,那麼直接當作點修改來做,那麼就變成了簡單的線段樹了

代碼:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define INF 0x3f3f3f3f#define lson(x) ((x<<1) + 1)#define rson(x) ((x<<1) + 2)const int N = 100005;int n, m, shif[35], sn, num[N];char Q[1005];struct Node {    int l, r, Min;} node[4 * N];void handle(char *Q) {    int len = strlen(Q);    int num = -1;    sn = 0;    for (int i = 0; i < len; i++) {if (Q[i] >= '0' && Q[i] <= '9') {    if (num == -1) num = Q[i] - '0';    else num = num * 10 + Q[i] - '0';}else {    if (num != -1) {shif[sn++] = num;num = -1;    }}    }    sort(shif, shif + sn);}void build(int l, int r, int x = 0) {    node[x].l = l; node[x].r = r;    if (l == r) {node[x].Min = num[l];return;    }    int mid = (l + r) / 2;    build(l, mid, lson(x));    build(mid + 1, r, rson(x));    node[x].Min = min(node[lson(x)].Min, node[rson(x)].Min);}void set(int k, int v, int x = 0) {    if (node[x].l == node[x].r) {node[x].Min = v;return;    }    int mid = (node[x].l + node[x].r) / 2;    if (k <= mid) set(k, v, lson(x));    if (k > mid) set(k, v, rson(x));    node[x].Min = min(node[lson(x)].Min, node[rson(x)].Min);}int query(int l, int r, int x = 0) {    if (node[x].l >= l && node[x].r <= r)return node[x].Min;    int mid = (node[x].l + node[x].r) / 2;    int ans = INF;    if (l <= mid) ans = min(ans, query(l, r, lson(x)));    if (r > mid) ans = min(ans, query(l, r, rson(x)));    return ans;}int main() {    while (~scanf("%d%d", &n, &m)) {for (int i = 1; i <= n; i++)    scanf("%d", &num[i]);build(1, n);while (m--) {    scanf("%s", Q);    handle(Q);    if (Q[0] == 'q')printf("%d\n", query(shif[0], shif[1]));    else {int tmp = num[shif[0]];set(shif[sn - 1], num[shif[0]]);for (int i = 1; i < sn; i++) {    set(shif[i - 1], num[shif[i]]);    num[shif[i - 1]] = num[shif[i]];}num[shif[sn - 1]] = tmp;    }}    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.