这里写自定义目录标题
题目地址: http://poj.org/problem?id=2352
思路:
题目要求的是每个等级的星星有几颗,那就需要先求出每颗行星的等级。
根据题目内容,每颗星星的等级,是X坐标和Y坐标均小于等于自身坐标的星星数量。
每颗星星的等级都需要算,那就存在计算先后的问题。
那么,对于某一颗星,只要确保在计算它的等级的时候,已经计算的星星都不在这颗行星右侧(已经计算的星星的X坐标都小于等于当前星星的X坐标),那就只需要看在这些星星中,有多少颗星的Y坐标小于等于当前星的,就可以了。
坐标取值范围为【0,3.2万】,则可以使用IndexTree,叶节点和坐标值对应。对于每头星,查找已经计算过的星中,有多少颗星的Y坐标小于等于当前星的,即可。
代码(IndexTree):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Main {
static int[][] S;
static int[] TREE;
static int N, K = 32768, LV;
static int[] ASW;
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
N = Integer.parseInt(st.nextToken());
S = new int[N][2];
ASW = new int[N];
TREE = new int[2 * K];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(bf.readLine());
S[i][0] = Integer.parseInt(st.nextToken()) + 1;
S[i][1] = Integer.parseInt(st.nextToken()) + 1;
}
Arrays.sort(S, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[1] == o2[1])
return o1[0] - o2[0];
return o1[1] - o2[1];
}
});
for (int i = 0; i < N; i++) {
LV = query(K, K + S[i][0]);
ASW[LV]++;
update(K + S[i][0]);
}
for (int i = 0; i < N; i++) {
System.out.println(ASW[i]);
}
}
public static void update(int idx) {
while (idx > 0) {
TREE[idx]++;
idx = idx >> 1;
}
}
public static int query(int s, int e) {
int res = 0;
while (s <= e) {
if ((s & 1) == 1)
res += TREE[s];
if ((e & 1) == 0)
res += TREE[e];
s = (s + 1) >> 1;
e = (e - 1) >> 1;
}
return res;
}
}
代码(BIT):
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static class Star {
int x, y;
Star(int x, int y) {
this.x = x;
this.y = y;
}
}
static int[] tree, asw;
static Star[] data;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
tree = new int[32005];
asw = new int[N];
data = new Star[N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
data[i] = new Star(Integer.parseInt(st.nextToken()) + 1, Integer.parseInt(st.nextToken()) + 1);
}
for (int i = 0; i < N; i++) {
asw[query(data[i].x)]++;
update(data[i].x);
}
for (int i = 0; i < N; i++) {
System.out.println(asw[i]);
}
}
public static void update(int i) {
while (i < 32005) {
tree[i] += 1;
i += lowbit(i);
}
}
public static int query(int i) {
int sum = 0;
while (i > 0) {
sum += tree[i];
i -= lowbit(i);
}
return sum;
}
public static int lowbit(int ids) {
return ids & (-ids);
}
}