题目
题意: 给定一个长度为n的数组,数组中元素大小为[-2,2].数组的贡献为数组中所有元素乘积的乘积,可以删除任意数量的元素,使得数组贡献最大。不要求删除的数量最少,找出任意解即可。空数组贡献为1。
思路: 模拟。
(1)不存在0,判断负数出现次数的奇偶性即可。如果是奇数,判断从左边删更优还是从右边删更优。
(2)存在0。如果全是0,那就全删除。
如果不全是0,会发现只能保留一小段两个0之间的数。否则的话有0一乘就变成0了。所以每一小段仿照(1)检查一下谁更优即可。
时间复杂度: O(n)
代码:
// Problem: D. Maximum Product Strikes Back
// Contest: Codeforces - Codeforces Round #780 (Div. 3)
// URL: https://codeforces.com/contest/1660/problem/D
// Memory Limit: 256 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
int n,m,k,T;
int s[N];
int sum[N];
int a[N];
void solve()
{
vector<int> va;
va.push_back(0);
scanf("%d",&n);
int cnt = 0; //负数的个数
for(int i=1;i<=n;++i)
{
int x; scanf("%d",&x);
a[i] = x;
if(x == 0) va.push_back(i);
if(x < 0) cnt++;
s[i] = s[i-1] + (x<0);
sum[i] = sum[i-1] + (abs(x)==2);
}
int ans1 = 0,ans2 = 0;
va.push_back(n+1);
if(va.size() == 2)
{
if(cnt % 2 == 0)
{
printf("0 0\n");
return ;
}
int l = 0,r = 0; //损失的2
for(int i=1;i<=n;++i)
{
if(a[i] == 2 || a[i] == -2) l++;
if(a[i] < 0)
{
ans1 = i;
ans2 = 0;
break;
}
}
for(int i=n;i>=1;--i)
{
if(abs(a[i])==2) r++;
if(a[i] < 0)
{
if(r < l)
{
ans1 = 0;
ans2 = (n-i+1);
}
break;
}
}
printf("%d %d\n",ans1,ans2);
}
else if(cnt == n)
{
printf("%d %d\n",n,0);
}
else
{
int mx = -1;
int ans1 = n,ans2 = 0;
for(int i=0;i<va.size()-1;++i)
{
int st = va[i]+1,ed = va[i+1]-1;
int tot = sum[ed] - sum[st-1];
int cnt = s[ed] - s[st-1];
// cout<<i<<" "<<st<<" "<<ed<<":"<<tot<<' '<<cnt<<endl;
if(cnt & 1)
{
int l = 0,r = 0;
for(int j=st;j<=ed;++j)
{
if(abs(a[j])==2) l++;
if(a[j] < 0 && tot-l > mx)
{
mx = tot-l;
ans1 = j;
ans2 = (n-ed);
break;
}
}
for(int j=ed;j>=st;--j)
{
if(abs(a[j])==2) r++;
if(a[j] < 0 && tot-r>mx)
{
mx = tot-r;
ans1 = st-1;
ans2 = (n-j+1);
break;
}
}
}
else
{
if(tot > mx)
{
mx = tot;
ans1 = st-1;
ans2 = (n-ed);
}
}
}
if(mx == -1)
{
ans1 = n;
ans2 = 0;
}
printf("%d %d\n",ans1,ans2);
}
}
signed main(void)
{
scanf("%d",&T);
while(T--)
solve();
return 0;
}