1
+ (* gia kathe thesi i,
2
+ sthn arxh: gnwrizume pws den mporei na exei nero an aristera tou den uparxei hill
3
+ efoson uparxei aristera tou hill, to i den mporei na einai megalutero apo to aristero kai deksi hill giati tha uparxei uperxilish.
4
+ uparxei h periptwsh na exw aristera ena hill, deksia ena hill to opoio na einai iso h mikrotero apo to aristero kai na uparxei ena deksia
5
+ >= apo ta aristerotero hill, opote na dhmiourgeitai mia "limnh" opou uparxei ena hill to opoio exei nero apo panw tou, deksia h kai aristera tou
6
+
7
+ pairnoume ena sequence apo N hills kai ta antistoixa height tous, opou stis koilades tous anamesa uparxei nero
8
+ thelume ton ogko tou nerou anamesa sta hills
9
+
10
+ sto position i, o ogkos tou nerou einai max to min height tou aristera kai deksia tou hill.
11
+
12
+ water = max(0,min(Left[i], Right[i]) - Height[i])
13
+
14
+ LeftHillI einai to hill me to megalutero height apo to i kai aristera tou
15
+ RightHillI einai to hill me to megalutero height apo to i kai deksia tou
16
+ *)
17
+
18
+ (* grafoume thn sunarthsh pou gia kathe position i, tha vriskei to max aristero tou *)
19
+ fun MaxHillLeft hs =
20
+ let
21
+ fun loop ([], _, acc) = List.rev acc
22
+ | loop (h::t, m, acc) =
23
+ let
24
+ val m' = Int.max(h, m) (* to megalutero height apo ta duo *)
25
+ in
26
+ loop(t, m', m'::acc)
27
+ end
28
+ in
29
+ loop (hs, 0 , [])
30
+ end
31
+
32
+ (* grafoume thn sunarthsh pou gia kathe position i, tha vriskei to max deksio tou *)
33
+ fun MaxHillRight hs =
34
+ let
35
+ val revHS = List.rev hs
36
+ fun loop ([], _, acc) = acc
37
+ | loop (h::t, m, acc) =
38
+ let
39
+ val m' = Int.max(h, m) (* to megalutero height apo ta duo *)
40
+ in
41
+ loop(t, m', m'::acc)
42
+ end
43
+ in
44
+ loop (revHS, 0 , [])
45
+ end
46
+
47
+ fun WaterTrapped ([],[],[]) total = total
48
+ | WaterTrapped (h::hs, l::ls, r::rs) total =
49
+ let
50
+ val water= Int.max(0 , Int.min(l, r) - h) (* to water pou uparxei sto i *)
51
+ in
52
+ WaterTrapped (hs, ls, rs) (total + water) (* prosthetoume to water sto total *)
53
+ end
54
+ | WaterTrapped _ _ = raise Fail " WaterTrapped: Invalid input"
55
+
56
+ fun WaterTrappedMain hs =
57
+ let
58
+ val leftHills = MaxHillLeft hs (* vriskei ta max aristera hills *)
59
+ val rightHills = MaxHillRight hs (* vriskei ta max deksia hills *)
60
+ in
61
+ WaterTrapped (hs, leftHills, rightHills) 0 (* ypologizei to water pou uparxei *)
62
+ end
63
+
64
+ fun readInts ins =
65
+ let
66
+ val line = valOf (TextIO.inputLine ins)
67
+ val toks = String.tokens Char.isSpace line
68
+ in
69
+ List.mapPartial Int.fromString toks
70
+ end
71
+
72
+
73
+ fun rain filename =
74
+ let
75
+ val ins = TextIO.openIn filename
76
+ val _ = TextIO.inputLine ins
77
+ val heights = readInts ins
78
+ val () = TextIO.closeIn ins
79
+ val result = WaterTrappedMain heights
80
+ in
81
+ print (Int.toString result ^ " \n " )
82
+ end
0 commit comments