K - The Number of Products

K - The Number of Products

题目入口:K - The Number of Products
Codeforces:B. The Number of Products
参考网站:
https://www.cnblogs.com/Tianwell/p/11530761.html
https://blog.csdn.net/weixin_43870697/article/details/100896170

解题思路

题意:给定一串数字 问从l到r形成的区间数字乘积为负、正的区间个数各是多少
思路:首先粗略谈一下第二个TLE的代码 想法是好的 数组的每一位异或实现存放当前为止所有数乘积结果的正负(0正 1负) 此外对于每一个l~r区间 想要知道其正负 只需要将到r为止乘积正负值与到l-1为止乘积正负值异或即可
但遗憾的是…TLE

我们开始说第一个代码
a[]存放每一位数字
neg[i]存放到第i个数为止以i结尾的区间数字乘积为负的区间个数
pos[i]存放到第i个数为止以i结尾的区间数字乘积为正的区间个数
那么显然最终的负区间个数便是neg[i]所有值之和 最终的正区间个数便是pos[i]所有值之和
所以在这里我们分别用ncnt(negative counting)和pcnt(positive counting)来得到最终答案
首先利用第一个数字初始化neg[1]pos[1]
接下来从第2到第n个数遍历
如果第i个数为负数 那么之前以第i-1个数结尾的所有区间数字乘积为正的区间涵盖第i个数(负数)后都转变为区间数字乘积为负的区间
因此此时的neg[i]存放的值为pos[i-1]加上1(这个1代表这第i个数自己形成的负区间)
同理我们不难得到第i个数位正数的情况的处理
到这里讲解结束

AC代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 2e5+10;
LL a[N], neg[N], pos[N];
int main() {
    LL n;
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
    neg[1] = a[1]<0?1:0;
    pos[1] = 1-neg[1];
    LL ncnt = neg[1], pcnt = pos[1];
    for (int i = 2; i <= n; i++){
        if (a[i] < 0){
            neg[i] = pos[i-1]+1;
            pos[i] = neg[i-1];
        }
        else {
            pos[i] = pos[i-1]+1;
            neg[i] = neg[i-1];
        }
        ncnt += neg[i];
        pcnt += pos[i];
    }
    printf("%lld %lld\n", ncnt, pcnt);
    return 0;
}

TLE代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 2e5+10;
LL a[N];
int main() {
    LL n, ncnt = 0, pcnt = 0;
    scanf("%lld", &n);
    a[0] = 0;
    for (int i = 1; i <= n; i++){
        scanf("%lld", &a[i]);
        if (a[i] > 0) a[i] = 0;
        else a[i] = 1;
        a[i] ^= a[i-1];
    }
    for (int i = 1; i <= n; i++){
        for (int j = i; j <= n; j++){
            if (a[i-1] ^ a[j]) ncnt++;
            else pcnt++;
        }
    }
    printf("%lld %lld\n", ncnt, pcnt);
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值