维护好前缀和b,那么 l 到 r 的要么正着走花费 b[r - 1] - b[l - 1] ,要么反着走花费 b[n] - b[r - 1] + b[l - 1]
记得保证 l<r
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 2e6 + 5; int __t = 1, n, q, l, r, a[N], b[N]; void solve() { cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; b[i] = b[i - 1] + a[i]; } cin >> l >> r; if (l > r) swap(l, r); cout << min(b[r - 1] - b[l - 1], b[n] - b[r - 1] + b[l - 1]) << '\n'; return; } int32_t main() { #ifdef ONLINE_JUDGE ios::sync_with_stdio(false); cin.tie(0); #endif // cin >> __t; while (__t--) solve(); return 0; }