tyvj P1039 忠诚2——线段树实现动态查询区间极值

    本来想给出一个链接,tyvjp1039忠诚2,大家自己找一下吧。这个问题很明显是区间极值问题,而且是动态的,这样就不能用RMQ了。线段树是一个比较好的选择。而且我发现一个问题,从前以为线段树之类的东西代码比较死,基本上都一样,其实我错了,越是高级的数据结构写法往往越活,变通性很强。只可惜此生无缘noi啦,这能自己虐一些简单的题目找找爽啦!悲剧呀!

 

  
    
1 type
2 ji =^ rec;
3 rec = record
4 l,r,min:longint;
5 lson,rson:ji;
6 end;
7
8 var
9 a:ji;
10 b:array[ 0 .. 100000 ] of longint;
11 i,j,x,y,m,n:longint;
12
13 function minn(x,y:longint):longint;
14 begin
15 if x < y then exit(x);
16 exit(y);
17 end;
18
19 procedure build(var a:ji; l,r:longint);
20 var
21 mid:longint;
22 begin
23 new (a);
24 a ^ .l: = l;
25 a ^ .r: = r;
26 mid: = (l + r) >> 1 ;
27 if l = r then
28 begin
29 a ^ .min: = b[l];
30 exit;
31 end;
32 build(a ^ .lson,l,mid);
33 build(a ^ .rson,mid + 1 ,r);
34 a ^ .min: = minn(a ^ .lson ^ .min,a ^ .rson ^ .min);
35 end;
36
37 function find(a:ji; l,r:longint):longint;
38 var
39 mid,k:longint;
40 begin
41 if (l <= a ^ .l)and(r >= a ^ .r) then exit(a ^ .min);
42 mid: = (a ^ .l + a ^ .r) >> 1 ; k: = maxlongint;
43 if mid >= l then k: = minn(k,find(a ^ .lson,l,r));
44 if mid < r then k: = minn(k,find(a ^ .rson,l,r));
45 exit(k);
46 end;
47
48 procedure change(var a:ji; x,y:longint);
49 var
50 mid:longint;
51 begin
52 if (x = a ^ .l)and(x = a ^ .r) then
53 begin
54 a ^ .min: = y;
55 exit;
56 end;
57 mid: = (a ^ .l + a ^ .r) >> 1 ;
58 if mid >= x then change(a ^ .lson,x,y);
59 if mid < x then change(a ^ .rson,x,y);
60 a ^ .min: = minn(a ^ .lson ^ .min,a ^ .rson ^ .min);
61 end;
62
63 begin
64 readln(n,m);
65 for i: = 1 to n do read(b[i]);
66 build(a, 1 ,n);
67 for i: = 1 to m do
68 begin
69 readln(j,x,y);
70 if j = 1 then write(find(a,x,y), ' ' )
71 else change(a,x,y);
72 end;
73 end.

你可能感兴趣的:(线段树)