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⋅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.

Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.

给你一个序列a1,a2,…,an一个由n个非零整数组成的序列(即a i≠0)。
必须计算以下两个值:
指数对(L,R)(L≤R)的数目,使得al⋅al+1…ar−1⋅ar为负;
指数对(L,R)(L≤R)的数目,使得al⋅al+1…ar−1⋅ar为正;
输入:
第一行包含一个整数n (1≤n≤2 *10 5)序列中的元素数。
第二行包含n个整数a1,a2,…,an(-10 9≤ai≤10 9;ai不等于0)序列的元素。
输出:
分别打印两个整数-负积的子段数和正积的子段数。
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

分析:
如果全为正数,则子段数全为正积,个数: 1+2+3+…+(n-1)+n;
所以可以将数组从头遍历,然后累加。
如果在遍历正数时遇到了负数,则子段数的积为负,个数为 i 。将负数个数与正数个数互换,然后累加负数个数。
如果再遇到负数,则字段数的积为正,个数为 i 。将正数个数与负数个数互换,然后再累加正数个数。
负数中间子段数的积也为正,所以还是需要累加正数个数。

code:

#include <iostream>

using namespace std;

int main()
{
    int n;
    while(cin>>n)
    {
        long long x,ne=0,po=0,ren=0,rep=0;
        while(n--)
        {
            cin>>x;
            if(x>0)
                po++;
            else
            {
                x=po;
                po=ne;
                ne=x;
                ne++;
            }
            rep+=po;
            ren+=ne;
        }
        cout<<ren<<" "<<rep<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44350170/article/details/100940014