B. The Number of Products
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a sequence a1,a2,…,an consisting of n non-zero integers (i.e. ai≠0).
You have to calculate two following values:
the number of pairs of indices (l,r) (l≤r) such that al⋅al+1…ar−1⋅ar is negative;
the number of pairs of indices (l,r) (l≤r) such that al⋅al+1…ar−1⋅ar is positive;
Input
The first line contains one integer n (1≤n≤2⋅105) — the number of elements in the sequence.
The second line contains n integers a1,a2,…,an (−109≤ai≤109;ai≠0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
inputCopy
5
5 -3 3 -1 1
outputCopy
8 7
inputCopy
10
4 2 -4 3 1 2 -4 3 2 3
outputCopy
28 27
inputCopy
5
-1 -2 -3 -4 -5
outputCopy
9 6
比赛时候竟然看不出是DP ,(ಥ_ಥ)
dp1[i]表示到i为止是负数的子序列的个数
dp2[i]表示到i为止乘积是正的子序列的个数
之后考虑之间正负之间的转换就好了
我面壁去了~~
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp1[200010],dp2[200010];
int main()
{
int n,a;scanf("%d",&n);
ll an1=0,an2=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
if(a<0)
{
dp1[i]=dp2[i-1]+1;
dp2[i]=dp1[i-1];
}else
{
dp1[i]=dp1[i-1];
dp2[i]=dp2[i-1]+1;
}
an1+=dp1[i];
an2+=dp2[i];
}
printf("%lld %lld\n",an1,an2);
}