B. The Number of Products
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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
Copy
5
5 -3 3 -1 1
output
Copy
8 7
input
Copy
10
4 2 -4 3 1 2 -4 3 2 3
output
Copy
28 27
input
Copy
5
-1 -2 -3 -4 -5
output
Copy
9 6
乍一看没想出来。
正解应该记录到当前位置,为正数的子串数,为负数的子串数。O(n)扫一遍得到答案。
#include <bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
typedef long long ll;
const int maxn = 1e6+50;
const int INF = 0x3f3f3f3f;
const ll MOD = 1e9+7;
template <class T>
inline bool scan_d(T &ret) {
char c; int sgn;
if (c = getchar(), c == EOF) return 0;
while (c != '-' && (c<'0' || c>'9')) c = getchar();
sgn = (c == '-') ? -1 : 1;
ret = (c == '-') ? 0 : (c - '0');
while (c = getchar(), c >= '0'&&c <= '9') ret = ret * 10 + (c - '0');
ret *= sgn;
return 1;
}
int main()
{
ll n;
cin >> n;
int temp;
ll pos = 0, neg = 0;
ll ansa = 0, ansb = 0;
rep(i, 1, n){
cin >> temp;
if(temp > 0){
pos++;
ansa += pos;
ansb += neg;
}else{
swap(neg, pos);
neg++;
ansb += neg;
ansa += pos;
}
}
cout << ansb << " " << ansa;
return 0;
}
/*
5 2 5 4 5
*/