题目大意:
给n个闭区间,求每个闭区间是多少个其他闭区间的真子集。
这一题先不考虑有相同闭区间的情况。
i区间是j区间的真子集,则有Ej <= Ei 且 Si <= Sj
所以可以将这个n个区间按照 “若Y大则大,若Y相同则X小的大” 的规则从大到小排序
bool operator < (const cow &a, const cow &b)
{
if (a.y == b.y)
return a.x < b.x;
return a.y > b.y;
}
然后对于每一个区间a[i]
其被另外h[1] + h[2] + h[3] + .... + h[a[i].x-1] + h[a[i].x] 个区间包含
然后更新h数组,h[a[i].x] ++;
for (i=2; i<=n; i++)
{
if (a[i].x == a[i-1].x && a[i].y == a[i-1].y)
ans[a[i].id] = ans[a[i-1].id];
else
{
ans[a[i].id] = query(a[i].x);
}
updata(a[i].x, 1);
}
我的全部代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string.h>
#include <string>
using namespace std;
class cow
{
public:
int x, y, id;
};
bool operator < (const cow &a, const cow &b)
{
if (a.y == b.y)
return a.x < b.x;
return a.y > b.y;
}
const int MAXN = 1e5+100;
int h[MAXN], ans[MAXN];
cow a[MAXN];
int n;
int lowbit(int x)
{
return x & (-x);
}
int query(int x)
{
int ans = 0;
while (x > 0)
{
ans += h[x];
x -= lowbit(x);
}
return ans;
}
void updata(int x, int val)
{
while (x < MAXN)
{
h[x] += val;
x += lowbit(x);
}
}
int main()
{
int i, x, y;
while (scanf("%d",&n))
{
if (n == 0)
break;
for (i=1; i<=n; i++)
{
scanf("%d%d",&x,&y);
a[i].x = x+1;
a[i].y = y+1;
a[i].id = i;
}
memset(h, 0, sizeof(h));
sort(a+1, a+n+1);
updata(a[1].x, 1);
ans[a[1].id] = 0;
for (i=2; i<=n; i++)
{
if (a[i].x == a[i-1].x && a[i].y == a[i-1].y)
ans[a[i].id] = ans[a[i-1].id];
else
{
ans[a[i].id] = query(a[i].x);
}
updata(a[i].x, 1);
}
for (i=1; i<n; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[n]);
}
return 0;
}