還注意的是建樹每次都是[1,8000]。
import java.util.Arrays;
import java.util.Scanner;
public class Main_ZOJ1610 {
static int[] color = new int[8005<<2];
static int[] cnt = new int[8005];
static int tcolor;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
tcolor = -1;
Arrays.fill(color, -1);
Arrays.fill(cnt, 0);
int n = sc.nextInt();
for(int i=1;i<=n;i++) {
int x1 = sc.nextInt();
int x2 = sc.nextInt();
int c = sc.nextInt();
update(x1+1,x2,c,1,8000,1); //更新的是區間(x1,x2] x1+1變成更新閉區間[x1+1,x2]
}
query(1,8000,1); //單點查詢
for(int i=0;i<=8000;i++) {
if(cnt[i]!=0) {
System.out.println(i+" "+cnt[i]);
}
}
System.out.println();
}
}
public static void update(int l,int r,int c,int L,int R,int root) {
if(l<=L&&R<=r) {
color[root] = c;
return;
}
pushdown(root);
int m = (L+R)>>1;
if(l<=m)
update(l,r,c,L,m,root<<1);
if(r>m)
update(l,r,c,m+1,R,root<<1|1);
}
public static void query(int l,int r,int root) {
if(l==r) {
if(color[root]!=-1&&color[root]!=tcolor) { //color[root]!=tcolor 說明是另一種顏色的開端
cnt[color[root]]++;
}
tcolor = color[root]; //記錄某一段的顏色
return;
}
pushdown(root);
int m = (l+r)>>1;
query(l,m,root<<1);
query(m+1,r,root<<1|1);
}
public static void pushdown(int root) {
if(color[root]!=-1) {
color[root<<1] = color[root<<1|1] = color[root];
color[root] = -1;
}
}
}