#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define pb(x) push_back(x)
#define sz(x) (int) x.size()
#define all(x) x.begin(), x.end()
#define un(x) (x).erase(unique(all(x)), x.end())
typedef long long ll;
typedef double db;
typedef pair <int, int> ii;
typedef pair <ll, ll> pll;
typedef vector <ll> V;
const int N = 2e5 + 10;
// template <class T1, class Gz> void add(T1 &x, Gz y) { x += y; if (x < 0) x += mod; if (x >= mod) x -= mod; }
template <class T1, class Gz> bool maximize(T1 &x, Gz y) { if (x < y) { x = y; return true; } return false; }
template <class T1, class Gz> bool minimize(T1 &x, Gz y) { if (x > y) { x = y; return true; } return false; }
int n, m;
int a[N], b[N];
struct Data {
int s, t, u;
} Q[N];
namespace sub1 {
const int N = 3e3 + 1;
int prev[N], nxt[N], sum[N];
int cost(int l, int r) {
if (l > r) return 0;
return sum[r] - sum[l - 1];
}
void solve() {
for(int i = 1; i <= n; i++) {
sum[i] = sum[i - 1] + a[i];
}
stack <int> st;
for(int i = 1; i <= n; i++) {
while (sz(st) && b[st.top()] >= b[i]) st.pop();
prev[i] = sz(st) ? st.top() : 0;
st.push(i);
}
while (sz(st)) st.pop();
for(int i = n; i >= 1; i--) {
while (sz(st) && b[st.top()] > b[i]) st.pop();
nxt[i] = sz(st) ? st.top() : n + 1;
st.push(i);
}
for(int i = 1; i <= m; i++) {
int s = Q[i].s, t = Q[i].t, u = Q[i].u;
bool flag = false;
for(int j = s; j < t; j++) {
if (u < a[j]) flag = true;
} if (flag) { cout << "-1\n"; continue; }
ll ans = 0;
for(int j = s; j < t; j++) {
int rem = prev[j] >= s ? max(0, u - cost(prev[j], j - 1)) : 0;
int cur = min(u, cost(j, min(nxt[j], t) - 1)) - rem;
maximize(cur, 0);
ans += 1ll * cur * b[j];
} cout << ans << endl;
}
}
};
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i++) {
cin >> a[i];
}
for(int i = 1; i <= n; i++) {
cin >> b[i];
}
for(int i = 1; i <= m; i++) {
int s, t, u; cin >> s >> t >> u;
Q[i] = {s, t, u};
}
sub1::solve();
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |