码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-06-14 16:59:19      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:pos   int   fir   rod   round   value   mod   positive   tin   

题目:
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(动态规划)

标签:pos   int   fir   rod   round   value   mod   positive   tin   

原文地址:https://www.cnblogs.com/K2MnO4/p/13125274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!