CF 1215 B The Number of Products(思維題)


鏈接:https://codeforces.com/contest/1215/problem/B

You are given a sequence a1,a2,,ana1,a2,…,an consisting of nn non-zero integers (i.e. ai0ai≠0).

You have to calculate two following values:

  1. the number of pairs of indices (l,r)(l,r) (lr)(l≤r) such that alal+1ar1aral⋅al+1…ar−1⋅ar is negative;
  2. the number of pairs of indices (l,r)(l,r) (lr)(l≤r) such that alal+1ar1aral⋅al+1…ar−1⋅ar is positive;
Input

The first line contains one integer n(1n2105)(1≤n≤2⋅105) — the number of elements in the sequence.

The second line contains nn integers a1,a2,,ana1,a2,…,an (109ai109;ai0)(−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.

 

題意:求乘積為負數和正數的子段個數(沒有0)

題解:正數0,負數1,統計前綴和(就是求前綴和奇偶),再從頭掃一遍,維護2個桶前綴和為奇數的個數和前綴和為偶數的個數。

#include <bits/stdc++.h>
using namespace std;
 
const int maxn=2e5+5;
int n;
int a[maxn], sum[maxn], cnt[2];
long long pos, neg;
 
int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>a[i];
        if(a[i]>0) a[i]=0;
        else a[i]=1;
    }
    for(int i=1; i<=n; i++)
        sum[i]=sum[i-1]+a[i];
    for(int i=1; i<=n; i++)
        sum[i]=sum[i]%2;
    cnt[0]++;                 //注意cnt0初始化為1,表示區間長度為1的那個
    for(int i=1; i<=n; i++)
    {
        if(sum[i]){
            pos+=cnt[1];
            neg+=cnt[0];
        }
        else{
            pos+=cnt[0];
            neg+=cnt[1];
        }
        cnt[sum[i]]++;
    }
    cout<<neg<<" "<<pos;
    return 0;
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM