在缺水之地,水源極其珍貴。給定 n 個水源,大小為 a1..an。q 個查詢,每個查詢給出 l, r,求區間 [l, r] 內最大水源大小。
限制:T≤10, n≤1000, q≤1000, ai∈[1, 106]。
輸入: 3 1 100 1 1 1 1 5 1 2 3 4 5 5 1 2 1 3 2 4 3 4 3 5 3 1 999999 1 4 1 1 1 2 2 3 3 3 輸出: 100 2 3 4 4 5 1 999999 999999 1
標準解法為線段樹或稀疏表(RMQ),單次查詢 O(log n) 或 O(1)。但本題 n, q 均 ≤ 1000,暴力掃描區間最大值僅需 O(n×q) = 106 量級,完全在時限內,代碼極簡,無需複雜數據結構。
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
int a[1010];
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
int q;
scanf("%d", &q);
while (q--) {
int l, r;
scanf("%d%d", &l, &r);
int mx = 0;
for (int i = l; i <= r; i++)
if (a[i] > mx) mx = a[i];
printf("%d\n", mx);
}
}
return 0;
}
若 n, q 擴大到 105,則需線段樹/稀疏表。本題數據範圍小,暴力最優(開發效率最高)。