题目链接:StarryCoding | 奕歌科技
#include <bits/stdc++.h> using ll = long long; using namespace std; const int N = 1e5 + 9; int a[N]; //对应动物的类型 int w[N]; //对应动物的体重 ll s[N]; //偏移量前缀和(释放魔法后) int main() {ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);int t;cin >> t;while (t--){int n;cin >> n;for (int i = 1; i <= n; i++)cin >> a[i];for (int i = 1; i <= n; i++)cin >> w[i];for (int i = 1; i <= n; i++)s[i] = s[i - 1] + (a[i] ? -1 : 1) * w[i]; //偏移量前缀和,如果类型为1则为-1(如果施加魔法会变成老鼠,要减去)ll zuichu=0; //时间魔法前的体重for (int i = 1; i <= n; i++)zuichu += a[i] * w[i];ll mi = 0, pianyi = 0; //mi=最小的s[j], 0<=j<i。如果发现无论怎样释放魔法,都会比释放前小,那么pianyi=0;for (int i = 1; i <= n; i++){pianyi = max(pianyi, s[i]-mi); //应该是求最大的(s[r]-s[l-1]),即求数值最大的偏移量区间,可以遍历,这时r是确定的,然后找最小的s[l-1]即可,但是l-1<r;mi = min(mi, s[i]); //mi赋值必须在后面才能确保<i;}cout << zuichu + pianyi << "\n";}return 0; }