Skip to content

Commit c967058

Browse files
committed
Init.
1 parent d30e6cb commit c967058

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

segtree.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#encoding:utf-8
2+
#Created by Liang Sun on May, 6, 2013
3+
class SegmentTree(object):
4+
def _init(self, start, end):
5+
self.data[(start, end)] = 0
6+
if start < end:
7+
mid = start + (end - start) / 2
8+
self._init(start, mid)
9+
self._init(mid+1, end)
10+
11+
def __init__(self, start, end):
12+
self.start = start
13+
self.end = end
14+
self.data = {}
15+
self._init(start, end)
16+
17+
def add(self, start, end, weight):
18+
if start < self.start or end > self.end:
19+
return False
20+
self._add(start, end, weight, self.start, self.end)
21+
return True
22+
23+
def _add(self, start, end, weight, in_start, in_end):
24+
if in_start == in_end:
25+
self.data[(in_start, in_end)] += weight
26+
return
27+
28+
mid = in_start + (in_end - in_start) / 2
29+
if mid >= end:
30+
self._add(start, end, weight, in_start, mid)
31+
elif mid+1 <= start:
32+
self._add(start, end, weight, mid+1, in_end)
33+
else:
34+
self._add(start, mid, weight, in_start, mid)
35+
self._add(mid+1, end, weight, mid+1, in_end)
36+
self.data[(in_start, in_end)] = max(self.data[(in_start, mid)], self.data[(mid+1, in_end)])
37+
38+
def query(self, start, end):
39+
return self._query(start, end, self.start, self.end)
40+
41+
def _query(self, start, end, in_start, in_end):
42+
if start == in_start and end == in_end:
43+
ans = self.data[(start, end)]
44+
else:
45+
mid = in_start + (in_end - in_start) / 2
46+
if mid >= end:
47+
ans = self._query(start, end, in_start, mid)
48+
elif mid+1 <= start:
49+
ans = self._query(start, end, mid+1, in_end)
50+
else:
51+
ans = max(self._query(start, mid, in_start, mid),
52+
self._query(mid+1, end, mid+1, in_end))
53+
#print start, end, in_start, in_end, ans
54+
return ans

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy