题意:给定 n 个数,然后有 q 个询问,问你每个区间的最大值。
析:数据很小,直接暴力即可,不会超时,也可以用RMQ算法。
代码如下:
#include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> using namespace std ; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f; const double eps = 1e-8; const int maxn = 1e3 + 5; const int dr[] = {0, 0, -1, 1}; const int dc[] = {-1, 1, 0, 0}; int n, m; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int a[maxn]; int main(){ int T; cin >> T; while(T--){ scanf("%d", &n); for(int i = 1; i <= n; ++i) scanf("%d", &a[i]); scanf("%d", &m); while(m--){ int l, r; scanf("%d %d", &l, &r); int ans = -1; for(int i = l; i <= r; ++i) ans = max(ans, a[i]); printf("%d\n", ans); } } return 0; }
#include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> using namespace std ; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f3f; const double eps = 1e-8; const int maxn = 1e3 + 5; const int dr[] = {0, 0, -1, 1}; const int dc[] = {-1, 1, 0, 0}; int n, m; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int d[maxn][20]; void rmq_init(){ for(int j = 1; (1<<j) <= n; ++j) for(int i = 1; i + (1<<j) - 1 <= n; ++i) d[i][j] = max(d[i][j-1], d[i+(1<<(j-1))][j-1]); } int rmq_query(int l, int r){ //int k = log(r-l+1)/log(2.0); int k = 0; while((1<<(k+1)) <= r-l+1) ++k; return max(d[l][k], d[r-(1<<k)+1][k]); } int main(){ int T; cin >> T; while(T--){ scanf("%d", &n); memset(d, 0, sizeof(d)); for(int i = 0; i < n; ++i) scanf("%d", &d[i+1][0]); rmq_init(); scanf("%d", &m); while(m--){ int l, r; scanf("%d %d", &l, &r); printf("%d\n", rmq_query(l, r)); } } return 0; }