今天起来的比较晚。。

同学问我看没看过线段树,我说看过,她让我做做今天的一日一题--zoj1610

线段树是去年暑假学的,快一年了,都没怎么看过,幸好前两天看了自己的一个模板,然后今天仍然记忆尤新。。

11点多开始敲代码,中间改了又改, 最后终于在2点时候搞定了。。

这个题目需要注意两点,

由于是对线段进行的操作,所以需要访问到所有的线段,建树的时候需要注意一下,

 maketree(begin,tree[step].mid,2*step);
 maketree(tree[step].mid,end,2*step+1);

以前都是对点进行操作的,然后下面那行就是maketree(tree[step].mid+1,end,2*step+1);

另外一点就是在更新了以后求每种颜色有多少段。。

如果color【1,3】=1;color【3,4】=1; 颜色为1的就只有一段【1,4】;

对于这种情况,我加了个visit数组。。

View Code
1 # include<stdio.h>
2  struct node{
3 int first,last,mid;
4 int color;
5 }tree[8005*4];
6 int s[8005],visit[8005];
7 void maketree(int begin,int end,int step)
8 {
9 tree[step].first=begin;
10 tree[step].last=end;
11 tree[step].mid=(begin+end)/2;
12 tree[step].color=-1;
13 if(end-begin == 1) return;
14 maketree(begin,tree[step].mid,2*step);
15 maketree(tree[step].mid,end,2*step+1);
16 /*这个地方需要注意,不能写成maketree(tree[step].mid+1,end,2*step+1);因为这个题是线段,必须把每条线段都给访问到*/
17 }
18 void change(int begin,int end,int c,int step)
19 {
20 if(tree[step].color==c) return;
21 if(tree[step].first==begin && tree[step].last==end)
22 {
23 tree[step].color=c;
24 return;
25 }
26 if(tree[step].color!=-1) {tree[2*step].color=tree[step].color;tree[2*step+1].color=tree[step].color;tree[step].color=-1;}
27 if(end<=tree[step].mid) change(begin,end,c,2*step);
28 else if(begin>=tree[step].mid) change(begin,end,c,2*step+1);
29 else
30 {
31 change(begin,tree[step].mid,c,2*step);
32 change(tree[step].mid,end,c,2*step+1);
33 }
34 }
35 void queue(int begin,int end,int step)
36 {
37 if(tree[step].color!=-1)
38 {
39 if(visit[begin]!=tree[step].color) {visit[end]=tree[step].color; s[tree[step].color]++;}
40 else visit[end]=tree[step].color;
41 return;
42 }
43 if(end - begin == 1) return;
44 queue(begin,tree[step].mid,2*step);
45 queue(tree[step].mid,end,2*step+1);
46 }
47 int main()
48 {
49 int i,n,x1,x2,c;
50 while(scanf("%d",&n)!=EOF)
51 {
52 maketree(0,8000,1);
53 for(i=1;i<=n;i++)
54 {
55 scanf("%d%d%d",&x1,&x2,&c);
56 if(x1==x2) continue;
57 change(x1,x2,c,1);
58 }
59 for(i=0;i<=8000;i++)
60 {
61 s[i]=0;
62 visit[i]=-1;
63 }
64 queue(0,8000,1);
65 for(i=0;i<=8000;i++)
66 if(s[i]!=0)
67 {
68 printf("%d %d\n",i,s[i]);
69 }
70 printf("\n");
71 }
72 return 0;
73 }
posted on 2011-03-26 15:02  奋斗青春  阅读(470)  评论(0编辑  收藏  举报