Codeforces Round #585 (Div. 2) B.The Number of Products(动态规划)

Posted k2mno4

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces Round #585 (Div. 2) B.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:

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;
Input
The first line contains one integer n (1≤n≤2?10^5) — the number of elements in the sequence.

The second line contains n integers a1,a2,…,an (?10^9 ≤ ai ≤ 10^9;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

解析:题意大概是给出一个序列,让你分别求出有几个区间中的乘积为正数与负数。思路:简单dp。
dp[i][0]:以第i个数结尾的区间中乘积为正数个数,dp[i][1]:以第i个数结尾的区间中乘积为负数的个数。
· 动态转移方程:
1. 当第i个数为正数时:dp[i][0] = dp[i-1][0]+1, dp[i][1] = dp[i-1][1];
2. 当第i个数为负数时:dp[i][0] = dp[i-1][0], dp[i][1] = dp[i-1][0] + 1;
原因很简单,加1其实就是加上自己本身作为一个区间,其次正数与区间乘积为正数的再相乘还是正数,与区间乘积为负数的再相乘为负数;负数与区间乘积为负数的再相乘为正数,负数与区间乘积为正数的再相乘为负数。
太久没写dp了,真的手生了很多...

AC代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<string.h>
#include<math.h>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 7;
const int maxm = 2e5 + 7;
const long long inf = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
int n, x;
int dp[maxm][2]; //dp[i][0]:以下标i结尾为正数子区间个数,dp[i][1]:下标i结尾为负数子区间个数 
LL pos, neg;

int main()
{
	cin >> n;
	for(int i = 1; i <= n; i++)
	{
		cin >> x;
		if(x > 0)
		{
			dp[i][0] = dp[i-1][0] + 1; //之前正数子区间个数+自身 
			dp[i][1] = dp[i-1][1];
		}
		else
		{
			dp[i][0] = dp[i-1][1]; // 
			dp[i][1] = dp[i-1][0] + 1; //之前正数子区间个数 + 自身 
		}
		pos += dp[i][0], neg += dp[i][1];
	}
	cout << neg << " " << pos << endl;
	return 0;
}






















以上是关于Codeforces Round #585 (Div. 2) B.The Number of Products(动态规划)的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #585 (Div. 2) D. Ticket Game

Codeforces Round #585 (Div. 2)

CodeForces Round #585 (Div 2)

Codeforces Round #585 (Div. 2)

Codeforces Round #585 (Div. 2) B.The Number of Products(动态规划)

Codeforces Round #585 (Div. 2) CF1215A~C