题目大意
一个由n (1<=n<=2e5) 个正整数组成的数组a,(1<=ai<=1e9),进行一次操作:选择两个端点l、r (1<=l,r<=n),将 a [ l ]~a [ r ] 所有的数替换成他们的乘积。问:为最大化数组a的和,l、r该如何选择。
思路
察看数据发现,数组a的和最大能到 2e5*1e9=2e14,当a的所有数的乘积大于这个值时,去掉左右两端的1,剩余的中间的数全部做乘积得到的结果是最优的;若所有数的和小于这个值时,找有多少个不为1的数,最小为2,而约等于48,由此可知大于1的数最多不超过50个可直接暴力求解,先存下来之后,两层循环枚举左右端点,找最优解。
code
#include<iostream>
#include<vector>
using namespace std;
using ll = long long;
const ll N = 2e5 + 10, maxn = 2e14;
ll a[N], mul[N], sum[N], n;
vector<int>v;
void solve()
{
cin >> n;
v.clear();
mul[0] = 1;
for (int i = 1; i <= n; i++){
cin >> a[i];
mul[i] = mul[i - 1] * a[i];
sum[i] = sum[i - 1] + a[i];
if (a[i] != 1)v.push_back(i);
}
ll now = 1;
for (int i = 1; i <= n; i++)
{
if (now > maxn / a[i])
{
int l = 1, r = n;
while (a[l] == 1)++l;
while (a[r] == 1)--r;
cout << l << " " << r << "\n";
return;
}
now *= a[i];
}
ll l = 1, r = 1, ans = 0;
for (int i = 0; i < v.size(); i++)
for (int j = i; j < v.size(); j++)
{
ll tmp = sum[n] - sum[v[j]] + sum[v[i] - 1];
tmp += mul[v[j]] / mul[v[i] - 1];
if (tmp > ans)
{
l = v[i];
r = v[j];
ans = tmp;
}
}
cout << l << " " << r << "\n";
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t = 1;
cin >> t;
while (t--)
{
solve();
}
return 0;
}