BZOJ 3289 Mato的文件管理

本文介绍了一种通过分块策略优化资料排序的过程,该过程利用了数据结构和算法技巧来减少文件排序所需的交换次数,适用于加密文件的高效查看。

Description
Mato同学从各路神犇以各种方式(你们懂的)收集了许多资料,这些资料一共有n份,每份有一个大小和一个编号。为了防止他人偷拷,这些资料都是加密过的,只能用Mato自己写的程序才能访问。Mato每天随机选一个区间[l,r],他今天就看编号在此区间内的这些资料。Mato有一个习惯,他总是从文件大小从小到大看资料。他先把要看的文件按编号顺序依次拷贝出来,再用他写的排序程序给文件大小排序。排序程序可以在1单位时间内交换2个相邻的文件(因为加密需要,不能随机访问)。Mato想要使文件交换次数最小,你能告诉他每天需要交换多少次吗?


【题目分析】
分块,打错了一个正负号调了半天。


【代码】

#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
using namespace std;
struct query{
    int l,r,num;
}b[50010];
int T,a[50010],L[50010],R[50010],cnt=0,n,q,top;
int t[50010],ls[50010];
long long out[50010];
bool cmp1(query a,query b)
{return a.l==b.l?a.r<b.r:a.l<b.l;}
bool cmp2(query a,query b)
{return a.r<b.r;}
void add(int x,int f)
{for (;x<=top;x+=x&(-x)) t[x]+=f;}
int gs(int x)
{
    int ret=0;
    for (;x;x-=x&(-x)) ret+=t[x];
    return ret;
}
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;++i) scanf("%d",&a[i]),ls[i]=a[i];
    sort(ls+1,ls+n+1);
    top=unique(ls+1,ls+n+1)-ls-1;
    for (int i=1;i<=n;++i) a[i]=lower_bound(ls+1,ls+top+1,a[i])-ls; top+=3;
    scanf("%d",&q);
    for (int i=1;i<=q;++i) scanf("%d%d",&b[i].l,&b[i].r),b[i].num=i;
    sort(b+1,b+q+1,cmp1);
    T=sqrt(q);
    for (int i=1;i<=q;i+=T)
    {
        cnt++;
        L[cnt]=i; R[cnt]=i+T-1;
    }
    R[cnt]=q;
    for (int i=1;i<=cnt;++i) sort(b+L[i],b+R[i]+1,cmp2);
    int nowl=1,nowr=0;
    long long ans=0;
    for (int i=1;i<=q;++i)
    {
//      printf("%d %d\n",b[i].l,b[i].r);
        while (nowl<b[i].l)
        {
            add(a[nowl],-1);
            ans-=(ll)(gs(a[nowl]-1));
            nowl++;
//          printf("nowl ++ dec %d\n",(gs(a[nowl]-1)));
        }
        while (nowl>b[i].l)
        {
            nowl--;
            add(a[nowl],1);
            ans+=(ll)(gs(a[nowl]-1));
//          printf("nowl -- dec %d\n",(gs(a[nowl]-1)));
        }
        nowl=b[i].l;
        while (nowr<b[i].r)
        {
            nowr++;
            add(a[nowr],1);
            ans+=(ll)(gs(top)-gs(a[nowr]));
//          printf("nowr ++  dec %d\n",(gs(top)-gs(a[nowr])));
        }
        while (nowr>b[i].r)
        {
            add(a[nowr],-1);
            ans-=(ll)(gs(top)-gs(a[nowr]));
//          printf("nowr --  dec %d\n",(gs(top)-gs(a[nowr])));
            nowr--;
        }
        out[b[i].num]=ans;
    }
    for (int i=1;i<=q;++i)
    printf("%lld\n",out[i]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值