标签:数据结构 acm algorithm poj 树状数组
| Time Limit: 3000MS | Memory Limit: 65536K | |
| Total Submissions: 13304 | Accepted: 4407 |
Description
Input
Output
Sample Input
3 1 2 0 3 3 4 0
Sample Output
1 0 0
Hint
Source
第一次用树状数组,不得不赞叹算法的奇妙啊,,太神奇了!!!!
我还是这么弱。。还得继续努力咯!!!!
题意给出每头牛的S与E,当Si<=Sj&&Ej<=Ei&&Ei-Si>Ej-Sj 说明i牛比j牛强壮,找出比i(1...n)强壮的牛的个数
思路:树状数组,将E[]升序排列,如果E相同则S[]降序排列,注意点就是坐标x会有0出现,所以坐标x+1,避免死循环
AC代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100005;
int C[maxn], ans[maxn], n, maxx;
struct node
{
int s, e, num;
}cow[maxn];
bool cmp(node a, node b)
{
if(a.e!=b.e) return a.e>b.e;
else return a.s<b.s;
}
int lowbit(int x)
{
return x&(-x);
}
int sum(int x)
{
int ret = 0;
while(x > 0)
{
ret += C[x]; x -= lowbit(x);
}
return ret;
}
void add(int x)
{
while(x <= maxx)
{
C[x] += 1; x += lowbit(x);
}
}
int main()
{
while(scanf("%d", &n), n)
{
memset(C, 0, sizeof(C));
memset(ans, 0, sizeof(ans));
maxx=0;
for(int i=1; i<=n; i++)
{
scanf("%d %d", &cow[i].s, &cow[i].e);
cow[i].s++, cow[i].e++;
cow[i].num=i;
maxx=max(maxx, cow[i].s);
}
sort(cow+1, cow+n+1, cmp);
for(int i=1; i<=n; i++)
{
add(cow[i].s);
if(cow[i].s==cow[i-1].s && cow[i].e==cow[i-1].e && i>1)
ans[cow[i].num] = ans[cow[i-1].num];
else
ans[cow[i].num] = sum(cow[i].s)-1;
}
for(int i=1; i<n; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[n]);
}
return 0;
}
标签:数据结构 acm algorithm poj 树状数组
原文地址:http://blog.csdn.net/u014355480/article/details/42193213