Codeforces Round #835 (Div. 4) E. Binary Inversions

Codeforces Round #835 (Div. 4) E. Binary Inversions

Let’s find out how to count the number of binary inversions, without flips. This is the number of 1 1 1s that appear before a 0 0 0. To do this, iterate through the array and keep a running total k k k of the number of 1 1 1s seen so far. When we see a 0 0 0, increase the total inversion count by k k k, since this 0 0 0 makes k k k inversions: one for each of the 1 1 1s before it.

Now let’s see how to maximize the inversions. Consider the flip 0 → 1 0→1 01. We claim that it is best to always flip the earliest 0 0 0 in the array. It’s never optimal to flip a later 0 0 0, since we have strictly fewer 0 0 0s after it to form inversions. Similarly, we should flip the latest 1 1 1 in the array.

Now recalculate the answer for these two choices for flipping, and pick the maximum. The complexity is O ( n ) O(n) O(n).

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int T=1;cin>>T;
    while(T--)
    {
        int n;cin>>n;
        vector<int> a(n);

        int sum0=0;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            if(!a[i]) sum0++;
        }

        int mx=0;
        int res0=0,res1=0;
        long long ans=0;
        for(int i=0;i<n;i++)
        {
            if(a[i])
            {
                ans+=sum0-res0;
                mx=max(mx,res1-(sum0-res0));
                res1++;
            }
            else
            {
                ans+=res1;
                mx=max(mx,(sum0-res0-1)-res1);
                res0++;
            }
        }
        cout<<ans/2+mx<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wa_Automata

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值