题目描述:
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;
输入描述
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.
输出描述
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
样例输入 1
5 5 -3 3 -1 1
样例输出 1
8 7
样例输入 2
10 4 2 -4 3 1 2 -4 3 2 3
样例输出 2
28 27
样例输入 3
5 -1 -2 -3 -4 -5
样例输出 3
9 6
第一种做法就是用dp动态规划,为什么会想到用dp呢,因为我们发现,后面出现正数或者负数,所能形成的数量是由前面决定的,
如果a[i]>0,它对正数区间的贡献是前面子区间乘积>0的个数
如果a[i]>0,它对负数区间的贡献是前面子区间乘积>0的个数+1
如果a[i]<0,它对正数区间的贡献是前面子区间乘积<0的个数
如果a[i]<0,它对负数区间的贡献是前面子区间乘积>0的个数+1
所以我们定义dp[i][0]为前面区间乘积<0的个数
dp[i][1]为前面区间乘积>0的个数
从而代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
int n, m, k;
int a[N];
ll dp[N][2];
int main(void)
{
ios::sync_with_stdio(0); cin.tie(0);//关闭同步流
cin >> n;
for (int i = 1; i <= n; ++i)cin >> a[i];
ll fu = 0, zheng = 0;
for (int i = 1; i <= n; ++i) {
if (a[i] < 0) {
dp[i][0] = dp[i - 1][1] + 1;
dp[i][1] = dp[i - 1][0];
}
else {
dp[i][0] = dp[i - 1][0];
dp[i][1] = dp[i - 1][1] + 1;
}
fu += dp[i][0]; zheng+= dp[i][1];
}
cout << fu << ' ' << zheng<< endl;
return 0;
}
第二种做法是利用前缀和
其实每个数我们不用看它的大小,只用看他的正负,所以我们把所有的正数都变为+1所有的负数都赋值为-1,然后我们看一个例子和图
5 -3 3 -1 1
+ - - + +
- - + +
+ - -
- -
+
这个图每个位置的坐标(i,j)表示 i 到 j 这个区间的正负情况,要一列一列的去看
#include <bits/stdc++.h>
using namespace std;
long long int n;
long long int f,z;
int main(){
cin>>n;
long long int sgn=1,pos=1,neg=0;
for(long long int i=1;i<=n;i++){
long long int a;
cin>>a;
if(a<0)sgn=-sgn;
if(sgn>0){
z+=pos;
f+=neg;
pos++;
}
else{
z+=neg;
f+=pos;
neg++;
}
}
cout<<f<<" "<<z<<endl;
}