Cows poj2481 树状数组应用-CSDN博客

47 阅读1分钟

在纸上写写画画可以理解

#define _CRT_SECURE_NO_WARNINGS
//这就类似于会场安排,求区间的真子集 
#include <cstdio> 
#include <cstring>
#include <algorithm>
#define N 100007
using namespace std;
int bit[N], n;
int cnt[N];//第i条线段是多少条线段的真子集 
struct Cows {
	int s, e;
	int idx;
	bool operator < (const Cows rhs) const {
		if (e == rhs.e)
			return s < rhs.s;
		return e > rhs.e; //e大的排在前面 
	}
	bool operator == (const Cows rhs) const {
		return (s == rhs.s && e == rhs.e);
	}
}cow[N];
inline int lowbit(int x) {
	return x & (-x);
}
void add(int pos, int val) {
	while (pos <= n) {
		bit[pos] += val;
		pos += lowbit(pos);
	}
}
int sum(int pos) {
	int res = 0;
	while (pos > 0) {
		res += bit[pos];
		pos -= lowbit(pos);
	}
	return res;
}
int main()
{
	while (~scanf("%d", &n) && n) {
		for (int i = 1; i <= n; ++i) {
			scanf("%d%d", &cow[i].s, &cow[i].e);
			cow[i].s++; //因为存在0
			cow[i].e++;
			cow[i].idx = i;
		}
		sort(cow + 1, cow + n + 1);
		memset(bit, 0, sizeof bit);
		memset(cnt, 0, sizeof cnt);
		cnt[cow[1].idx] = 0;
		add(cow[1].s, 1); 
		for (int i = 2; i <= n; ++i) {
			if (cow[i] == cow[i - 1])
				cnt[cow[i].idx] = cnt[cow[i - 1].idx];
			else
				cnt[cow[i].idx] = sum(cow[i].s);
			add(cow[i].s, 1);//加的是1
		}
		printf("%d", cnt[1]);
		for (int i = 2; i <= n; ++i) {
			printf(" %d", cnt[i]);
		}
		puts("");

	}

	return 0;
}
/*
3
1 2
0 3
3 4
*/


\