POJ 3264 Balanced Lineup (RMQ detailed)

Source: Internet
Author: User

RMQ: (interval max problem)

Essentially dynamic programming, with D (I, j) representing the minimum value of a section of an element that starts with a length of 2^j from I, you can use a recursive method to calculate D (i, J): D (i, j) = min{D (i, j-1), D (i + 2^ (j-1), j-1)}

Because 2^j <= n so the number of elements in the D array does not exceed Nlogn, the total time complexity is O (NLOGN);

#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include < algorithm> #include <vector> #include <set> #include <map> #include <queue> #include < cmath> #include <stack> #define LL long longusing namespace Std;const int maxn = 50000 + 10;int D[maxn][20];int a[m    Axn];int N, q;void rmq_init_min () {for (int i=0;i<n;i++) d[i][0] = A[i]; for (int. j=1; (1<<j) <= n;j++) for (int i=0;i+ (1&LT;&LT;J)-1 < n;i++) D[i][j] = min (d[i][j-1], d[i+ (1<< (j-1))][j-1]);}    int rmq_min (int L, int R) {int k = 0;    while ((1<< (k+1)) <= r-l + 1) k++; return min (D[l][k], d[r-(1<<k) +1][k]);}    int dp[maxn][20];void Rmq_init_max () {for (int i=0;i<n;i++) dp[i][0] = A[i]; for (int j=1, (1<<j) <= n;j++) for (int i=0;i+ (1&LT;&LT;J)-1 < n;i++) Dp[i][j] = max (dp[i][j-1) , dp[i+ (1<< (j-1))][j-1]);}    int Rmq_max (int L, int R) {int k = 0; While(1<< (k+1)) <= r-l + 1) k++; Return Max (Dp[l][k], dp[r-(1<<k) +1][k]);} int main () {while (scanf ("%d%d", &n, &q)!=eof) {for (int i=0;i<n;i++) scanf ("%d", &a        [i]);        Rmq_init_min ();        Rmq_init_max ();        int L, R;            while (q--) {scanf ("%d%d", &l, &r);            int L = rmq_min (L-1, R-1);            int r = Rmq_max (L-1, R-1);        printf ("%d\n", r-l); }} return 0;}


POJ 3264 Balanced Lineup (RMQ detailed)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.