我们考虑暴力枚举a[i]为最大值 通过单调栈可以求出a[i]左边右边第一个大于a[i]的 然后通过ST表查询前缀和数组(i,R[i]-1)的最大值 (L[i]+1,i)的最小值得到我们需要的区间和最大值 check即可
注意我们这里因为是前缀和 query_max(i, R[i] - 1) - query_min(L[i], i - 1) L这边要-1 所以就会有0这个点 我们ST表的范围就要更改为[0,n]
#include <bits/stdc++.h> using namespace std; const int N = 2e5+10; const int M = 998244353; const int mod = 1000000007; #define int long long #define endl '\n' #define Endl '\n' #define YES cout<<"YES"<<endl; #define NO cout<<"NO"<<endl; #define _ 0 #define inf 0x3f3f3f3f3f3f3f3f #define fast ios::sync_with_stdio(false);cin.tie(nullptr); int a[N],f1[N][30],f2[N][30],n,L[N],R[N],pre[N]; void init() { for (int len = 0; len < 30; len++) { for (int i = 0; i + (1 << len) - 1 <= n; i++) { if (!len)f1[i][len] = pre[i]; else f1[i][len] = max(f1[i][len - 1], f1[i + (1 << (len - 1))][len - 1]); } //i+1<<len-1的话是包括了i 不用加1 } for (int len = 0; len < 30; len++) { for (int i = 0; i + (1 << len) - 1 <= n; i++) { if (!len)f2[i][len] = pre[i]; else f2[i][len] = min(f2[i][len - 1], f2[i + (1 << (len - 1))][len - 1]); } //i+1<<len-1的话是包括了i 不用加1 } } int query_max(int l,int r) { int len = r - l + 1; int k = log(len) / log(2); return max(f1[l][k], f1[r - (1 << k) + 1][k]); //而r-1<<k是没有包含到r所以要+1 } int query_min(int l,int r) { int len = r - l + 1; int k = log(len) / log(2); return min(f2[l][k], f2[r - (1 << k) + 1][k]); //而r-1<<k是没有包含到r所以要+1 } void solve() { cin >> n; for (int i = 1; i <= n; i++)cin >> a[i], pre[i] = pre[i - 1] + a[i]; stack<int> stk; a[n + 1] = inf; for (int i = 1; i <= n + 1; i++) { while (stk.size() && a[stk.top()] < a[i]) { R[stk.top()] = i; stk.pop(); } stk.push(i); } while (stk.size())stk.pop(); a[0] = inf; for (int i = n; i >= 0; i--) { while (stk.size() && a[stk.top()] < a[i]) { L[stk.top()] = i; stk.pop(); } stk.push(i); } for (int i = 1; i <= n; i++) { if (a[i] < (query_max(i, R[i] - 1) - query_min(L[i], i - 1))) { NO return; } } YES } signed main(){ fast int T;cin>>T; while(T--) { solve(); } return ~~(0^_^0); }