栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

E2. Array Optimization by Deque

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

E2. Array Optimization by Deque

E2. Array Optimization by Deque

题目入口

思路
贪心+树状数组
在每次加入一个数时比较加在头和尾时新增逆序对数即可,利用树状数组维护即可,由于求逆序对只需要知道数字比当前数大的有几个,即只需要知道他们之间的相对关系,因此首先将数组离散化。

离散化模板

		for(int i=1;i<=n;i++)
        {
            cin>>a1[i];
            a2[i]=a1[i];
        }
        sort(a1+1,a1+n+1);
        int len=unique(a1+1,a1+n+1)-a1-1;
        for(int i=1;i<=n;i++) 
        	a2[i]=lower_bound(a1+1,a1+1+len,a2[i])-a1;

代码

#include
#define int long long
using namespace std;
const int N=2e5+5;
int t,n;
int tree[N];
int a1[N],a2[N];

int lowbit(int x)
{
    return x&-x;
}
void add(int pos,int x)
{
    while(pos<=n)
    {
        tree[pos]+=x;
        pos+=lowbit(pos);
    }
}
int cal(int pos)
{
    int res=0;
    while(pos>=1)
    {
        res+=tree[pos];
        pos-=lowbit(pos);
    }
    return res;
}
signed main()
{
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(int i=1;i<=n;i++) tree[i]=0;
        for(int i=1;i<=n;i++)
        {
            cin>>a1[i];
            a2[i]=a1[i];
        }
        sort(a1+1,a1+n+1);
        int len=unique(a1+1,a1+n+1)-a1-1;
        for(int i=1;i<=n;i++) 
            a2[i]=lower_bound(a1+1,a1+1+len,a2[i])-a1;
        int cnt=0;
        int res=0;
        for(int i=1;i<=n;i++)
        {
            int tmp=a2[i];
            add(tmp,1);
            int check1=cal(n)-cal(tmp);//加在尾
            int check2=cal(tmp-1);//加在头
            res+=min(check1,check2);
        }
        cout<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/289361.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号