BZOJ 3289 Mato的文件管理
莫队 + 树状数组
先离散化,把值域离散出来。
每次莫队指针移动的时候,用树状数组维护该范围的值域即可。
具体来说,如果有一个数在左边加入(删除),就用树状数组查询比他小的数,右边同理,查询比他大的数就行了。和逆序对差不多的感觉。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 50005;
int t[N], a[N], b[N], n, q, k, s, ans, res[N];
struct Query{
int l, r, block, id;
bool operator < (const Query &rhs) const {
return (block ^ rhs.block) ? l < rhs.l : (block & 1) ? r < rhs.r : r > rhs.r;
}
}query[N];
void add(int index, int i){
for(; index <= k; index += lowbit(index))
t[index] += i;
}
int response(int index){
int ret = 0;
for(; index; index -= lowbit(index))
ret += t[index];
return ret;
}
int main(){
n = read();
for(int i = 1; i <= n; i ++) b[i] = a[i] = read();
sort(b + 1, b + n + 1);
k = (int)(unique(b + 1, b + n + 1) - b - 1);
for(int i = 1; i <= n; i ++){
a[i] = (int)(lower_bound(b + 1, b + k + 1, a[i]) - b);
}
q = read(), s = (int)sqrt(n);
for(int i = 1; i <= q; i ++){
query[i].l = read(), query[i].r = read();
query[i].id = i, query[i].block = (query[i].l - 1) / s + 1;
}
int l = 1, r = 0;
sort(query + 1, query + q + 1);
for(int i = 1; i <= q; i ++){
int curL = query[i].l, curR = query[i].r;
while(l < curL) add(a[l], -1), ans -= response(a[l] - 1), l ++;
while(r < curR) r ++, add(a[r], 1), ans += r - l + 1 - response(a[r]);
while(l > curL) l --, add(a[l], 1), ans += response(a[l] - 1);
while(r > curR) add(a[r], -1), ans -= r - l - response(a[r]), r --;
res[query[i].id] = ans;
}
for(int i = 1; i <= q; i ++){
printf("%d\n", res[i]);
}
return 0;
}