最大數maxnumber BZOJ - 1012

題目傳送門

思路:就可以直接用線段樹來做,但是這個題用cin,cout就會re,好迷啊。

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

#define MAXN 1000010
#define MAXE 5
#define INF 0x7ffffff
#define MOD 1000000007
#define LL long long
#define ULL unsigned long long
#define pi 3.14159

using namespace std;

int M, n;
LL D;
LL dat[MAXN];

void init() {
    n = 1;
    while (n < M + 10) {
        n *= 2;
    }
    for (int i = 0; i <= 2 * n - 1; ++i) {
        dat[i] = -INF;
    }
}

void update(int pos, LL a) {
    pos += n - 1;
    dat[pos] = a;
    while (pos > 0) {
        pos = (pos - 1) / 2;
        dat[pos] = max(dat[pos * 2 + 1], dat[pos * 2 + 2]);
    }
}

LL query(int a, int b, int k, int l, int r) {
    if (r <= a || b <= l)
        return -INF;
    if (a <= l && r <= b) {
        return dat[k];
    } else {
        LL vl = query(a, b, k * 2 + 1, l, (l + r) / 2);
        LL vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return max(vl, vr);
    }
}

int main() {
    //std::ios::sync_with_stdio(false);
    scanf("%d%lld", &M, &D);
    init();
    LL k;
    LL t = 0;
    char op;
    int cnt = 0;
    for (int i = 0; i < M; ++i) {
        scanf(" %c%lld", &op, &k);
        if (op == 'A') {
            k += t;
            k %= D;
            update(cnt, k);
            cnt++;
        } else {
            t = query(cnt - (int) k, cnt, 0, 0, n);
            printf("%lld\n", t);
        }
    }
    return 0;
}

補上一個單調棧的做法,效率更高,代碼量也很小。

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

#define MAXN 1000010
#define MAXE 5
#define INF 0x7ffffff
#define MOD 1000000007
#define LL long long
#define ULL unsigned long long
#define pi 3.14159

using namespace std;

LL num[MAXN];
LL sta[MAXN];

int main() {
    //std::ios::sync_with_stdio(false);
    int M;
    LL D;
    scanf("%d%lld", &M, &D);
    char op;
    LL k;
    LL t = 0;
    int cnt = 0;
    int top = 0;
    for (int i = 0; i < M; ++i) {
        scanf(" %c%lld", &op, &k);
        if (op == 'A') {
            k = (k + t) % D;
            num[cnt++] = k;
            while (top && num[sta[top - 1]] < k) {
                top--;
            }
            sta[top++] = cnt - 1;
        } else {
            int pos = lower_bound(sta, sta + top, cnt - k) - sta;
            t = num[sta[pos]];
            printf("%lld\n", t);
        }
    }
    return 0;
}
發佈了130 篇原創文章 · 獲贊 25 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章