hdu5124(树状数组+离散化)
John has several lines. The lines are covered on the X axis. Let A is a point which is covered by the most lines. John wants to know how many lines cover A.
Input
The first line contains a single integer T(1≤T≤100)T(1≤T≤100)(the data for N>100N>100 less than 11 cases),indicating the number of test cases.
Each test case begins with an integer N(1≤N≤105)N(1≤N≤105),indicating the number of lines.
Next N lines contains two integers XiXi and Yi(1≤Xi≤Yi≤109)Yi(1≤Xi≤Yi≤109),describing a line.
Output
For each case, output an integer means how many lines cover A.
Sample Input
2 5 1 2 2 2 2 4 3 4 5 1000 5 1 1 2 2 3 3 4 4 5 5
Sample Output
3 1
//树状数组加离散化
//暑假学的树状数组和数据离散化又忘得差不多了。。。重新学了一遍。。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 100100;
int bit[N*2], a[N*2];
int n;
struct node
{
int v, u;
}s[N];
int sum(int i)
{
int s = 0;
while(i > 0)
{
s += bit[i];
i -= i & - i;
}
return s;
}
void add(int i, int x)
{
while(i <= 2 * n) //离散化后最多n*2个点
{
bit[i] += x;
i += i & - i;
}
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
memset(bit, 0, sizeof bit);
int k = 0;
for(int i = 0; i < n; i++)
{
scanf("%d%d", &s[i].v, &s[i].u);
a[k++] = s[i].v;
a[k++] = s[i].u;
}
sort(a, a + k);
for(int i = 0; i < n; i++) //离散化,用排序后的数的顺序代替。
{
s[i].v = lower_bound(a, a + k, s[i].v) - a + 1;
s[i].u = lower_bound(a, a + k, s[i].u) - a + 1;
}
for(int i = 0; i < n; i++)
{
add(s[i].v, 1);
add(s[i].u + 1, -1);
}
int res = -1;
for(int i = 1; i <= 2 * n; i++) //离散化后最多n*2个点
res = max(res, sum(i));
printf("%d\n", res);
}
return 0;
}
下面举个例子具体说说离散化的原理.