Codeforces Round #806 (Div. 4) F. Yet Another Problem About Pairs Satisfying an Inequality

Codeforces Round #806 (Div. 4) F. Yet Another Problem About Pairs Satisfying an Inequality

Call a pair good if it satisfies the condition. Let’s split the inequality into three parts: a i < i a_i < i ai<i, i < a j i<a_j i<aj, a j < j a_j<j aj<j.

Note that if a i ≥ i a_i≥i aii for any i i i, then it can’t be an element of a good pair, because it fails the first and third conditions. So we can throw out all elements of the array satisfying a i ≥ i a_i≥i aii.

For the remaining elements, the first and third inequalities are already satisfied, so we only have to count the number of pairs ( i , j ) (i,j) (i,j) with i < a j i<a_j i<aj. Let’s iterate j j j through the array from the left to the right, and make a list storing all i i i that appear before j j j. Then for each j j j, count the number of i i i less than a j a_j aj by binary searching on the number of elements in the list less than a j a_j aj. Afterwards, add j j j to the end of the list.

Since we iterate from left to right, the list will always remain sorted (we insert the indices of elements, which are increasing from left to right), so the binary search will always work.

The time complexity is O ( n l o g n ) O(nlogn) O(nlogn).

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

typedef long long LL;
const int N = 200010;

int tr[N],n;

void add(int x,int y)
{
    for(;x<=n;x+=(x&-x))
        tr[x]+=y;
}

LL query(int x)
{
    LL res=0;
    for(;x>0;x-=(x&-x))
        res+=tr[x];
    return res;
}

int main()
{
    int T;cin>>T;
    while(T--)
    {
        memset(tr,0,sizeof tr);
        cin>>n;
        vector<int> a(n+1);
        for(int i=1;i<=n;i++) cin>>a[i];

        LL res=0;
        for(int i=1;i<=n;i++)
            if(a[i]<i)
            {
                res+=query(a[i]-1);
                add(i,1);
            }

        cout<<res<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Wa_Automata

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

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

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

打赏作者

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

抵扣说明:

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

余额充值