The Number of Products
You are given a sequence a1,a2,…,ana1,a2,…,an consisting of nn non-zero integers (i.e. ai≠0ai≠0).
You have to calculate two following values:
- the number of pairs of indices (l,r)(l,r) (l≤r)(l≤r) such that al⋅al+1…ar−1⋅aral⋅al+1…ar−1⋅ar is negative;
- the number of pairs of indices (l,r)(l,r) (l≤r)(l≤r) such that al⋅al+1…ar−1⋅aral⋅al+1…ar−1⋅ar is positive;
Input
The first line contains one integer nn (1≤n≤2⋅105)(1≤n≤2⋅105) — the number of elements in the sequence.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109;ai≠0)(−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
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6
题解及分析
AC代码:
#include<stdio.h>
#include<string.h>
//R[i]表示以i为结尾的正子列的个数,L[i]表示以i为结尾的负子列的个数
long long int n,a[200005],R[200005],L[200005],ansR=0,ansL=0;
int main()
{
scanf("%lld",&n);
for(long long int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
//将a[i]按照是否为负数分类,便于后面进行遍历
if(a[i]<0) a[i]=1;
else a[i]=0;
}
R[0]=0;
L[0]=0;
for(int i=1;i<=n;i++)
{
if(a[i])//递推关系
{
L[i]=R[i-1]+1;
R[i]=L[i-1];
}
else
{
R[i]=R[i-1]+1;
L[i]=L[i-1];
}
ansR+=R[i];//ansR表示前i个数组成的数列一共有ansR个正子列
ansL+=L[i];//ansL表示前i个数组成的数列一共有ansL个负子列
}
printf("%lld %lld",ansL,ansR);
return 0;
}