In fact, it's very clear what blocks are.
The operation of a sequence is O(mn), so each n √ is divided into a segment, which is divided into n √ segments. Then, when we operate, for the direct single point violent modification within a segment, the cross segment segment is transferred by segment, so the complexity of each operation is reduced to O(n √).
It's a very simple idea. It's about how to realize it.
Building block
First, we find the number of blocks bct = (int)sqrt(n)
Then use the block array to record a certain element in the next block to realize:
block[i] = (i - 1) / bct + 1
And then it's done
Interval modification
Some violent changes in the block, what about the fast ones? We can build a similar line segment tree lazy array to maintain the situation of each block.
void update(int l, int r, int x) {
for(int i = l; i <= min(r, block[l] * bct); ++i)
a[i] += x;
if(block[l] != block[r]) {
for(int i = block[l] + 1; i <= block[r] - 1; ++i)
lazy[i] += x;
for(int i = (block[r] - 1) * bct + 1; i <= r; ++i)
a[i] += x;
}
}
Single point query
As there is no need to put the mark down, it is very comfortable.
int query(int x) {
return a[x] + lazy[block[x]];
}
Template Title: HDU1556
Although T, let's be a template (x)
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
inline void read(int &x) {
x = 0; char c = getchar();
while(!isdigit(c)) c = getchar();
while(isdigit(c)) x = x * 10 + c - '0', c = getchar();
}
#define MAXN 50003
int n, bct, m;
int a[MAXN], lazy[MAXN], block[MAXN];
void update(int l, int r, int x) {
for(int i = l; i <= min(r, block[l] * bct); ++i)
a[i] += x;
if(block[l] != block[r]) {
for(int i = block[l] + 1; i <= block[r] - 1; ++i)
lazy[i] += x;
for(int i = (block[r] - 1) * bct + 1; i <= r; ++i)
a[i] += x;
}
}
int query(int x) {
return a[x] + lazy[block[x]];
}
int main() {
while(cin>>n) {
if(n == 0) break;
memset(a, 0, sizeof a);
memset(block, 0, sizeof block);
memset(lazy, 0, sizeof lazy);
bct = (int)sqrt(n);
for(int i = 1; i <= n; ++i) block[i] = (i - 1) / bct + 1;
//read(m);
int cmd, l, r, x;
for(int i = 1; i <= n; ++i) {
read(l), read(r);
update(l, r, 1);
}
for(int i = 1; i <= n; ++i) cout<<query(i)<<" ";
}
return 0;
}