poj2481
树状数组,难点在于处理相同区间,对于相同区间,只是把答案直接拷贝过来,并把其加入树状数组,不可以直接在树状数组中求和。
View Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 100005
struct Interval
{
int s, e;
int pos;
} interval[maxn];
int n;
int ar[maxn];
int ans[maxn];
bool operator <(const Interval &a, const Interval &b)
{
if (a.e == b.e)
return a.s < b.s;
return a.e > b.e;
}
int lowbit(int a)
{
return a & (-a);
}
void add(int i, int v)
{
for (; i < maxn; ar[i] += v, i += lowbit(i))
;
}
int sum(int i)
{
int s = 0;
for (; i > 0; s += ar[i], i -= lowbit(i))
;
return s;
}
int main()
{
//freopen("t.txt", "r", stdin);
while (scanf("%d", &n), n != 0)
{
memset(ar, 0, sizeof(ar));
for (int i = 0; i < n; i++)
{
scanf("%d%d", &interval[i].s, &interval[i].e);
interval[i].pos = i;
}
sort(interval, interval + n);
for (int i = 0; i < n; i++)
{
if (i != 0 && interval[i].s == interval[i - 1].s && interval[i].e
== interval[i - 1].e)
{
ans[interval[i].pos] = ans[interval[i - 1].pos];
}
else
ans[interval[i].pos] = sum(interval[i].s + 1);
add(interval[i].s + 1, 1);
}
printf("%d", ans[0]);
for (int i = 1; i < n; i++)
printf(" %d", ans[i]);
printf("\n");
}
return 0;
}