#include<iostream>
#include<cstring>
#include<cstdio>
#define N 8000
#define M 20005
using namespace std;
int temp;
struct Seg
{
int L, R, color;
}seg[M], seg1[M];
void CreateTree(int n, int l, int r)
{
seg[n].L = l;
seg[n].R = r;
seg[n].color = -1;
if(l == r)
return ;
CreateTree(n * 2, l, (l + r) / 2);
CreateTree(n * 2 + 1, (l + r) / 2 + 1, r);
}
void InsertSeg(int n, int l, int r, int color)
{
if(seg[n].L == l && seg[n].R == r)
{
seg[n].color = color;
return ;
}
else if(seg[n].color > -1)
{
seg[n * 2].color = seg[n].color;
seg[n * 2 + 1].color = seg[n].color;
seg[n].color = -1;
}
int mid = (seg[n].L + seg[n].R) / 2;
if(r <= mid)
InsertSeg(n * 2, l, r, color);
else if(l >= mid + 1)
InsertSeg(n * 2 + 1, l, r, color);
else
{
InsertSeg(n * 2, l, mid, color);
InsertSeg(n * 2 + 1, mid + 1, r, color);
}
}
void Count(int n, int l, int r)
{
if(seg[n].L == l && seg[n].R == r && seg[n].color > -1)
{
seg1[temp].L = l;
seg1[temp].R = r;
seg1[temp ++].color = seg[n].color;
//printf("%d %d %d\n", l, r, n);
return ;
}
if(r == l)
return ;
int mid = (seg[n].L + seg[n].R) / 2;
if(r <= mid)
Count(n * 2, l, r);
else if(l >= mid + 1)
Count(n * 2 + 1, l, r);
else
{
Count(n * 2, l, mid);
Count(n * 2 + 1, mid + 1, r);
}
}
int main()
{
int n, l, r, c;
while(scanf("%d", &n) != EOF)
{
CreateTree(1, 1, N);
for(int i = 0; i < n; ++ i)
{
cin >> l >> r >> c;
InsertSeg(1, l + 1, r, c);
}
temp = 0;
Count(1, 1, N);
int total[N + 5];
memset(total, 0, sizeof(total));
total[seg1[0].color] ++;
for(int i = 1; i < temp; ++ i)
{
if(seg1[i].color != seg1[i - 1].color || seg1[i].L > seg1[i - 1].R + 1)
total[seg1[i].color] ++;
}
for(int i = 0; i <= N; ++ i)
{
if(total[i])
printf("%d %d\n", i, total[i]);
}
printf("\n");
}
return 0;
}
学习线段树以后就去找题目做了,发现自己做还是很勉强,最后还是参考了解题报告才做出来的。原来没有理解的是Insert的时候为什么起点+1了 终点却不动,想了好久才明白线段树里存的是线段而不是点,而线段的数量比点少一个,所以终点不用+1。 要继续努力下去,认真做题。