You are given a sequence a1,a2,…,an consisting of n integers.
You have to calculate three 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 zero; 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) — the elements of the sequence.
Output Print three integers — the number of subsegments with negative product, the number of subsegments with product equal to zero and the number of subsegments with positive product, respectively.
Examples input 5 5 -3 3 -1 0 output 6 5 4 input 10 4 0 -4 3 1 2 -4 3 0 3 output 12 32 11 input 5 -1 -2 -3 -4 -5 output 9 0 6 Note In the first example there are six subsegments having negative products: (1,2), (1,3), (2,2), (2,3), (3,4), (4,4), five subsegments having products equal to zero: (1,5), (2,5), (3,5), (4,5), (5,5), and four subsegments having positive products: (1,1), (1,4), (2,4), (3,3).
分析:
分3个数组,pos[i]表示以i结尾的区间积为正数的数量,nage[i]表示负数,zero[i]表示区间积为0。
1.如果第i为是正数:
pos[i]=pos[i-1]+1。加一是因为包含自己一个数。
nage[i]=nage[i-1]。
zero[i]=zero[i-1]。
2.如果第i为是负数:
nage[i]=pos[i-1]+1。负数可由正数乘上第i变成负数。加一是加上自己。
pos[i]=nage[i-1]。负数可由正数乘上第i变成正数数。
zero[i]=zero[i-1]。
3.如果第i是0:
pos[i]=0; nage[i]=0; 清0,因为乘上0都变成0了。 zero[i]=zero[i-1]+pos[i-1]+nage[i-1]+1; 正数或负数或者0乘上0都是0。
代码:
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<sstream> #include<vector> #include<stack> #include<deque> #include<cmath> #include<map> using namespace std; typedef long long ll; const int maxn=2e5+6; const int mod=1e4+7; int pos[maxn],nage[maxn],o[maxn]; int main() { int n; cin>>n; //以i为定点,前面的区间数 for(int i=1;i<=n;i++) { int a; scanf("%d",&a); if(a>0) { pos[i]=pos[i-1]+1; nage[i]=nage[i-1]; o[i]=o[i-1]; } else if(a<0) { pos[i]=nage[i-1]; nage[i]=pos[i-1]+1; o[i]=o[i-1]; } else { pos[i]=0; nage[i]=0; o[i]=o[i-1]+pos[i-1]+nage[i-1]+1; } } ll poss=0,nag=0,zeo=0; for(int i=1;i<=n;i++) { poss+=pos[i]; nag+=nage[i]; zeo+=o[i]; } printf("%lld %lld %lld\n",nag,zeo,poss); return 0; }
原文:https://www.cnblogs.com/studyshare777/p/12615324.html