The Number of Products(两种解法,想了一晚上的成果~)

题目描述:

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:

  1. the number of pairs of indices (l,r) (l≤r) such that al​⋅al+1​…ar−1​⋅ar​ is negative;
  2. 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;
}

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值