您的位置:首页 > 其它

BZOJ 1112 POI2008 砖块

2016-02-10 15:49 211 查看
树状数组 , Treap , 还有MultiSet&Map 都是可搞的。

这里提供一个树状数组的版本……

提示:

1. 对于这种点间求距离的题目 , 初中课本上讲中位数应该提到过……

代码后详解:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <deque>
#include <stack>
#include <algorithm>
#include <set>

using namespace std;
typedef long long ll;

const int maxn = 1010000;

__inline int re() {
int n = 0, ch = getchar(); bool flag = false;
while(!isdigit(ch)) flag |= ch == '-', ch = getchar();
while(isdigit(ch)) n = n * 10 + ch - '0', ch = getchar();
return flag ? -n : n;
}

int n , k;
int a[maxn] , Max;

ll d1[1100000] , d2[1100000];

int lowbit(int x) { return x& -x; }
void add(int x , int a , int n , ll* d)
{
while(x<=n)
{
d[x]+= a;
x+= lowbit(x);
}
}

ll query(int x , int n , ll* d)
{
ll res =0;
while(x>0)
{
res+= d[x];
x-= lowbit(x);
}
return res;
}

int findK(int k , ll* d)
{
int res = 0 , cnt = 0;
for(int i=20;i>=0;i--)
{
res+= 1<<i;
if(res>Max || cnt+d[res]>=k) res-= 1<<i;
else cnt+= d[res];
}
return res+1;
}

int main(int argc, char *argv[]) {

n = re(); k = re();
for(int i=1;i<=n;i++) a[i] = re() , Max =max(Max , a[i]);
for(int i=1;i<=n+1;i++) a[i]++;

int cnt = k;
ll res = 1e15 , sum = 0;
for(int i=1;i<=k;i++) add(a[i], 1, Max, d1) , add(a[i], a[i], Max, d2) , sum+= a[i];
do
{
int now = findK((k+1)/2, d1);
ll  m1 = query(now, Max, d1);
ll  m2 = query(now, Max, d2);
res = min(res , sum-2*m2+m1*now-(k-m1)*now);

sum-= a[cnt-k+1];
add(a[cnt-k+1], -1, Max, d1);
add(a[cnt-k+1], -a[cnt-k+1], Max, d2);

sum+= a[cnt+1];
add(a[cnt+1], 1, Max, d1);
add(a[cnt+1], a[cnt+1], Max, d2);
cnt++;
}while(cnt<=n);

printf("%lld\n" , res);
return 0;
}


其实就是滑动窗口 , 然后找一个区间的第K大啦……

具体实现方法类似于树上倍增的写法 , 一点点通过lowbit来逼近。 利用树状数组的存储值的特性可以办到。

网上这个题好像没有这个版本的代码 , 这玩意比较好写但是由于这是基于值的区间的 , 所以时间复杂度是O(105∗lg(106))所以 , 慢一些啦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  POI 树状数组