bzoj5278 [Usaco2018 Open]Out of Sorts(智商题+BIT)

本文介绍了一种使用双向冒泡排序算法的优化方法,并通过BIT(Binary Indexed Tree)数据结构进行维护,以减少排序过程中的比较次数。核心在于利用Mi表示前i个数中排序后不在前i个位置的数的数量,通过最大化Mi来确定完成排序所需的趟数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

双向冒泡排序,问你需要跑几趟。
定义Mi表示前i个数中排序后不在前i个的数的个数。
Mi就是答案的一个下界,因此所有Mi的最大值就是答案。
可以用一个BIT来维护。
为啥呢?考虑i,i+1之间的分割点,你每一趟双向冒泡,实际上是使得一个在分割点左边的本应在右边的跑到了右边,同时让一个在分割点右边的本应在左边的跑到了左边。也就是说每一趟最多使得Mi-1,因此需要Mi趟才能使得这个分割点出现。

注意如果全是0也要有一次检查qaq

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 100010
#define ll long long
#define inf 0x3f3f3f3f
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int n,c[N],ans=0;
struct node{
    int id,x;
    friend bool operator<(node a,node b){return a.x==b.x?a.id<b.id:a.x<b.x;}
}a[N];
inline void add(int x){for(;x<=n;x+=x&-x) c[x]++;}
inline int ask(int x){int res=0;for(;x;x-=x&-x) res+=c[x];return res;}
inline bool cmp(node a,node b){return a.id<b.id;}
int main(){
//  freopen("a.in","r",stdin);
    n=read();for(int i=1;i<=n;++i) a[i].x=read(),a[i].id=i;
    sort(a+1,a+n+1);for(int i=1;i<=n;++i) a[i].x=i;sort(a+1,a+n+1,cmp);
    for(int i=1;i<=n;++i){
        add(a[i].x);ans=max(ans,i-ask(i));
    }printf("%d\n",ans?ans:1);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值