题解: CF1903C Theofanis' Nightmare
Codeforces Round 912 (Div. 2) C. Theofanis' Nightmare 题解 - 题解
分析
这道题要求将一个数组分成若干个非空的子数组,然后计算每个子数组的和,并用每个子数组的和乘以子数组的长度,最后求和。问题的关键在于找到一种分割方式,使得其值最大。
观察发现,我们需要在数组中找到一个位置,将数组分为两个部分,使得右半部分的和尽可能大。对于这个问题,从数组的末尾开始往前遍历是一个比较自然的想法。我们可以维护一个变量
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
ll a[N];
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
ll sum=0, res=0;
for(int i=n-1; i>=0; i--)
{
res += a[i];
if(res > 0 || i == 0)
sum += res;
}
cout<<sum<<endl;
}
return 0;
}