├── .gitignore ├── ALLERGY ├── input.txt ├── markers_ALLERGY.py └── output.txt ├── ARCTIC └── free-lunch_ARCTIC.py ├── ASYMTILING ├── .gitkeep ├── ASYMTILING_JK.py ├── in.txt └── returns_asymtiling.py ├── BISHOPS ├── input.txt └── markers_BISHOPS.py ├── BLOCKGAME ├── cjm9236_BLOCKGAME.cpp └── cjm9236_BLOCKGAME.py ├── BOARDCOVER └── .gitkeep ├── BOARDCOVER2 └── rlakim5521_boardcover2.py ├── BRACKETS2 ├── free-lunch_BRACKETS2.py └── free-lunch_BRACKETS2_UnitTest.py ├── CANADATRIP ├── free-lunch_CANADATRIP.py └── free-lunch_CANADATRIP_Unittest.py ├── CHILDRENDAY ├── free-lunch_CHILDRENDAY.py └── free-lunch_CHILDRENDAY_Unittest.py ├── CLOCKSYNC └── .gitkeep ├── DRAGON ├── cccc612_dragon.py ├── input.txt ├── markers_DRAGON.py ├── output.txt └── rlakim5521_dragon.py ├── DRUNKEN ├── drunken_rlakim5521.py ├── free-lunch_DRUNKEN.cpp └── free-lunch_DRUNKEN.py ├── FANMEETING └── claire_fanmeeting.py ├── FENCE ├── .gitkeep └── cjm9236_fence.py ├── FIRETRUCKS ├── input.txt └── markers_FIRETRUCKS.py ├── FORTRESS ├── input.txt ├── markers_FORTRESS.py └── output.txt ├── GALLERY ├── free-lunch_GALLERY.py ├── free-lunch_GALLERY_Unittest.py ├── rlakim5521_gallery.py └── rlakim5521_gallery_jongman.py ├── ITES ├── free-lunch_ITES.py └── rlakim5521_ites.cpp ├── JAEHASAFE ├── README.md ├── img_1.png ├── j2h_JaeHaSafe.py ├── j2h_JaeHaSafeTest.py └── rlakim5521_jaehasafe.cpp ├── JLIS ├── .gitkeep ├── JLIS.cpp ├── JLIS.py ├── cjm9236_JLIS.py └── in.txt ├── JOSEPHUS └── free-lunch_JOSEPHUS.py ├── LAN ├── input.txt └── markers_LAN.py ├── LUNCHBOX ├── free-lunch_LUNCHBOX.py ├── input.txt ├── markers_LUNCHBOX.py ├── output.txt ├── returns_lunchbox.py └── rlakim5521_lunchbox.py ├── MORDOR ├── rlakim5521_mordor.java ├── rlakim5521_mordor_bruteforce.py ├── rlakim5521_mordor_rangeminimumquery └── rlakim5521_mordor_redblacktree ├── NERD2 └── rlakim5521_nerd2.py ├── NUMB3RS ├── cccc612_numb3rs.py ├── in.txt ├── input.txt ├── output.txt ├── returns_numb3rs.py └── rlakim5521_numb3rs.py ├── NUMBERGAME ├── cjm9236_NUMBERGAME.py ├── input.txt ├── markers_NUMBERGAME.py └── output.txt ├── PACKING ├── rlakim5521_packing.py └── rlakim5521_packing_jk.py ├── PI ├── .gitkeep ├── cjm9236_PI.cpp └── cjm9236_PI.py ├── POLY ├── .gitkeep ├── POLY_JK.py ├── in.txt ├── jonnung_poly.py ├── returns_poly.cpp └── returns_poly.py ├── POTION ├── j2h_Potion.py ├── j2h_PotionTest.py └── rlakim5521_potion.py ├── PROMISES ├── free-lunch_PROMISES.cpp └── free-lunch_PROMISES.py ├── QUADTREE ├── .gitkeep ├── cjm9236_quadtree.py ├── jonnung_quadtree.py └── jonnung_quadtree_RTE.py ├── QUANTIZE ├── .gitkeep ├── cjm9236_QUANTIZE.py ├── input.txt ├── jonnung_quantize_RTE.py └── output.txt ├── RATIO ├── input.txt ├── markers_RATIO.py ├── output.txt └── rlakim5521_ratio.py ├── README.md ├── ROUTING └── free-lunch_ROUTING.py ├── RUNNINGMEDIAN └── rlakim5521_runningmedian.py ├── SORTGAME ├── free-lunch_SORTGAME.py └── free-lunch_SORTGAME_Unittest.py ├── STRJOIN ├── j2h_StrJoin.py ├── j2h_StrJoinTest.py ├── returns_strjoin.py └── rlakim5521_strjoin.py ├── SUSHI └── free-lunch_SUSHI.py ├── TIMETRIP └── free-lunch_TIMETRIP.py ├── TPATH ├── free-lunch_TPATH.cpp └── free-lunch_TPATH.py ├── TRAVERSAL └── rlakim5521_traversal.py ├── TREASURE └── rlakim5521_treasure.py └── WILDCARD └── .gitkeep /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Vim template 3 | [._]*.s[a-w][a-z] 4 | [._]s[a-w][a-z] 5 | *.un~ 6 | Session.vim 7 | .netrwhist 8 | *~ 9 | 10 | 11 | ### Windows template 12 | # Windows image file caches 13 | Thumbs.db 14 | ehthumbs.db 15 | 16 | # Folder config file 17 | Desktop.ini 18 | 19 | # Recycle Bin used on file shares 20 | $RECYCLE.BIN/ 21 | 22 | # Windows Installer files 23 | *.cab 24 | *.msi 25 | *.msm 26 | *.msp 27 | 28 | # Windows shortcuts 29 | *.lnk 30 | 31 | 32 | ### IPythonNotebook template 33 | # Temporary data 34 | .ipynb_checkpoints/ 35 | 36 | 37 | ### Python template 38 | # Byte-compiled / optimized / DLL files 39 | __pycache__/ 40 | *.py[cod] 41 | *$py.class 42 | 43 | # C extensions 44 | *.so 45 | 46 | # Distribution / packaging 47 | .Python 48 | env/ 49 | build/ 50 | develop-eggs/ 51 | dist/ 52 | downloads/ 53 | eggs/ 54 | .eggs/ 55 | lib/ 56 | lib64/ 57 | parts/ 58 | sdist/ 59 | var/ 60 | *.egg-info/ 61 | .installed.cfg 62 | *.egg 63 | 64 | # PyInstaller 65 | # Usually these files are written by a python script from a template 66 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 67 | *.manifest 68 | *.spec 69 | 70 | # Installer logs 71 | pip-log.txt 72 | pip-delete-this-directory.txt 73 | 74 | # Unit test / coverage reports 75 | htmlcov/ 76 | .tox/ 77 | .coverage 78 | .coverage.* 79 | .cache 80 | nosetests.xml 81 | coverage.xml 82 | *,cover 83 | 84 | # Translations 85 | *.mo 86 | *.pot 87 | 88 | # Django stuff: 89 | *.log 90 | 91 | # Sphinx documentation 92 | docs/_build/ 93 | 94 | # PyBuilder 95 | target/ 96 | 97 | 98 | ### Eclipse template 99 | *.pydevproject 100 | .metadata 101 | .gradle 102 | bin/ 103 | tmp/ 104 | *.tmp 105 | *.bak 106 | *.swp 107 | *~.nib 108 | local.properties 109 | .settings/ 110 | .loadpath 111 | 112 | # Eclipse Core 113 | .project 114 | 115 | # External tool builders 116 | .externalToolBuilders/ 117 | 118 | # Locally stored "Eclipse launch configurations" 119 | *.launch 120 | 121 | # CDT-specific 122 | .cproject 123 | 124 | # JDT-specific (Eclipse Java Development Tools) 125 | .classpath 126 | 127 | # Java annotation processor (APT) 128 | .factorypath 129 | 130 | # PDT-specific 131 | .buildpath 132 | 133 | # sbteclipse plugin 134 | .target 135 | 136 | # TeXlipse plugin 137 | .texlipse 138 | 139 | 140 | ### OSX template 141 | .DS_Store 142 | .AppleDouble 143 | .LSOverride 144 | 145 | # Icon must end with two \r 146 | Icon 147 | 148 | # Thumbnails 149 | ._* 150 | 151 | # Files that might appear in the root of a volume 152 | .DocumentRevisions-V100 153 | .fseventsd 154 | .Spotlight-V100 155 | .TemporaryItems 156 | .Trashes 157 | .VolumeIcon.icns 158 | 159 | # Directories potentially created on remote AFP share 160 | .AppleDB 161 | .AppleDesktop 162 | Network Trash Folder 163 | Temporary Items 164 | .apdisk 165 | 166 | 167 | ### VirtualEnv template 168 | # Virtualenv 169 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 170 | .Python 171 | [Bb]in 172 | [Ii]nclude 173 | [Ll]ib 174 | [Ss]cripts 175 | pyvenv.cfg 176 | pip-selfcheck.json 177 | 178 | 179 | ### JetBrains template 180 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion 181 | 182 | *.iml 183 | 184 | ## Directory-based project format: 185 | .idea/ 186 | # if you remove the above rule, at least ignore the following: 187 | 188 | # User-specific stuff: 189 | # .idea/workspace.xml 190 | # .idea/tasks.xml 191 | # .idea/dictionaries 192 | 193 | # Sensitive or high-churn files: 194 | # .idea/dataSources.ids 195 | # .idea/dataSources.xml 196 | # .idea/sqlDataSources.xml 197 | # .idea/dynamic.xml 198 | # .idea/uiDesigner.xml 199 | 200 | # Gradle: 201 | # .idea/gradle.xml 202 | # .idea/libraries 203 | 204 | # Mongo Explorer plugin: 205 | # .idea/mongoSettings.xml 206 | 207 | ## File-based project format: 208 | *.ipr 209 | *.iws 210 | 211 | ## Plugin-specific files: 212 | 213 | # IntelliJ 214 | /out/ 215 | 216 | # mpeltonen/sbt-idea plugin 217 | .idea_modules/ 218 | 219 | # JIRA plugin 220 | atlassian-ide-plugin.xml 221 | 222 | # Crashlytics plugin (for Android Studio and IntelliJ) 223 | com_crashlytics_export_strings.xml 224 | crashlytics.properties 225 | crashlytics-build.properties 226 | 227 | # python idea directory ignore 228 | .idea/* 229 | -------------------------------------------------------------------------------- /ALLERGY/input.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 4 6 3 | cl bom dara minzy 4 | 2 dara minzy 5 | 2 cl minzy 6 | 2 cl dara 7 | 1 cl 8 | 2 bom dara 9 | 2 bom minzy 10 | 10 7 11 | a b c d e f g h i j 12 | 6 a c d h i j 13 | 3 a d i 14 | 7 a c f g h i j 15 | 5 b c f h i 16 | 3 b d g 17 | 4 b e g j 18 | 5 b c g h i2 19 | 4 6 20 | cl bom dara minzy 21 | 2 dara minzy 22 | 2 cl minzy 23 | 2 cl dara 24 | 1 cl 25 | 2 bom dara 26 | 2 bom minzy 27 | 10 7 28 | a b c d e f g h i j 29 | 6 a c d h i j 30 | 3 a d i 31 | 7 a c f g h i j 32 | 3 b d g 33 | 5 b c f h i 34 | 4 b e g j 35 | 5 b c g h i -------------------------------------------------------------------------------- /ALLERGY/markers_ALLERGY.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 2. 28. 5 | ''' 6 | 7 | import sys 8 | from _collections import defaultdict 9 | from collections import OrderedDict 10 | 11 | rl = lambda: sys.stdin.readline() 12 | 13 | 14 | class Allergy(): 15 | best = 987654321 16 | 17 | def __init__(self): 18 | self.dictionary = defaultdict(list) 19 | self.eater = {} 20 | 21 | def clear(self): 22 | self.dictionary.clear() 23 | self.eater.clear() 24 | self.best = 987654321 25 | 26 | def start(self): 27 | testCase = int(rl()) 28 | for tc in xrange(testCase): 29 | people_num, food_num = map(int, rl().strip().split()) 30 | people = rl().strip().split() 31 | for food_index in xrange(food_num): 32 | can_eat_people = rl().split() 33 | # print can_eat_people[1:] 34 | self.set_food_list(food_index, can_eat_people[1:]) 35 | self.dictionary = OrderedDict( 36 | sorted(self.dictionary.items(), key=lambda 37 | x: 38 | len(x[1]))) 39 | 40 | self.check(0) 41 | print self.best 42 | self.clear() 43 | 44 | def set_food_list(self, food_idx, people): 45 | for person in people: 46 | self.dictionary.setdefault(person, []).append(food_idx) 47 | 48 | def check(self, cnt): 49 | # 가지치기 50 | # print "cnt = {} , best = {}".format(cnt,self.best) 51 | if cnt >= self.best: return 52 | 53 | # 모든 사람들이 다 먹었다면 종료 54 | if not bool(self.dictionary): 55 | self.best = cnt 56 | return 57 | 58 | key = next(self.dictionary.iterkeys()) 59 | # print "key = {} ".format(key) 60 | # print key 61 | # print self.dictionary[key] 62 | 63 | # 먹은 음식 체크 64 | for food_idx in self.dictionary[key]: 65 | back = OrderedDict([(key, values) for key, values in 66 | self.dictionary.items() if food_idx in values]) 67 | for key in back.keys(): 68 | self.dictionary.pop(key) 69 | cnt += 1 70 | self.check(cnt) 71 | cnt -= 1 72 | self.dictionary.update(back) 73 | 74 | 75 | if __name__ == "__main__": 76 | # import cProfile 77 | allergy = Allergy() 78 | allergy.start() 79 | # cProfile.run('print allergy.start(); print') -------------------------------------------------------------------------------- /ALLERGY/output.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 3 -------------------------------------------------------------------------------- /ARCTIC/free-lunch_ARCTIC.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import collections 3 | 4 | # Visit all vetex using BFS 5 | def decision(stations, power): 6 | n = len(stations) 7 | q = collections.deque() 8 | 9 | visited = [False] * n 10 | q.append(0) 11 | visited[0] = True 12 | 13 | while q: 14 | here = q.pop() 15 | for there in xrange(n): 16 | if not visited[there]: 17 | dist = (stations[here][0]-stations[there][0])**2 + (stations[here][1]-stations[there][1])**2 18 | if dist <= power: 19 | visited[there] = True 20 | q.append(there) 21 | return all(visited) 22 | 23 | 24 | def solve(stations): 25 | n = len(stations) 26 | dist_list = set() 27 | 28 | # Calculate all distances 29 | for i in xrange(n): 30 | for j in xrange(n): 31 | if i == j: 32 | continue 33 | dist = (stations[i][0]-stations[j][0])**2 + (stations[i][1]-stations[j][1])**2 34 | dist_list.add(dist) 35 | 36 | # Sort distances 37 | dist_list = sorted(dist_list) 38 | low = 0 39 | high = len(dist_list) -1 40 | 41 | # Search a range of correct answer 42 | while high - low > 3: 43 | mid = int(round(low+high)/2) 44 | if decision(stations, dist_list[mid]): 45 | high = mid 46 | else: 47 | low = mid 48 | 49 | # Search correct answer in range 50 | for i in xrange(low, high+1): 51 | if decision(stations, dist_list[i]): 52 | return round(dist_list[i]**(0.5),2) 53 | 54 | if __name__ == "__main__": 55 | rl = lambda : sys.stdin.readline() 56 | 57 | for _ in xrange(int(rl())): 58 | stations = [] 59 | for _ in xrange(int(rl())): 60 | stations.append(map(float, rl().split())) 61 | 62 | print "{:.2f}".format(solve(stations)) 63 | -------------------------------------------------------------------------------- /ASYMTILING/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/ASYMTILING/.gitkeep -------------------------------------------------------------------------------- /ASYMTILING/ASYMTILING_JK.py: -------------------------------------------------------------------------------- 1 | # ASYMTILING 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | # Returns a list of all possible numbers of cases of tiles 5 | # when n is 1 to 100 6 | def getAllTiles(allTiles): 7 | for iter in range(2, 101): 8 | allTiles[iter] = allTiles[iter - 1] + allTiles[iter - 2] 9 | 10 | return allTiles 11 | 12 | # Returns a list of all possible numbers of cases of symmetric tiles 13 | # when n is 1 to 100 14 | def getSymmetricTiles(symmetricTiles): 15 | for iter in range(4, 101): 16 | symmetricTiles[iter] = symmetricTiles[iter - 2] + symmetricTiles[iter - 4] 17 | 18 | return symmetricTiles 19 | 20 | # Returns a list of all possible numbers of cases of non-symmetric tiles 21 | # when n is 1 to 100 22 | def getAsymmetricTiles(asymmetricTiles, allTiles, symmetricTiles): 23 | for iter in range(1, 101): 24 | asymmetricTiles[iter] = allTiles[iter] - symmetricTiles[iter] 25 | 26 | return asymmetricTiles 27 | 28 | # Caches for memoization 29 | asymmetricTiles = [0 for _ in range(101)] 30 | allTiles = [0 for _ in range(101)] 31 | symmetricTiles = [0 for _ in range(101)] 32 | 33 | 34 | # Sets initial values for allTiles 35 | allTiles[0] = 1 36 | allTiles[1] = 1 37 | 38 | # Gets all possible numbers of cases of tiles when n is 1 to 100 39 | allTiles = getAllTiles(allTiles) 40 | 41 | # Sets initial values for symmetricTiles 42 | symmetricTiles[0] = 1 43 | symmetricTiles[1] = 1 44 | symmetricTiles[2] = 2 45 | symmetricTiles[3] = 1 46 | 47 | # Gets all possible numbers of cases of symmetric tiles when n is 1 to 100 48 | symmetricTiles = getSymmetricTiles(symmetricTiles) 49 | 50 | # Gets all possible numbers of cases of non-symmetric tiles when n is 1 to 100 51 | asymmetricTiles = getAsymmetricTiles(asymmetricTiles, allTiles, symmetricTiles) 52 | 53 | # Main function 54 | if __name__ == "__main__": 55 | caseNumber = int(raw_input()) 56 | 57 | for iter in range(caseNumber): 58 | n = int(raw_input()) 59 | 60 | print (asymmetricTiles[n] % 1000000007) 61 | -------------------------------------------------------------------------------- /ASYMTILING/in.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 2 3 | 4 4 | 92 5 | -------------------------------------------------------------------------------- /ASYMTILING/returns_asymtiling.py: -------------------------------------------------------------------------------- 1 | 2 | gTileCount = [ int(0) for i in range(101) ] 3 | 4 | def getAllCount( aTileCount ) : 5 | global gTileCount 6 | 7 | if gTileCount[aTileCount] is not 0 : 8 | return gTileCount[aTileCount] 9 | 10 | gTileCount[aTileCount] = ( getAllCount( aTileCount-1 ) + getAllCount( aTileCount-2 ) ) 11 | 12 | return gTileCount[aTileCount] 13 | 14 | def getSymTilingCount( aTileCount ) : 15 | 16 | if aTileCount % 2 is 1 : 17 | return getAllCount( (aTileCount - 1) / 2 ) 18 | else : 19 | return ( getAllCount( aTileCount / 2 ) + getAllCount( (aTileCount-2) / 2 ) ) 20 | 21 | def getAsymTilingCount( aTileCount ) : 22 | return ( getAllCount( aTileCount ) - getSymTilingCount( aTileCount ) ) % 1000000007 23 | 24 | 25 | def solve() : 26 | 27 | global gTileCount 28 | 29 | # Base Data 30 | gTileCount[0] = 1 # fake 31 | gTileCount[1] = 1 32 | gTileCount[2] = 2 33 | 34 | sCount = input() 35 | 36 | for i in range( sCount ) : 37 | sTileCount = input() 38 | print getAsymTilingCount( sTileCount ) 39 | 40 | solve() 41 | -------------------------------------------------------------------------------- /BISHOPS/input.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 5 3 | *.*.. 4 | .*..* 5 | *.*** 6 | *.*.* 7 | .*.*. 8 | 8 9 | ..**.*.* 10 | **.***.* 11 | *.**...* 12 | .*.**.** 13 | *.**.*.* 14 | ..**.*.* 15 | ...*.*.* 16 | **.*.*.* 17 | 8 18 | *.*.*.*. 19 | .*.*.*.* 20 | *.*.*.*. 21 | .*.*.*.* 22 | *.*.*.*. 23 | .*.*.*.* 24 | *.*.*.*. 25 | .*.*.*.* -------------------------------------------------------------------------------- /BISHOPS/markers_BISHOPS.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 7. 31. 5 | ''' 6 | 7 | 8 | import sys 9 | 10 | rl = lambda : sys.stdin.readline() 11 | 12 | 13 | direction = [(-1,1), (1,1)] 14 | 15 | def input(): 16 | global board_size 17 | board_size = int(rl()) 18 | global board 19 | board = [ None ] * board_size 20 | for index in xrange(board_size): 21 | board[index] = list(rl().rstrip()) 22 | 23 | 24 | 25 | def define_line_number(edge, count): 26 | for dir in xrange(2): 27 | for y in xrange(board_size): 28 | for x in xrange(board_size): 29 | if board[y][x] == "." and edge[dir][y][x] == None: 30 | current_x, current_y = x, y 31 | while 0 <= current_x < board_size and 0 <= current_y < board_size \ 32 | and board[current_y][current_x] == ".": 33 | edge[dir][current_y][current_x] = count[dir] 34 | current_x += direction[dir][0] 35 | current_y += direction[dir][1] 36 | 37 | count[dir] += 1 38 | return edge, count 39 | 40 | 41 | 42 | def make_adj_matrix(edge): 43 | adj_matrix = [ [None] * 64 for x in xrange(64) ] 44 | for y in xrange(board_size): 45 | for x in range(board_size): 46 | if board[y][x] == ".": 47 | adj_matrix[ edge[0][y][x] ][ edge[1][y][x] ] = 1 48 | return adj_matrix 49 | 50 | 51 | def dfs(u_index, adj_matrix): 52 | if visited[u_index]: 53 | return False 54 | 55 | visited[u_index] = True 56 | 57 | for v_index in xrange(v): 58 | if adj_matrix[u_index][v_index]: 59 | if v_lines[v_index] == None or dfs(v_lines[v_index], adj_matrix): 60 | u_lines[u_index] = v_index 61 | v_lines[v_index] = u_index 62 | return True 63 | 64 | return False 65 | 66 | 67 | def bipartite_match(adj_matrix): 68 | global u_lines, v_lines 69 | u_lines = [ None ] * u 70 | v_lines = [ None ] * v 71 | size = 0 72 | global visited 73 | 74 | for u_index in xrange(u): 75 | visited = [ False ] * u 76 | if dfs(u_index, adj_matrix): 77 | size += 1 78 | 79 | return size 80 | 81 | 82 | def main(): 83 | for tc in xrange(int(rl())): 84 | 85 | # initalize 86 | # array[2][8][8] 87 | edge = [ [ [ None ] * 8 for x in xrange(8) ] for x in xrange(2) ] 88 | count = [0,0] 89 | 90 | input() 91 | 92 | edge, count = define_line_number(edge,count) 93 | 94 | global u, v 95 | u,v = count 96 | 97 | adj_matrix = make_adj_matrix(edge) 98 | 99 | print bipartite_match(adj_matrix) 100 | 101 | 102 | 103 | if __name__ == "__main__": 104 | main() -------------------------------------------------------------------------------- /BLOCKGAME/cjm9236_BLOCKGAME.cpp: -------------------------------------------------------------------------------- 1 | // BLOCKGAME problem 2 | // Author: JeongminCha (cjm9236@me.com) 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | std::vector strategy; 11 | char cache[1 << 25] = {-1, }; // 2^25-size 12 | const int L_block[4][3][2] = { 13 | {{0,0},{1,0},{1,1}}, 14 | {{0,0},{0,1},{1,1}}, 15 | {{0,0},{0,1},{-1,1}}, 16 | {{0,0},{1,0},{0,1}}, 17 | }; 18 | const int I_block[2][2][2] = { 19 | {{0,0},{1,0}}, 20 | {{0,0},{0,1}}, 21 | }; 22 | 23 | int make_board(char input[5][5]) { 24 | int idx_board = 0; 25 | for (int row = 0; row < 5; row++) { 26 | for (int col = 0; col < 5; col++) { 27 | idx_board *= 2; 28 | if (input[row][col] == '#') { 29 | idx_board += 1; 30 | } 31 | } 32 | } 33 | return idx_board; 34 | } 35 | 36 | int index(int x, int y) { 37 | return 1 << (x + y*5); 38 | } 39 | 40 | bool empty(int& idx_board, int x, int y) { 41 | return (x >= 0 && x < 5) && 42 | (y >= 0 && y < 5) && 43 | (idx_board & index(x,y)) == 0; 44 | } 45 | 46 | bool L_available(int& idx_board, int row, int col, int shape) { 47 | // Check the block can be put in the specified location. 48 | for (int i = 0; i < 3; i++) { 49 | int y = row + L_block[shape][i][0]; 50 | int x = col + L_block[shape][i][1]; 51 | if (!empty(idx_board, x, y)) { 52 | return false; 53 | } 54 | } 55 | // Add the block (by OR operation) 56 | for (int i = 0; i < 3; i++) { 57 | int y = row + L_block[shape][i][0]; 58 | int x = col + L_block[shape][i][1]; 59 | idx_board |= index(x,y); 60 | } 61 | return true; 62 | } 63 | 64 | bool I_available(int& idx_board, int row, int col, int shape) { 65 | // Check the block can be put in the specified location. 66 | for (int i = 0; i < 2; i++) { 67 | int y = row + I_block[shape][i][0]; 68 | int x = col + I_block[shape][i][1]; 69 | if (!empty(idx_board, x, y)) { 70 | return false; 71 | } 72 | } 73 | // Add the block (by OR operation) 74 | for (int i = 0; i < 2; i++) { 75 | int y = row + I_block[shape][i][0]; 76 | int x = col + I_block[shape][i][1]; 77 | idx_board |= index(x,y); 78 | } 79 | return true; 80 | } 81 | 82 | void L_pop(int& idx_board, int row, int col, int shape) { 83 | // Delete the block (by XOR operation) 84 | for (int i = 0; i < 3; i++) { 85 | int y = row + L_block[shape][i][0]; 86 | int x = col + L_block[shape][i][1]; 87 | idx_board ^= index(x,y); 88 | } 89 | } 90 | 91 | void I_pop(int& idx_board, int row, int col, int shape) { 92 | // Delete the block (by XOR operation) 93 | for (int i = 0; i < 2; i++) { 94 | int y = row + I_block[shape][i][0]; 95 | int x = col + I_block[shape][i][1]; 96 | idx_board ^= index(x,y); 97 | } 98 | } 99 | 100 | void construct_all_strategies() { 101 | for (int row = 0; row < 5; row++) { 102 | for (int col = 0; col < 5; col++) { 103 | int idx_board = 0; 104 | // processing L-shaped block 105 | for (int shape = 0; shape < 4; shape++) { 106 | if (L_available(idx_board, row, col, shape)) { 107 | strategy.push_back(idx_board); 108 | L_pop(idx_board, row, col, shape); 109 | } 110 | } 111 | // processing I-shaped block 112 | for (int shape = 0; shape < 2; shape++) { 113 | if (I_available(idx_board, row, col, shape)) { 114 | strategy.push_back(idx_board); 115 | I_pop(idx_board, row, col, shape); 116 | } 117 | } 118 | } 119 | } 120 | } 121 | 122 | // Returns True if there's a way to win in the current board condition. 123 | char check_winning_way(int idx_board) { 124 | char& ret = cache[idx_board]; 125 | if (ret != -1) { 126 | return ret; 127 | } 128 | ret = 0; 129 | // For every strategies about putting new block 130 | for (int i = 0; i < strategy.size(); i++) { 131 | int new_block = strategy[i]; 132 | // 1. new block is not overlapped with the existing blocks. 133 | // 2. failing is guranteed after the next new block is added. 134 | if ((new_block & idx_board) == 0 && 135 | !check_winning_way(new_block | idx_board)) { 136 | ret = 1; 137 | break; 138 | } 139 | } 140 | return ret; 141 | } 142 | 143 | int main() { 144 | construct_all_strategies(); 145 | int test_case = 0; 146 | std::cin >> test_case; 147 | while (test_case --) { 148 | char input[5][5]; 149 | memset(cache, -1, sizeof(cache)); 150 | for (int i = 0; i < 5; i++) { 151 | std::cin >> input[i]; 152 | } 153 | int idx_board = make_board(input); 154 | bool result = check_winning_way(idx_board); 155 | if (result > 0) { 156 | std::cout << "WINNING" << std::endl; 157 | } else { 158 | std::cout << "LOSING" << std::endl; 159 | } 160 | } 161 | return 0; 162 | } -------------------------------------------------------------------------------- /BLOCKGAME/cjm9236_BLOCKGAME.py: -------------------------------------------------------------------------------- 1 | # BLOCKGAME problem 2 | # Author: JeongminCha (cjm9236@me.com) 3 | 4 | cache = None 5 | strategy = [] 6 | 7 | L_block = [ 8 | [[0,0],[1,0],[1,1]], 9 | [[0,0],[0,1],[1,1]], 10 | [[0,0],[0,1],[-1,1]], 11 | [[0,0],[1,0],[0,1]] 12 | ] 13 | I_block = [ 14 | [[0,0],[1,0]], 15 | [[0,0],[0,1]] 16 | ] 17 | 18 | def initial_setting(): 19 | global strategy 20 | for row in range(5): 21 | for col in range(5): 22 | board = [0] 23 | # processing L block 24 | for shape in range(4): 25 | if L_available(board, row, col, shape): 26 | strategy.append(board[0]) 27 | L_pop(board, row, col, shape) 28 | # processing I block 29 | for shape in range(2): 30 | if I_available(board, row, col, shape): 31 | strategy.append(board[0]) 32 | I_pop(board, row, col, shape) 33 | 34 | def index(x, y): 35 | return int(2 ** (x + y*5)) 36 | 37 | def empty(board, x, y): 38 | if (x >= 0 and x < 5) and (y >= 0 and y < 5) and (board[0] & index(x,y)) == 0: 39 | return True 40 | else: 41 | return False 42 | 43 | # Checks if a 'L' block is available 44 | def L_available(board, p, q, shape): 45 | # Check the block can be put in the specified location. 46 | for i in range(3): 47 | x = q + L_block[shape][i][1] 48 | y = p + L_block[shape][i][0] 49 | if empty(board, x, y) is False: 50 | return False 51 | # Add the block (by OR operation) 52 | for i in range(3): 53 | x = q + L_block[shape][i][1] 54 | y = p + L_block[shape][i][0] 55 | board[0] |= index(x,y) 56 | return True 57 | 58 | # Checks if a 'I' block is available 59 | def I_available(board, p, q, shape): 60 | # Check the block can be put in the specified location. 61 | for i in range(2): 62 | x = q + I_block[shape][i][1] 63 | y = p + I_block[shape][i][0] 64 | if empty(board, x, y) is False: 65 | return False 66 | # Add the block (by OR operation) 67 | for i in range(2): 68 | x = q + I_block[shape][i][1] 69 | y = p + I_block[shape][i][0] 70 | board[0] |= index(x,y) 71 | return True 72 | 73 | # Pops the 'L' block 74 | def L_pop(board, p, q, shape): 75 | # Delete the block (by XOR operation) 76 | for i in range(3): 77 | x = q + L_block[shape][i][1] 78 | y = p + L_block[shape][i][0] 79 | board[0] ^= index(x,y) 80 | 81 | # Pops the 'I' block 82 | def I_pop(board, p, q, shape): 83 | # Delete the block (by XOR operation) 84 | for i in range(2): 85 | x = q + I_block[shape][i][1] 86 | y = p + I_block[shape][i][0] 87 | board[0] ^= index(x,y) 88 | 89 | # Returns True if there's a way to win in the current board condition. 90 | def check_winning_way(board): 91 | ret = cache[board[0]] 92 | if ret != -1: 93 | return ret 94 | ret = 0 95 | # For every strategies about putting new block 96 | for new_block in strategy: 97 | # 1. new block is not overlapped with the existing blocks. 98 | # 2. failing is guranteed after the new block is added. 99 | if ((new_block & board[0]) == 0) and \ 100 | (check_winning_way([new_block | board[0]]) <= 0): 101 | ret = 1 102 | break 103 | return ret 104 | 105 | # Returns the number meaning marked points in board 106 | def make_board(input): 107 | ret = 0 108 | for row in range(5): 109 | for col in range(5): 110 | ret *= 2 111 | if input[row][col] == '#': 112 | ret += 1 113 | return ret 114 | 115 | if __name__ == "__main__": 116 | initial_setting() 117 | 118 | for _ in range(int(raw_input())): 119 | cache = [-1] * (2 ** 25) 120 | input = [] 121 | for _ in range(5): 122 | input.append(list(raw_input())) 123 | 124 | result = check_winning_way([make_board(input)]) 125 | if result > 0: 126 | print("WINNING") 127 | else: 128 | print("LOSING") -------------------------------------------------------------------------------- /BOARDCOVER/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/BOARDCOVER/.gitkeep -------------------------------------------------------------------------------- /BOARDCOVER2/rlakim5521_boardcover2.py: -------------------------------------------------------------------------------- 1 | # int_boardCOVER2 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | global cache 5 | 6 | class BitMatrix: 7 | def __init__(self, matrix, row_size, col_size): 8 | self.matrix = matrix 9 | self.row_size = row_size 10 | self.col_size = col_size 11 | 12 | # TODO: Test 13 | def write(self, stream, start_row, start_col): 14 | self.matrix = self.matrix | ((stream << (start_row * self.col_size)) << start_col) 15 | return self 16 | 17 | # complete 18 | def read(self, length, start_row, start_col): 19 | extractor = 0 20 | for iter in xrange(length): 21 | extractor = (extractor << 1) | 1 22 | 23 | readStream = (self.matrix >> (self.col_size * start_row) >> start_col) & extractor 24 | return readStream 25 | 26 | # complete 27 | def compare(self, comparing): 28 | if(self.row_size == comparing.row_size 29 | and self.col_size == comparing.col_size 30 | and self.matrix == comparing.matrix): 31 | return True 32 | else: 33 | return False 34 | 35 | # TODO: We need write and read function. 36 | def resize(self, new_row_size, new_col_size): 37 | resizedMatrix = BitMatrix(0, new_row_size, new_col_size) 38 | 39 | # complete 40 | def rotate(self): 41 | res = 0 42 | for iter1 in xrange(self.col_size): 43 | for iter2 in xrange(self.col_size): 44 | res = res << 1 45 | res = res | self.read(1, iter2, self.col_size-iter1-1) 46 | return BitMatrix(res, self.row_size, self.col_size) 47 | 48 | # complete 49 | def reverseDiagonally(self): 50 | extractor = 0 51 | reversedBlock = 0 52 | for col in xrange(self.col_size): 53 | extractor = extractor << 1 54 | extractor = extractor | 1 55 | for row in xrange(self.row_size): 56 | originalLine = (self.matrix >> row * self.col_size) & extractor 57 | for col in xrange(self.col_size): 58 | reversedBlock = reversedBlock << 1 59 | reversedBlock = reversedBlock | ((originalLine >> col) & 1) 60 | return BitMatrix(reversedBlock, self.row_size, self.col_size) 61 | 62 | # complete 63 | def printMatrix(self): 64 | board = self.matrix 65 | for printed in xrange(self.row_size*self.col_size-1, -1, -1): 66 | if((board >> printed) & 1 == 1): 67 | print '#', 68 | else: 69 | print '.', 70 | if(printed % self.col_size == 0): 71 | print "" 72 | print "-----------------------------" 73 | 74 | # TODO: When two BitMatrixes have different size, comparing one have to be resized to compared one. 75 | def is_overlap(self, comparing): 76 | if(self.row_size == comparing.row_size and self.col_size == comparing.col_size): 77 | if(self.matrix & comparing.matrix != 0): 78 | return True 79 | else: 80 | return False 81 | 82 | # complete 83 | def overlap(self, overlapping): 84 | return BitMatrix(self.matrix | overlapping.matrix, self.row_size, self.col_size) 85 | 86 | # MAX_INDEX = pow(2, 50) 87 | # MASK = MAX_INDEX - 1 88 | 89 | def getMaxNumber(board, blocks, start_point, R, C): 90 | number = [0] 91 | for iter in xrange(start_point, (board.row_size - R)*board.col_size + (board.col_size - C + 1)): 92 | if(iter % board.col_size > (board.col_size - C)): 93 | continue 94 | if(not board.is_overlap(BitMatrix(blocks[0].matrix << iter,H,W))): 95 | nextMatrix = board.matrix | (blocks[0].matrix << iter) 96 | # if(cache[nextMatrix >> 50][nextMatrix & MASK] == -1): 97 | number.append(getMaxNumber(BitMatrix(nextMatrix, H, W), blocks, start_point + 1, R, C)+1) 98 | if(not board.is_overlap(BitMatrix(blocks[2].matrix << iter,H,W))): 99 | nextMatrix = board.matrix | (blocks[2].matrix << iter) 100 | # if(cache[nextMatrix >> 50][nextMatrix & MASK] == -1): 101 | number.append(getMaxNumber(BitMatrix(nextMatrix, H, W), blocks, start_point + 1, R, C)+1) 102 | 103 | for iter in xrange(start_point, (board.row_size - C)*board.col_size + (board.col_size - R + 1)): 104 | if(iter % board.col_size > (board.col_size - C)): 105 | continue 106 | if(not board.is_overlap(BitMatrix(blocks[1].matrix << iter,H,W))): 107 | nextMatrix = board.matrix | (blocks[1].matrix << iter) 108 | # if(cache[nextMatrix >> 50][nextMatrix & MASK] == -1): 109 | number.append(getMaxNumber(BitMatrix(nextMatrix, H, W), blocks, start_point + 1, R, C)+1) 110 | if(not board.is_overlap(BitMatrix(blocks[3].matrix << iter,H,W))): 111 | nextMatrix = board.matrix | (blocks[3].matrix << iter) 112 | # if(cache[nextMatrix >> 50][nextMatrix & MASK] == -1): 113 | number.append(getMaxNumber(BitMatrix(nextMatrix, H, W), blocks, start_point + 1, R, C)+1) 114 | 115 | # cache[board.matrix >> 50][board.matrix & MASK] = max(number) 116 | return max(number) 117 | 118 | # Main function 119 | if __name__ == "__main__": 120 | # cache = [[-1 for col in xrange(MAX_INDEX)] for row in xrange(MAX_INDEX)] 121 | for _ in range(int(raw_input())): 122 | # Input 123 | H, W, R, C = map(int, raw_input().split()) 124 | int_board = 0 125 | for row in xrange(H): 126 | line = raw_input() 127 | for col in xrange(W): 128 | int_board = int_board << 1 129 | if(line[col] == '#'): 130 | int_board = int_board | 1 131 | int_block = 0 132 | for row in xrange(H): 133 | if(row < R): 134 | line = raw_input() 135 | for col in xrange(W): 136 | int_block = int_block << 1 137 | if(col < C): 138 | if(line[col] == '#'): 139 | int_block = int_block | 1 140 | int_block = int_block >> (W-C) 141 | 142 | # Solve 143 | board = BitMatrix(int_board, H, W) 144 | block = BitMatrix(int_block, H, W) 145 | 146 | blocks = [ 147 | block, 148 | BitMatrix(block.rotate().matrix >> (W-R), H, W), 149 | BitMatrix(block.reverseDiagonally().matrix >> ((H-R)*W) >> (W-C), H, W), 150 | BitMatrix(BitMatrix(block.reverseDiagonally().matrix >> ((H-R)*W) >> (W-C), H, W).rotate().matrix >> (W-R), H, W) 151 | ] 152 | 153 | # Output 154 | print getMaxNumber(board, blocks, 0, R, C) 155 | -------------------------------------------------------------------------------- /BRACKETS2/free-lunch_BRACKETS2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Brackets2: 4 | def __init__(self, str): 5 | self.str = str 6 | self.bracketMap = { 7 | '(' : 0, 8 | '{' : 1, 9 | '[' : 2, 10 | ')' : 10, 11 | '}' : 11, 12 | ']' : 12, 13 | } 14 | 15 | def isValidated(self): 16 | stack = list() 17 | for c in self.str: 18 | if c != '\n': 19 | id = self.bracketMap.get(c) 20 | # CASE : Open Case 21 | if id < 10: 22 | stack.append(id) 23 | # CASE : Close Case 24 | else : 25 | # CASE : Stack is empty 26 | if len(stack) == 0: 27 | return False 28 | # CASE : Mismatched Bracket 29 | if stack.pop() + 10 != id: 30 | return False 31 | # CASE : Remain open Brackets 32 | if len(stack) != 0: 33 | return False 34 | 35 | return True 36 | 37 | if __name__ == "__main__": 38 | rl = lambda: sys.stdin.readline() 39 | retList = [] 40 | for _ in xrange(int(rl())): 41 | input = rl() 42 | bracket = Brackets2(input) 43 | if bracket.isValidated(): 44 | print "YES" 45 | else : 46 | print "NO" -------------------------------------------------------------------------------- /BRACKETS2/free-lunch_BRACKETS2_UnitTest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | Brackets2 = __import__('free-lunch_BRACKETS2') 3 | 4 | class Mytest(unittest.TestCase): 5 | def test1(self): 6 | bracket = Brackets2.Brackets2("()()") 7 | self.assertEqual(bracket.isValidated(), True) 8 | 9 | def test2(self): 10 | bracket = Brackets2.Brackets2("({[}])") 11 | self.assertEqual(bracket.isValidated(), False) 12 | 13 | def test3(self): 14 | bracket = Brackets2.Brackets2("({}[(){}])") 15 | self.assertEqual(bracket.isValidated(), True) 16 | 17 | def test4(self): 18 | bracket = Brackets2.Brackets2("(((((") 19 | self.assertEqual(bracket.isValidated(), False) 20 | 21 | def test5(self): 22 | bracket = Brackets2.Brackets2("]]]]]") 23 | self.assertEqual(bracket.isValidated(), False) 24 | 25 | 26 | if __name__ == "__main__": 27 | TS = unittest.TestSuite() 28 | TS.addTest(Mytest("test1")) 29 | TS.addTest(Mytest("test2")) 30 | TS.addTest(Mytest("test3")) 31 | TS.addTest(Mytest("test4")) 32 | TS.addTest(Mytest("test5")) 33 | runner = unittest.TextTestRunner() 34 | runner.run(TS) 35 | 36 | -------------------------------------------------------------------------------- /CANADATRIP/free-lunch_CANADATRIP.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class CanadaTrip: 4 | class City: 5 | def __init__(self, L=0, M=0, G=0): 6 | self.location = L 7 | self.meter = M 8 | self.gap =G 9 | 10 | def __init__(self): 11 | self.cityList = [] 12 | self.min = sys.maxint 13 | self.max = 0 14 | 15 | def insert(self, location, meter, gap): 16 | self.cityList.append(self.City(location, meter, gap)) 17 | self.min = min(self.min, location-meter) 18 | self.max = max(self.max, location) 19 | 20 | def decision(self, dist): 21 | ans = 0 22 | for city in self.cityList: 23 | startPoint = city.location-city.meter 24 | if startPoint > dist : 25 | continue 26 | remainDist = min(dist, city.location) - startPoint 27 | ans += remainDist / city.gap + 1 28 | return ans 29 | 30 | def search(self, number): 31 | start,end = self.min, self.max 32 | while start <= end : 33 | mid = (start + end ) / 2 34 | ans = self.decision(mid) 35 | if ans < number: 36 | start = mid +1 37 | else: 38 | end = mid -1 39 | return start 40 | 41 | if __name__ == "__main__": 42 | rl = lambda: sys.stdin.readline() 43 | retList = [] 44 | for _ in xrange(int(float((rl())))): 45 | input = [int(n) for n in rl().split()] 46 | cityNum, tagetNum = input[0], input[1] 47 | trip = CanadaTrip() 48 | 49 | for _ in xrange(cityNum): 50 | input = [int(n) for n in rl().split()] 51 | location, meter, gap = input[0], input[1], input[2] 52 | trip.insert(location, meter, gap) 53 | 54 | retList.append(trip.search(tagetNum)) 55 | 56 | for ret in retList: 57 | print ret -------------------------------------------------------------------------------- /CANADATRIP/free-lunch_CANADATRIP_Unittest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import CANADATRIP 3 | 4 | class Mytest(unittest.TestCase): 5 | def test1(self): 6 | trip = CANADATRIP.CanadaTrip() 7 | trip.insert(500, 100, 10) 8 | trip.insert(504, 16, 4) 9 | trip.insert(510,60, 6) 10 | self.assertEqual(trip.search(15), 480) 11 | 12 | def test2(self): 13 | trip = CANADATRIP.CanadaTrip() 14 | trip.insert(8030000,8030000,1) 15 | trip.insert(2,2,1) 16 | self.assertEqual(trip.search(1234567), 1234563) 17 | 18 | if __name__ == "__main__": 19 | TS = unittest.TestSuite() 20 | TS.addTest(Mytest("test1")) 21 | TS.addTest(Mytest("test2")) 22 | runner = unittest.TextTestRunner() 23 | runner.run(TS) 24 | 25 | -------------------------------------------------------------------------------- /CHILDRENDAY/free-lunch_CHILDRENDAY.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import collections 3 | 4 | def append(here, edge, mod): 5 | there = here * 10 + edge 6 | if there >= mod: 7 | return there % mod + mod 8 | return there % mod 9 | 10 | def solve(digits, N, M): 11 | d = dict() 12 | q = collections.deque() 13 | digits = sorted(digits) 14 | 15 | here = 0 16 | d[0] = 0,0 17 | q.append(0) 18 | 19 | while len(q): 20 | here = q.popleft() 21 | for i in digits: 22 | there = append(here, i, N) 23 | if not there in d: 24 | d[there] = here, i 25 | q.append(there) 26 | 27 | here = N + M 28 | ret ='' 29 | if not here in d: 30 | return 'IMPOSSIBLE' 31 | 32 | while d[here][0] != here: 33 | ret += str(d[here][1]) 34 | here = d[here][0] 35 | 36 | return ret[::-1] 37 | 38 | if __name__ == "__main__": 39 | rl = lambda : sys.stdin.readline() 40 | for _ in xrange(int(rl())): 41 | digits, N, M = rl().split() 42 | N = int(N) 43 | M = int(M) 44 | digits = map(int, list(digits)) 45 | print solve(digits, N, M) 46 | -------------------------------------------------------------------------------- /CHILDRENDAY/free-lunch_CHILDRENDAY_Unittest.py: -------------------------------------------------------------------------------- 1 | test = __import__('free-lunch_CHILDRENDAY') 2 | import unittest 3 | 4 | class Test_CHILDRENDAY(unittest.TestCase): 5 | def test_append_1(self): 6 | # Case : result < Mod 7 | self.assertEqual(test.append(0, 3, 9), 3) 8 | 9 | def test_append_2(self): 10 | # Case : result < Mod 11 | self.assertEqual(test.append(0, 5, 9), 5) 12 | 13 | def test_append_3(self): 14 | # Case : result >= Mod 15 | self.assertEqual(test.append(5, 3, 9), 8 + 9) 16 | 17 | def test_solve_1(self): 18 | self.assertEqual(test.solve((1,),7,0), '111111') 19 | 20 | def test_solve_2(self): 21 | self.assertEqual(test.solve((1,),10,1), '11') 22 | 23 | def test_solve_3(self): 24 | self.assertEqual(test.solve((0,),7,3), 'IMPOSSIBLE') 25 | 26 | def test_solve_4(self): 27 | self.assertEqual(test.solve((3,4,5),9997, 3333), '35355353545') 28 | 29 | def test_solve_5(self): 30 | self.assertEqual(test.solve((3,5), 9, 8), '35') 31 | 32 | 33 | 34 | if __name__ == "__main__": 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /CLOCKSYNC/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/CLOCKSYNC/.gitkeep -------------------------------------------------------------------------------- /DRAGON/cccc612_dragon.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | len_memo = [-1] * 51 4 | def gen_len_memo(): 5 | len_memo[0] = 1 6 | 7 | for i in xrange(1,51): 8 | len_memo[i] = len_memo[i - 1] * 2 + 2 9 | 10 | def get_dragon_ch(dragon_str, gen, skip): 11 | if gen == 0: 12 | return dragon_str[skip] 13 | 14 | for ch in dragon_str: 15 | if ch == 'X' or ch == 'Y': 16 | if skip >= len_memo[gen]: 17 | skip -= len_memo[gen] 18 | elif ch == 'X': 19 | return get_dragon_ch('X+YF', gen - 1, skip) 20 | else: 21 | return get_dragon_ch('FX-Y', gen - 1, skip) 22 | elif skip > 0: 23 | skip -= 1 24 | else: 25 | return ch 26 | 27 | gen_len_memo() 28 | tc = int(raw_input()) 29 | 30 | for _ in xrange(tc): 31 | gen, start, length = map(int, raw_input().split()) 32 | 33 | for i in xrange(length): 34 | sys.stdout.write(get_dragon_ch('FX', gen, start + i - 1)) 35 | print('') 36 | -------------------------------------------------------------------------------- /DRAGON/input.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 0 1 2 3 | 1 1 5 4 | 2 6 5 5 | 42 764853475 30 -------------------------------------------------------------------------------- /DRAGON/markers_DRAGON.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 1. 18. 5 | ''' 6 | 7 | import sys 8 | 9 | rl = lambda : sys.stdin.readline() 10 | 11 | 12 | n_length = [-1] * 51 13 | 14 | def generate_length_nth(): 15 | n_length[0] = 1 16 | for n in range(1,51): 17 | n_length[n] = min(1000000001, n_length[n-1]*2+2) 18 | 19 | #def generate_length_nth(): 20 | # n_length.append(1) 21 | # for n in range(1,50): 22 | # n_length.append(min(1000000001, n_length[n-1]*2+2)) 23 | 24 | 25 | def curve(seed, n_th, skip): 26 | if n_th == 0: 27 | #print seed, 28 | return seed[skip] 29 | for word in seed: 30 | if word == "X" or word == "Y": 31 | if skip >= n_length[n_th]: 32 | skip -= n_length[n_th] 33 | elif word == "X": 34 | return curve("X+YF", n_th-1, skip) 35 | elif word == "Y": 36 | return curve("FX-Y", n_th-1, skip) 37 | elif skip > 0: 38 | skip -= 1 39 | else: 40 | return word 41 | return 42 | 43 | 44 | if __name__ == "__main__": 45 | testCase = int(rl()) 46 | generate_length_nth() 47 | for tc in xrange(testCase): 48 | n_th, position, length = map(int, rl().rstrip().split()) 49 | string = [] 50 | for l in xrange(length): 51 | string.append( curve("FX", n_th, position-1+l ) ) 52 | print ''.join(string) 53 | #print string 54 | 55 | -------------------------------------------------------------------------------- /DRAGON/output.txt: -------------------------------------------------------------------------------- 1 | FX 2 | FX+YF 3 | +FX-Y 4 | FX-YF-FX+YF+FX-YF-FX+YF-FX-YF- -------------------------------------------------------------------------------- /DRAGON/rlakim5521_dragon.py: -------------------------------------------------------------------------------- 1 | # DRAGON 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | import sys 5 | 6 | # Returns a biggest power of two number which is equal to index or smaller than index. 7 | def getNotBigPowerOfTwo(index): 8 | for exponent in xrange(29): 9 | if(index - pow(2, exponent) < 0): 10 | return pow(2, exponent - 1) 11 | return pow(2, 28) 12 | 13 | # Returns '+' or '-' 14 | # There is a rule that a character of (3 * 2^n)th index is '+' and a character of (3 * (2^n + 2^(n-1)))th index is '-'. 15 | # For example, 16 | # F X + Y F + F X - Y F + F X + Y F - F X - Y F + F X + Y F + F X - Y F - F X + Y F - F X - Y F + 17 | # 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 18 | # 3*2^0 3*2^1 3*2^2 3*2^3 3*2^4 19 | # 3*(2^1+2^0) 3*(2^2+2^1) 3*(2^3+2^2) 20 | # 21 | # Also, if a character of Mth index (M is neither (3 * 2^n) nor (3 * (2^n + 2^(n-1)))), 22 | # the character of Mth index is equal to a character of (M - 3 * a biggest power of two number which is smaller than M)th index. 23 | def getOperator(index): 24 | notBigPowerOfTwo = getNotBigPowerOfTwo(index) 25 | 26 | if(index == 1): 27 | return "+" 28 | elif(index == notBigPowerOfTwo + notBigPowerOfTwo / 2): 29 | return "-" 30 | elif(index == notBigPowerOfTwo): 31 | return "+" 32 | else: 33 | return getOperator(index - notBigPowerOfTwo) 34 | 35 | 36 | # Main function 37 | def MainFunction(): 38 | if __name__ == "__main__": 39 | for _ in xrange(input()): 40 | # Input 41 | generationOfDragonCurve, startIndex, numberOfprintedIndex = map(int, raw_input().split()) 42 | 43 | # Output 44 | # There is a rule that 45 | # every character of (6N + 1)th index is 'F' and 46 | # every character of (6N + 2)th index is 'x' and 47 | # every character of (6N + 4)th index is 'Y' and 48 | # every character of (6N + 5)th index is 'F'. 49 | modIndex = startIndex % 6 50 | for index in xrange(modIndex, modIndex + numberOfprintedIndex): 51 | modResult = index % 6 52 | if(modResult == 1): 53 | sys.stdout.write("F") 54 | elif(modResult == 2): 55 | sys.stdout.write("X") 56 | elif(modResult == 3): 57 | sys.stdout.write(getOperator((startIndex + index - modIndex) / 3)) 58 | elif(modResult == 4): 59 | sys.stdout.write("Y") 60 | elif(modResult == 5): 61 | sys.stdout.write("F") 62 | elif(modResult == 0): 63 | sys.stdout.write(getOperator((startIndex + index - modIndex) / 3)) 64 | print 65 | 66 | MainFunction() 67 | -------------------------------------------------------------------------------- /DRUNKEN/drunken_rlakim5521.py: -------------------------------------------------------------------------------- 1 | # DRUNKEN 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | 5 | def main(): 6 | # Map of Seoul City 7 | # V : a number of locations 8 | # E : a number of roads 9 | V, E = map(int, raw_input().split()) 10 | # crackdown : times for a crackdown on drunk drive 11 | crackdown = map(int, raw_input().split()) 12 | crackdown = [-1] + crackdown 13 | # path[(a, b)] = (c, d) : an adjacent list representing c(a time for arriving) and d(an worst crackdown time) 14 | # from a to b 15 | path = {} 16 | for road_index in xrange(E): 17 | a, b, c = map(int, raw_input().split()) 18 | path[(a, b)] = (c, 0) 19 | path[(b, a)] = (c, 0) 20 | 21 | for k in xrange(V): 22 | for i in xrange(V): 23 | for j in xrange(V): 24 | if (i, k) in path and (k, j) in path: 25 | if not (i, j) in path or\ 26 | sum(path[(i, j)]) > path[(i, k)][0] + path[(k, j)][0] + max(path[(i, k)][1], 27 | path[(k, j)][1], 28 | crackdown[k]): 29 | path[(i, j)] = (path[(i, k)][0] + path[(k, j)][0], 30 | max(path[(i, k)][1], path[(k, j)][1], crackdown[k])) 31 | 32 | # Problem 33 | # T : the number of test cases 34 | T = int(raw_input()) 35 | for case in xrange(T): 36 | # s : the location of Hyoseung 37 | # t : the location where friends are waiting 38 | s, t = map(int, raw_input().split()) 39 | 40 | # Output 41 | print sum(path[(s, t)]) 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /DRUNKEN/free-lunch_DRUNKEN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define MAX 987654321 10 | int V, adj[500][500]; 11 | int delay[500]; 12 | int W[500][500]; 13 | 14 | void solve(){ 15 | vector > order; 16 | for(int i = 0; i < V; i++) { 17 | order.push_back(make_pair(delay[i],i)); 18 | } 19 | sort(order.begin(), order.end()); 20 | for(int i = 0; i < V; i++) 21 | W[i][i] = 0; 22 | 23 | for(int k = 0; k < V; k++) { 24 | int w = order[k].second; 25 | for(int i = 0; i < V; i++){ 26 | for(int j = 0; j < V; j++){ 27 | adj[i][j] = min(adj[i][j], adj[i][w]+adj[w][j]); 28 | W[i][j] = min(W[i][j], adj[i][w]+adj[w][j]+delay[w]); 29 | } 30 | } 31 | } 32 | } 33 | 34 | int main(){ 35 | cin.sync_with_stdio(false); 36 | int E = 0; 37 | string s; 38 | 39 | cin >> V >> E; 40 | cin.get(); 41 | getline(cin, s); 42 | stringstream ss(s); 43 | 44 | int n = 0; 45 | for(int i = 0; i < V; i++){ 46 | ss >> n; 47 | delay[i] = n; 48 | } 49 | for(int i = 0; i < V; i++) { 50 | for(int j = 0; j < V; j++) { 51 | adj[i][j] = MAX; 52 | W[i][j] = MAX; 53 | } 54 | } 55 | 56 | int v1, v2, cost; 57 | while(E--){ 58 | cin >> v1 >> v2 >> cost; 59 | v1--;v2--; 60 | adj[v1][v2] = cost; 61 | adj[v2][v1] = cost; 62 | W[v1][v2] = cost; 63 | W[v2][v1] = cost; 64 | } 65 | 66 | solve(); 67 | 68 | int tests; 69 | cin >> tests; 70 | while(tests--) { 71 | cin >> v1 >> v2; 72 | v1--;v2--; 73 | cout<= int(cur_fence)): 28 | max_area = max(max_area, int(stack.peek()[0]) * (cur_index - stack.peek()[1])) 29 | new_index = stack.pop()[1] 30 | # push current element with 31 | stack.push(cur_fence, new_index) 32 | 33 | return max_area 34 | 35 | if __name__ == '__main__': 36 | test_case = int(raw_input()) 37 | 38 | for case in range(test_case): 39 | num_fence = int(raw_input()) # number of fences 40 | fences = raw_input().split(' ') # heights of fences 41 | fences.append(0) 42 | print(cut_fence(fences)) -------------------------------------------------------------------------------- /FIRETRUCKS/input.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 8 12 3 2 3 | 1 2 3 4 | 1 6 9 5 | 2 3 6 6 | 3 4 4 7 | 3 5 2 8 | 4 5 7 9 | 6 5 5 10 | 8 6 5 11 | 6 7 3 12 | 8 7 3 13 | 7 5 1 14 | 2 8 3 15 | 2 3 5 16 | 4 6 -------------------------------------------------------------------------------- /FIRETRUCKS/markers_FIRETRUCKS.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | rl = lambda : sys.stdin.readline() 5 | 6 | 7 | class Graph(): 8 | 9 | 10 | def __init__(self, number_of_place): 11 | self.graph = [ [ sys.maxint] * number_of_place for _ in xrange(number_of_place) ] 12 | self.number_of_place = number_of_place 13 | 14 | def add_edge(self, start_point, end_point, time): 15 | self.graph[start_point][end_point] = time 16 | self.graph[end_point][start_point] = time 17 | 18 | def dijkstra(self, start,end): 19 | visited = [ 0 ] * self.number_of_place 20 | dist = [ sys.maxint ] * self.number_of_place 21 | dist[start] = 0 22 | v = 0 23 | 24 | for index in xrange(1,self.number_of_place): 25 | min_node = sys.maxint 26 | for inner_index in xrange(1, self.number_of_place): 27 | if visited[inner_index] == 0 and min_node > dist[inner_index]: 28 | min_node = dist[inner_index] 29 | v = inner_index 30 | 31 | visited[v] = True 32 | 33 | for inner_index in xrange(1, self.number_of_place): 34 | if dist[inner_index] > dist[v] + self.graph[v][inner_index]: 35 | dist[inner_index] = dist[v] + self.graph[v][inner_index] 36 | 37 | return dist[end] 38 | 39 | 40 | def main(): 41 | for tc in xrange(int(rl())): 42 | place, edge, fires, fire_stations = map(int, rl().rstrip().split()) 43 | graph = Graph(place + 1) 44 | for _ in xrange(edge): 45 | start_point, end_point, time = map(int, rl().rstrip().split()) 46 | graph.add_edge(start_point, end_point, time) 47 | fired_place_list = map(int, rl().rstrip().split()) 48 | fire_station_list = map(int, rl().rstrip().split()) 49 | 50 | sum = 0 51 | 52 | for fire_station in fire_station_list: 53 | graph.add_edge(0,fire_station, 0) 54 | 55 | for fire in fired_place_list: 56 | sum += graph.dijkstra(0,fire) 57 | 58 | print sum 59 | 60 | if __name__ == "__main__": 61 | main() 62 | -------------------------------------------------------------------------------- /FORTRESS/input.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 3 3 | 5 5 15 4 | 5 5 10 5 | 5 5 5 6 | 8 7 | 21 15 20 8 | 15 15 10 9 | 13 12 5 10 | 12 12 3 11 | 19 19 2 12 | 30 24 5 13 | 32 10 7 14 | 32 9 4 -------------------------------------------------------------------------------- /FORTRESS/markers_FORTRESS.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 5. 04. 5 | ''' 6 | 7 | import sys 8 | import unittest 9 | 10 | rl = lambda : sys.stdin.readline() 11 | 12 | 13 | def sqrt(n): 14 | return n*n 15 | 16 | 17 | class Test_FORTRESS(unittest.TestCase): 18 | def test_anything(self): 19 | pass 20 | 21 | 22 | class Fortress(): 23 | 24 | def __init__(self,x,y,r): 25 | self.x = x 26 | self.y = y 27 | self.r = r 28 | self.children = [] 29 | 30 | def __repr__(self): 31 | return "[ x = {}, y = {}, r = {} ]".format(self.x, self.y, self.r) 32 | 33 | def is_children(self,fortress): 34 | if sqrt(self.r - fortress.r) > self._distance(fortress): 35 | return True 36 | return False 37 | 38 | def _distance(self, fortress): 39 | return sqrt(self.x - fortress.x) + sqrt(self.y - fortress.y) 40 | 41 | def add_child(self,fortress): 42 | for child in self.children: 43 | if child.is_children(fortress): 44 | child.add_child(fortress) 45 | return 46 | self.children.append(fortress) 47 | 48 | def long_distance(self,m): 49 | if len(self.children) == 0: 50 | return 0 51 | 52 | m1 = 0 53 | m2 = 0 54 | for child in self.children: 55 | m2 = max(m2, child.long_distance(m) + 1) 56 | if m2 > m1: 57 | m2, m1 = m1 , m2 58 | m[0] = max(m[0], m1+m2) 59 | 60 | return m1 61 | 62 | 63 | if __name__ == "__main__": 64 | 65 | for _ in xrange(int(rl().rstrip())): 66 | num_rampart = int(rl().rstrip()) 67 | rampart_list = [] 68 | for _ in xrange(num_rampart): 69 | x,y,r = map(int, rl().rstrip().split()) 70 | rampart_list.append(Fortress(x,y,r)) 71 | rampart_list.sort(key=lambda fortress: fortress.r, 72 | reverse=True) 73 | root = rampart_list.pop(0) 74 | 75 | for node in rampart_list: 76 | if root.is_children(node): 77 | root.add_child(node) 78 | 79 | m = [0] 80 | root.long_distance(m) 81 | print m[0] 82 | 83 | 84 | 85 | """ 86 | 20 -> 10, 7, 5 87 | 10 -> 5, 2 88 | 7 -> 4 89 | 5 -> x 90 | 5 -> 3 91 | 2 -> x 92 | 4 -> x 93 | """ -------------------------------------------------------------------------------- /FORTRESS/output.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 5 3 | -------------------------------------------------------------------------------- /GALLERY/free-lunch_GALLERY.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | UNWATCHED = 0 4 | WATCHED = 1 5 | INSTALLED = 2 6 | 7 | class DFS(): 8 | def __init__(self,visited, adj, installed): 9 | self.visited = visited 10 | self.adj = adj 11 | self.installed = 0 12 | 13 | def dfs(self,here): 14 | self.visited[here] = True 15 | children = [0] * 3 16 | for there in self.adj[here]: 17 | if not self.visited[there]: 18 | children[self.dfs(there)] += 1 19 | 20 | if children[UNWATCHED] != 0: 21 | self.installed += 1 22 | return INSTALLED 23 | 24 | if children[INSTALLED] != 0: 25 | return WATCHED 26 | return UNWATCHED 27 | 28 | def getInstalled(self): 29 | return self.installed 30 | 31 | def printAll(self): 32 | print self.visited 33 | print self.adj 34 | print self.installed 35 | 36 | def solve(G, H, connected): 37 | 38 | visited = [False] * G 39 | installed = 0 40 | 41 | adj = [[] for _ in xrange(G)] 42 | for c in connected: 43 | adj[c[0]].append(c[1]) 44 | adj[c[1]].append(c[0]) 45 | 46 | d = DFS(visited, adj, installed) 47 | 48 | 49 | for i in xrange(G): 50 | if not visited[i] and d.dfs(i) == UNWATCHED: 51 | installed += 1 52 | 53 | 54 | return installed + d.getInstalled() 55 | 56 | 57 | if __name__ == "__main__": 58 | rl = lambda : sys.stdin.readline() 59 | for _ in xrange(int(rl())): 60 | G,H = map(int,rl().split()) 61 | connected = [] 62 | for _ in xrange(H): 63 | connected.append(map(int, rl().split())) 64 | print solve(G, H, connected) 65 | -------------------------------------------------------------------------------- /GALLERY/free-lunch_GALLERY_Unittest.py: -------------------------------------------------------------------------------- 1 | test = __import__('free-lunch_GALLERY') 2 | import unittest 3 | 4 | class Test_GALLERY(unittest.TestCase): 5 | def test_exam1(self): 6 | connected = [[0, 1], [1, 2], [1, 3], [2, 5], [0, 4]] 7 | G,H = 6,5 8 | self.assertEqual(test.solve(G,H,connected), 3) 9 | 10 | 11 | def test_exam2(self): 12 | connected = [[0, 1], [2, 3]] 13 | G,H = 4,2 14 | self.assertEqual(test.solve(G,H,connected), 2 ) 15 | 16 | def test_exam3(self): 17 | connected = [[0, 1]] 18 | G,H = 1000,1 19 | self.assertEqual(test.solve(G,H,connected), 999 ) 20 | 21 | 22 | if __name__ == "__main__": 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /GALLERY/rlakim5521_gallery.py: -------------------------------------------------------------------------------- 1 | # GALLERY 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | import sys 5 | from Queue import Queue 6 | input = sys.stdin.readline 7 | 8 | class DominatingSet: 9 | def __init__(self, g, h): 10 | # adjList : a graph representing connections of galleries 11 | # trees : a list of trees 12 | self.num_of_node = g 13 | self.num_of_edge = h 14 | self.adjList = [[] for _ in xrange(g)] 15 | self.trees = [] 16 | self.visited = [ False ] * g 17 | 18 | def insertEdge(self, nodes): 19 | self.adjList[nodes[0]].append(nodes[1]) 20 | self.adjList[nodes[1]].append(nodes[0]) 21 | 22 | def bfs(self, node): 23 | if not self.visited[node]: 24 | self.visited[node] = True 25 | child_iter = 1 26 | tree = [] 27 | 28 | treeNode = [0] 29 | for child in self.adjList[node]: 30 | if not self.visited[child]: 31 | treeNode.append(child_iter) 32 | child_iter += 1 33 | tree.append(treeNode) 34 | 35 | children_queue = Queue() 36 | parent_queue = Queue() 37 | for child in self.adjList[node]: 38 | children_queue.put(child) 39 | parent_queue.put(node) 40 | 41 | while(not children_queue.empty()): 42 | current = children_queue.get() 43 | parent = parent_queue.get() 44 | if not self.visited[current]: 45 | self.visited[current] = True 46 | 47 | treeNode = [parent] 48 | for child in self.adjList[current]: 49 | if not self.visited[child]: 50 | treeNode.append(child_iter) 51 | child_iter += 1 52 | children_queue.put(child) 53 | parent_queue.put(current) 54 | tree.append(treeNode) 55 | 56 | self.trees.append(tree) 57 | 58 | def turnTree(self): 59 | self.visited = [ False ] * self.num_of_node 60 | for node in xrange(self.num_of_node): 61 | self.bfs(node) 62 | #print self.trees 63 | #print 64 | 65 | def getNumberOfDominatingNode(self, tree): 66 | # If there is no other node without root, return 1. 67 | if len(tree) == 1: 68 | return 1 69 | 70 | result = 0 71 | dominated = [False] * len(tree) 72 | for iter in xrange(len(tree)-1, -1, -1): 73 | for child in tree[iter][1:]: 74 | if dominated[child] == False: 75 | # select the current node 76 | # turn the current node and parent node to be dominated 77 | # we don't need to turn children nodes 78 | dominated[tree[iter][0]] = True 79 | dominated[iter] = True 80 | result += 1 81 | break 82 | 83 | return result 84 | 85 | def solve(self): 86 | result = 0 87 | self.turnTree() 88 | for tree in self.trees: 89 | result += self.getNumberOfDominatingNode(tree) 90 | 91 | return result 92 | 93 | if __name__ == "__main__": 94 | for _ in xrange(int(input())): 95 | # Input 96 | # g : the number of galleries (1<=g<=1000) 97 | # h : the number of halls (0<=h 5 | #include 6 | using namespace std; 7 | 8 | unsigned int getNextA(unsigned int preA) 9 | { 10 | return preA * 214013 + 2531011; 11 | } 12 | 13 | unsigned int getSignal(unsigned int currentA) 14 | { 15 | return (currentA % 10000) + 1; 16 | } 17 | 18 | int main() 19 | { 20 | unsigned int C; 21 | cin >> C; 22 | for (unsigned int c = 0; c < C; c++) { 23 | // Input 24 | unsigned int K, N; 25 | cin >> K >> N; 26 | 27 | // Solve 28 | unsigned int count = 0; 29 | unsigned int sectionSum = 0; 30 | unsigned int currentA = 1983; 31 | unsigned int currentSignal = getSignal(currentA); 32 | queue section; 33 | 34 | for (unsigned int n = 0; n < N; n++) { 35 | section.push(currentSignal); 36 | sectionSum += currentSignal; 37 | while (sectionSum > K) { 38 | sectionSum -= section.front(); 39 | section.pop(); 40 | } 41 | if (sectionSum == K) { 42 | count++; 43 | } 44 | currentA = getNextA(currentA); 45 | currentSignal = getSignal(currentA); 46 | } 47 | 48 | // Output 49 | cout << count << endl; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /JAEHASAFE/README.md: -------------------------------------------------------------------------------- 1 | ## Problem H. Jaeha’s Safe 2 | 3 | Jaeha just bought a new children’s safe to store his valuables. 4 | The safe uses a dial to lock the door, and on the rim of dial are drawn pictures of cute animals instead of numbers. 5 | To open the safe, Jaeha must rotate the dial to reach certain positions, alternating direction each time. 6 | ![Image](img_1.png) 7 | 8 | The above pictures show an example of how the safe can be opened. 9 | Picture (a) shows the dial’s current position. Jaeha needs to rotate the dial clockwise until position (b) is reached. Then Jaeha needs to rotate the dial counterclockwise until position (c) appears, and then the safe will open. 10 | Jaeha wants to be careful, so he only rotates the dial one tick at a time. A tick means a picture drawn 11 | on the rim of the dial. Therefore, to open the safe in the above example, Jaeha needs to rotate 4 ticks to reach position (b) and 6 ticks to reach position (c), totalling 10 ticks. 12 | Like his father, Jaeha is an impatient child. Let’s help him out by writing a program that, given a set of dial positions, calculate how many ticks Jaeha has to rotate the dial to open the safe. 13 | 14 | ### Input 15 | The input consists of T test cases. The number of test cases T is given in the first line of the input. 16 | The first line of each test case will contain an integer N(1 ≤ N ≤ 50), the number of positions Jaeha needs to reach. The next N + 1 lines will each contain a dial configuration. 17 | A configuration is given by listing the pictures in clockwise order, starting from the topmost picture. Each type of picture is denoted by an alphabet character, therefore each configuration is given as a string. 18 | The first configuration shows the current dial. Jaeha will rotate clockwise to reach the second configuration, rotate counterclockwise to reach the third, and so on. 19 | The number of pictures on a dial will not exceed 10,000. 20 | Two adjacent configurations given in the input will always be different. It is always possible to open the safe. 21 | 22 | ### Output 23 | Print exactly one line for each test case. 24 | The line should contain the minimum number of ticks required to open the safe. 25 | 26 | ### Sample 27 | * Input 28 | * 2 29 | * 3 30 | * abbab 31 | * babab 32 | * ababb 33 | * bbaba 34 | * 2 35 | * RMDCMRCD 36 | * MRCDRMDC 37 | * DCMRCDRM 38 | * Output 39 | * 6 40 | * 10 41 | -------------------------------------------------------------------------------- /JAEHASAFE/img_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/JAEHASAFE/img_1.png -------------------------------------------------------------------------------- /JAEHASAFE/j2h_JaeHaSafe.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class JaeHaSafe(): 4 | def shiftLeft(self, inputList): 5 | r = inputList[1:] 6 | r.append(inputList[0]) 7 | return r 8 | 9 | def shiftRight(self, inputList): 10 | r = inputList[:-1] 11 | r.insert(0, inputList[-1]) 12 | return r 13 | 14 | def sameWhile(self, fromList, toList): 15 | _fromList = fromList[:] 16 | maxCnt = len(fromList) 17 | # Left 18 | cnt = 0 19 | for _ in range(maxCnt): 20 | _fromList = self.shiftLeft(_fromList) 21 | cnt = cnt + 1 22 | if _fromList == toList: 23 | break 24 | if maxCnt > cnt: 25 | return cnt 26 | # Right 27 | cnt = 0 28 | for _ in range(maxCnt): 29 | _fromList = self.shiftRight(_fromList) 30 | cnt = cnt + 1 31 | if _fromList == toList: 32 | break 33 | return cnt 34 | 35 | def solve(self, inputList): 36 | _inputList = [] 37 | for _str in inputList: 38 | _inputList.append(list(_str)) 39 | 40 | cnt = 0 41 | for idx in range(len(_inputList)-1): 42 | cnt = cnt + self.sameWhile(_inputList[idx], _inputList[idx+1]) 43 | return cnt 44 | 45 | if __name__ == '__main__': 46 | TC = int(raw_input()) 47 | INDEX = 0 48 | answerList = [] 49 | 50 | while INDEX < TC: 51 | numberOfList = int(raw_input()) 52 | inputList = [] 53 | for _ in range(numberOfList+1): 54 | inputList.append(raw_input()) 55 | 56 | answerList.append(JaeHaSafe().solve(inputList)) 57 | INDEX = INDEX + 1 58 | 59 | for answer in answerList: 60 | print(answer) 61 | -------------------------------------------------------------------------------- /JAEHASAFE/j2h_JaeHaSafeTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import time 4 | import unittest 5 | from j2h_JaeHaSafe import JaeHaSafe 6 | 7 | class JaeHaSafeTest(unittest.TestCase): 8 | input_1 = ["abbab", "babab", "ababb", "bbaba"] 9 | input_2 = ["RMDCMRCD","MRCDRMDC","DCMRCDRM"] 10 | 11 | answer_1 = 6 12 | answer_2 = 10 13 | 14 | def setUp(self): 15 | self.startTime = time.time() 16 | print 17 | 18 | def tearDown(self): 19 | print("{0}: {1}".format(self.id(), time.time() - self.startTime)) 20 | 21 | def testShiftLeft(self): 22 | self.assertEquals([2,3,1], JaeHaSafe().shiftLeft([1,2,3])) 23 | 24 | def testShiftRight(self): 25 | self.assertEquals([3,1,2], JaeHaSafe().shiftRight([1,2,3])) 26 | 27 | def testSameWhile(self): 28 | self.assertEquals(1, JaeHaSafe().sameWhile([1,2,3], [3,1,2])) 29 | self.assertEquals(2, JaeHaSafe().sameWhile([1,2,3], [2,3,1])) 30 | 31 | def testSample(self): 32 | self.assertEquals(self.answer_1, JaeHaSafe().solve(self.input_1)) 33 | self.assertEquals(self.answer_2, JaeHaSafe().solve(self.input_2)) 34 | 35 | if __name__ == '__main__': 36 | totalSuite = unittest.TestLoader().loadTestsFromTestCase(JaeHaSafeTest) 37 | suite = unittest.TestSuite() 38 | # suite.addTest(JaeHaSafeTest('testShiftLeft')) 39 | # suite.addTest(JaeHaSafeTest('testShiftRight')) 40 | #o suite.addTest(JaeHaSafeTest('testSameWhile')) 41 | suite.addTest(JaeHaSafeTest('testSample')) 42 | unittest.TextTestRunner(verbosity=2).run(suite) 43 | # unittest.TextTestRunner(verbosity=2).run(totalSuite) 44 | -------------------------------------------------------------------------------- /JAEHASAFE/rlakim5521_jaehasafe.cpp: -------------------------------------------------------------------------------- 1 | // JAEHASAFE 2 | // Jaekyoung Kim(rlakim5521@naver.com) 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int turnLeft(const string before, const string after) { 10 | int ret = 0; 11 | string doubleBefore = before + before; 12 | int compareIndex = 0; 13 | int len = after.length(); 14 | while (after.compare(doubleBefore.substr(compareIndex, len))) { 15 | compareIndex += 1; 16 | ret += 1; 17 | } 18 | return ret; 19 | } 20 | 21 | int turnRight(const string before, const string after) { 22 | int ret = 0; 23 | string doubleBefore = before + before; 24 | int compareIndex = after.length(); 25 | int len = after.length(); 26 | while (after.compare(doubleBefore.substr(compareIndex, len))) { 27 | compareIndex -= 1; 28 | ret += 1; 29 | } 30 | return ret; 31 | } 32 | 33 | int main() 34 | { 35 | int C; 36 | cin >> C; 37 | for (int c = 0; c < C; c++) { 38 | int N; 39 | string str_dial; 40 | vector vec_dials; 41 | cin >> N; 42 | for (int n = 0; n <= N; n++) { 43 | cin >> str_dial; 44 | vec_dials.push_back(str_dial); 45 | } 46 | 47 | int output = 0; 48 | for (int n = 1; n <= N; n++) { 49 | if (n % 2 == 1) { 50 | output += turnRight(vec_dials[n - 1], vec_dials[n]); 51 | } 52 | else { 53 | output += turnLeft(vec_dials[n - 1], vec_dials[n]); 54 | } 55 | } 56 | 57 | cout << output << endl; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /JLIS/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/JLIS/.gitkeep -------------------------------------------------------------------------------- /JLIS/JLIS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int gList1[100]; 5 | int gList2[100]; 6 | 7 | int gList1Count = 0; 8 | int gList2Count = 0; 9 | 10 | int gJLIS[101][101]; 11 | 12 | long MIN = -2147483647; 13 | 14 | int getJLIS( int aIndex1, 15 | int aIndex2 ) 16 | { 17 | int i = 0; 18 | int j = 0; 19 | int sJLIS = 0; 20 | int sTempJLIS = 0; 21 | long sMaxValue = 0; 22 | long sList1Value = 0; 23 | long sList2Value = 0; 24 | 25 | /* already get it */ 26 | if ( gJLIS[aIndex1+1][aIndex2+1] != 0 ) 27 | { 28 | //printf ( "aIndex1 %d aIndex2 %d return %d\n", aIndex1, aIndex2, gJLIS[aIndex1+1][aIndex2+1] ); 29 | return gJLIS[aIndex1+1][aIndex2+1]; 30 | } 31 | 32 | if ( aIndex1 == -1 ) 33 | { 34 | sList1Value = MIN; 35 | } 36 | else 37 | { 38 | sList1Value = gList1[aIndex1]; 39 | } 40 | 41 | if ( aIndex2 == -1 ) 42 | { 43 | sList2Value = MIN; 44 | } 45 | else 46 | { 47 | sList2Value = gList2[aIndex2]; 48 | } 49 | 50 | /* get max value */ 51 | if ( sList1Value < sList2Value ) 52 | { 53 | sMaxValue = sList2Value; 54 | sJLIS = 2; 55 | } 56 | else if ( sList1Value > sList2Value ) 57 | { 58 | sMaxValue = sList1Value; 59 | sJLIS = 2; 60 | } 61 | else 62 | { 63 | sMaxValue = sList1Value; 64 | sJLIS = 1; 65 | } 66 | 67 | //gJLIS[aIndex1+1][aIndex2+1] = sJLIS; 68 | //printf( "Index1 %d Value %d Index2 %d Value %d \n", aIndex1, gList1[aIndex1],aIndex2, gList2[aIndex2] ); 69 | 70 | /* list 1 */ 71 | for ( i = aIndex1+1; i < gList1Count; i++ ) 72 | { 73 | //printf( "MaxValue %d, Index %d, value %d\n", sMaxValue, i, gList1[i] ); 74 | if ( sMaxValue < gList1[i] ) 75 | { 76 | sTempJLIS = getJLIS( i, aIndex2 ) + 1; 77 | //printf( " i : %d, aIndex2 : %d, sTempJLIS : %d JLIS %d\n", i, aIndex2, sTempJLIS, sJLIS ); 78 | if ( sTempJLIS > sJLIS ) 79 | { 80 | sJLIS = sTempJLIS; 81 | //gJLIS[aIndex1+1][aIndex2+1] = sJLIS; 82 | //printf ( "List 1 Set JLIS aIndex1 %d aIndex2 %d JLIS %d i :%d\n", aIndex1, aIndex2, sJLIS, i ); 83 | } 84 | } 85 | } 86 | 87 | /* list 2 */ 88 | for ( i = aIndex2+1; i < gList2Count; i++ ) 89 | { 90 | //printf( "MaxValue %d, Index %d, value %d\n", sMaxValue, i, gList1[i] ); 91 | if ( sMaxValue < gList2[i] ) 92 | { 93 | sTempJLIS = getJLIS( aIndex1, i ) + 1; 94 | //printf( " aIndex1: %d, i: %d, sTempJLIS : %d JLIS %d\n", aIndex2, i, sTempJLIS, sJLIS ); 95 | if ( sTempJLIS > sJLIS ) 96 | { 97 | sJLIS = sTempJLIS; 98 | //gJLIS[aIndex1+1][aIndex2+1] = sJLIS; 99 | //printf ( "List 2 Set JLIS aIndex1 %d aIndex2 %d JLIS %d : i : %d\n", aIndex1, aIndex2, sJLIS, i ); 100 | } 101 | } 102 | } 103 | //printf ( "JLIS aIndex1 %d aIndex2 %d JLIS %d : i : %d\n", aIndex1, aIndex2, sJLIS, i ); 104 | gJLIS[aIndex1+1][aIndex2+1] = sJLIS; 105 | 106 | return sJLIS; 107 | } 108 | 109 | int main( void ) 110 | { 111 | int sCount = 0; 112 | int i = 0; 113 | int j = 0; 114 | 115 | scanf( "%d", &sCount ); 116 | 117 | for ( i = 0; i < sCount; i++ ) 118 | { 119 | memset( gJLIS, 0x00, sizeof(gJLIS) ); 120 | 121 | scanf( "%d %d", &gList1Count, &gList2Count ); 122 | 123 | /* list 1 */ 124 | for ( j = 0; j < gList1Count; j++ ) 125 | { 126 | scanf( "%d ", &gList1[j] ); 127 | } 128 | 129 | /* list 2 */ 130 | for ( j = 0; j < gList2Count; j++ ) 131 | { 132 | scanf( "%d ", &gList2[j] ); 133 | } 134 | 135 | printf( "%d\n", getJLIS( -1, -1 ) - 2 ); 136 | } 137 | 138 | return 0; 139 | } 140 | -------------------------------------------------------------------------------- /JLIS/JLIS.py: -------------------------------------------------------------------------------- 1 | 2 | gList1 = [] 3 | gList2 = [] 4 | gList1Count = 0 5 | gList2Count = 0 6 | gJLIS = [] 7 | 8 | MIN_VALUE = float("-inf") 9 | 10 | def getJLIS( aIndex1, 11 | aIndex2 ) : 12 | 13 | global gList1 14 | global gList2 15 | 16 | global gList1Count 17 | global gList2Count 18 | 19 | if gJLIS[aIndex1+1][aIndex2+1] is not 0 : 20 | return gJLIS[aIndex1+1][aIndex2+1] 21 | 22 | if aIndex1 is -1 : 23 | sList1Value = MIN_VALUE 24 | else : 25 | sList1Value = gList1[aIndex1] 26 | 27 | if aIndex2 is -1 : 28 | sList2Value = MIN_VALUE 29 | else : 30 | sList2Value = gList2[aIndex2] 31 | 32 | sMaxValue = max( sList1Value, sList2Value ) 33 | sJLIS = 2 34 | 35 | for sIndex in range( aIndex1+1, gList1Count ) : 36 | if sMaxValue < gList1[sIndex] : 37 | sTempJLIS = getJLIS( sIndex, aIndex2 ) + 1 38 | if sTempJLIS > sJLIS : 39 | sJLIS = sTempJLIS 40 | 41 | for sIndex in range( aIndex2+1, gList2Count ) : 42 | if sMaxValue < gList2[sIndex] : 43 | sTempJLIS = getJLIS( aIndex1, sIndex ) + 1 44 | if sTempJLIS > sJLIS : 45 | sJLIS = sTempJLIS 46 | 47 | gJLIS[aIndex1+1][aIndex2+1] = sJLIS 48 | 49 | return sJLIS 50 | 51 | def solve() : 52 | global gList1 53 | global gList2 54 | 55 | global gList1Count 56 | global gList2Count 57 | 58 | global gJLIS 59 | 60 | sCount = input() 61 | 62 | for i in range( sCount ) : 63 | 64 | gJLIS = [ [ int(0) for i in range(101) ] for i in range(101) ] 65 | 66 | sInput = raw_input() 67 | 68 | sInput = raw_input().split() 69 | gList1 = [ int(num) for num in sInput ] 70 | gList1Count = len( gList1 ) 71 | 72 | sInput = raw_input().split() 73 | gList2 = [ int(num) for num in sInput ] 74 | gList2Count = len( gList2 ) 75 | 76 | print getJLIS( -1, -1 ) - 2 77 | 78 | solve(); 79 | -------------------------------------------------------------------------------- /JLIS/cjm9236_JLIS.py: -------------------------------------------------------------------------------- 1 | # JLIS problem (Joined Longest Increasing Subsequence) 2 | # Author: JeongminCha (cjm9236@me.com) 3 | 4 | from sys import maxint 5 | 6 | len_A = 0 7 | len_B = 0 8 | seq_A = [] 9 | seq_B = [] 10 | JLIS = [] 11 | 12 | # Returns element of sequence at specified index. 13 | # If the index is unavailable, it returns absolute minimum value. 14 | def element(seq, index): 15 | if index < 0: 16 | return -maxint 17 | else: 18 | return seq[index] 19 | 20 | # Returns length of JLIS of two sequences. 21 | def get_JLIS(index_A = -1, index_B = -1): 22 | # Memoization 23 | length_JLIS = JLIS[index_A+1][index_B+1] 24 | if length_JLIS is not 0: 25 | return length_JLIS 26 | 27 | length_JLIS = 2 28 | 29 | max_elem = max(element(seq_A, index_A), element(seq_B, index_B)) 30 | 31 | for index in range(index_A + 1, len_A): 32 | if max_elem < seq_A[index]: 33 | length_JLIS = max(length_JLIS, 1 + get_JLIS(index, index_B)) 34 | 35 | for index in range(index_B + 1, len_B): 36 | if max_elem < seq_B[index]: 37 | length_JLIS = max(length_JLIS, 1 + get_JLIS(index_A, index)) 38 | 39 | # Record a memo 40 | JLIS[index_A + 1][index_B + 1] = length_JLIS 41 | 42 | return length_JLIS 43 | 44 | if __name__ == '__main__': 45 | # 1. Input number of test cases. 46 | num_case = int(raw_input()) 47 | 48 | for case in range(num_case): 49 | # 2. Input the numbers of elements of two sequences. 50 | nums = raw_input().split(' ') 51 | len_A = int(nums[0]) 52 | len_B = int(nums[1]) 53 | 54 | # Initialize all elements of JLIS to -1. 55 | JLIS = [[int(0) for i in range(len_B + 1)] for j in range(len_A + 1)] 56 | 57 | # 3. Input the elements of the sequences. 58 | seq_A = map(int, raw_input().split(' ')) 59 | seq_B = map(int, raw_input().split(' ')) 60 | 61 | print(get_JLIS() - 2) -------------------------------------------------------------------------------- /JLIS/in.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 2 2 3 | 1 2 4 | 3 4 5 | 3 3 6 | 1 2 4 7 | 3 4 7 8 | 3 3 9 | 1 2 3 10 | 4 5 6 11 | 5 3 12 | 10 20 30 1 2 13 | 10 20 30 14 | -------------------------------------------------------------------------------- /JOSEPHUS/free-lunch_JOSEPHUS.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def solve(n, k): 4 | list = [i for i in xrange(n)] 5 | index = 0 6 | del list[index] 7 | 8 | while len(list) > 2: 9 | index = (index + (k-1)) % len(list) 10 | del list[index] 11 | 12 | return list 13 | 14 | if __name__ == "__main__": 15 | rl = lambda: sys.stdin.readline() 16 | for _ in xrange(int(rl())): 17 | n, k = rl().split() 18 | ret = solve(int(n), int(k)) 19 | print ret[0]+1, ret[1]+1 -------------------------------------------------------------------------------- /LAN/input.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 3 1 3 | 0 0 1 4 | 0 1 2 5 | 0 1 6 | 10 5 7 | -7 -7 10 -4 10 -4 -5 0 -10 -6 8 | 6 8 -5 3 -4 6 -10 4 -7 10 9 | 9 7 10 | 7 3 11 | 9 7 12 | 5 0 13 | 8 6 14 | 15 | 16 | -------------------------------------------------------------------------------- /LAN/markers_LAN.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 7. 16. 5 | ''' 6 | 7 | 8 | import sys 9 | import math 10 | from heapq import * 11 | from collections import defaultdict 12 | 13 | rl = lambda : sys.stdin.readline() 14 | 15 | 16 | def sovle(buildings, LAN): 17 | # shortest distance algorithms 18 | # prim 19 | 20 | # mst = [] 21 | visited = set([0]) 22 | result_distance = 0 23 | 24 | edge = LAN[0] 25 | # print edge 26 | 27 | heapify(edge) 28 | # print heapq.heappop(edge) 29 | 30 | while edge: 31 | cost, node_from, node_to = heappop(edge) 32 | # print heappop(edge) 33 | if node_to not in visited: 34 | visited.add(node_to) 35 | # mst.append((cost,node_from,node_to)) 36 | result_distance += cost 37 | 38 | for node in LAN[node_to]: 39 | if node[2] not in visited: 40 | heappush(edge, node) 41 | 42 | # for node in mst: 43 | # result_distance += node[0] 44 | # print node[0] 45 | 46 | 47 | # print result_distance 48 | # return mst 49 | return result_distance 50 | 51 | 52 | def point_sqrt(x, y): 53 | return math.sqrt( (x[0]-y[0])**2 + (x[1] - y[1])**2) 54 | 55 | ''' 56 | def set_LAN2(buildings, linked, points): 57 | # LAN distance setting 58 | LAN = [ [ float('inf') for x in xrange(buildings) ] for x in xrange( 59 | buildings) ] 60 | 61 | A_LAN = defaultdict(list) 62 | 63 | for index in xrange(buildings): 64 | for inner_index in xrange(buildings): 65 | if index is inner_index: 66 | continue 67 | elif index in linked.keys(): 68 | if inner_index in linked[index]: 69 | LAN[index][inner_index] = 0.0 70 | LAN[inner_index][index] = 0.0 71 | else: 72 | LAN[index][inner_index] = point_sqrt(points[index], 73 | points[inner_index]) 74 | A_LAN[index].append((point_sqrt(points[index],points[inner_index]), 75 | index, 76 | inner_index)) 77 | else: 78 | LAN[index][inner_index] = point_sqrt(points[index], 79 | points[inner_index]) 80 | 81 | ''' 82 | 83 | 84 | 85 | 86 | def set_LAN(buildings, linked, points): 87 | # LAN distance setting 88 | LAN = defaultdict(list) 89 | 90 | for index in xrange(buildings): 91 | for inner_index in xrange(buildings): 92 | if index is inner_index: 93 | continue 94 | elif index in linked.keys(): 95 | if inner_index in linked[index]: 96 | LAN[index].append((0.0, index, inner_index)) 97 | else: 98 | LAN[index].append((point_sqrt(points[index],points[inner_index]), 99 | index, 100 | inner_index)) 101 | else: 102 | LAN[index].append((point_sqrt(points[index],points[inner_index]), 103 | index, 104 | inner_index)) 105 | # print LAN 106 | # print linked 107 | 108 | # sovle(buildings, LAN) 109 | # print LAN 110 | return LAN 111 | 112 | 113 | def set_linked(cables): 114 | ## link setting 115 | linked = dict() 116 | for cable in xrange(cables): 117 | linked_from, linked_to = map(int, rl().rstrip().split()) 118 | try: 119 | # linked[linked_from].append(linked_to) 120 | linked[linked_from].add(linked_to) 121 | # linked[linked_to].add(linked_from) 122 | except KeyError: 123 | # linked[linked_from] = [linked_to] 124 | linked[linked_from] = set() 125 | linked[linked_from].add(linked_to) 126 | # linked[linked_to] = set() 127 | # linked[linked_to].add(linked_from) 128 | try: 129 | linked[linked_to].add(linked_from) 130 | except KeyError: 131 | linked[linked_to] = set() 132 | linked[linked_to].add(linked_from) 133 | return linked 134 | 135 | 136 | 137 | 138 | def main(): 139 | for tc in xrange(int(rl())): 140 | # input setting 141 | buildings, cables = map(int, rl().rstrip().split()) 142 | points_of_x = map(int, rl().rstrip().split()) 143 | points_of_y = map(int, rl().rstrip().split()) 144 | points = zip(points_of_x, points_of_y) 145 | # print points 146 | 147 | # print linked 148 | linked = set_linked(cables) 149 | 150 | #set LAN 151 | LAN = set_LAN(buildings, linked, points) 152 | 153 | # print sovle(buildings, LAN) 154 | print sovle(buildings, LAN) 155 | 156 | if __name__ == "__main__": 157 | main() -------------------------------------------------------------------------------- /LUNCHBOX/free-lunch_LUNCHBOX.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from operator import itemgetter 3 | 4 | def lunchBox(list): 5 | # The index 0 of lunchbox is microwaving time 6 | # The index 1 of lunchbox is eating time 7 | sortedList = sorted(list, key=itemgetter(1), reverse=True) 8 | 9 | cusumMicrowaving = 0 10 | finishLunch = 0 11 | 12 | for lunchbox in sortedList: 13 | cusumMicrowaving += lunchbox[0] 14 | finishEating = cusumMicrowaving + lunchbox[1] 15 | finishLunch = finishEating if finishEating > finishLunch else finishLunch 16 | 17 | return finishLunch 18 | 19 | if __name__ == "__main__": 20 | inputList = [] 21 | rl = lambda: sys.stdin.readline() 22 | 23 | for _ in xrange(int(rl())): 24 | rl() 25 | inputList.append(zip(map(int, rl().split()),map(int, rl().split()))) 26 | 27 | for testcase in inputList: 28 | print lunchBox(testcase) -------------------------------------------------------------------------------- /LUNCHBOX/input.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 3 3 | 2 2 2 4 | 2 2 2 5 | 3 6 | 1 2 3 7 | 1 2 1 8 | 5 9 | 10 2 13 4 2 10 | 1 4 82 29 8 11 | 4 12 | 4 2 6 1 13 | 5 2 2 1 14 | 15 | -------------------------------------------------------------------------------- /LUNCHBOX/markers_LUNCHBOX.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 2. 22. 5 | ''' 6 | 7 | import sys 8 | from operator import itemgetter 9 | 10 | rl = lambda : sys.stdin.readline().rstrip() 11 | 12 | def check_time(lunchbox_time): 13 | 14 | time = 0 15 | warm_time = 0 16 | for box in lunchbox_time: 17 | warm_time += box[0] 18 | time = max(time, warm_time + box[1]) 19 | return time 20 | 21 | 22 | if __name__ == "__main__": 23 | testCase = int(rl()) 24 | for tc in xrange(testCase): 25 | num_box = int(rl()) 26 | box_warm_time = map(int, rl().split()) 27 | box_eat_time = map(int, rl().split()) 28 | lunchbox_time = zip(box_warm_time, box_eat_time) 29 | lunchbox_time = sorted(lunchbox_time, key=itemgetter(1),reverse=True) 30 | #print lunchbox_time 31 | print check_time(lunchbox_time) 32 | -------------------------------------------------------------------------------- /LUNCHBOX/output.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 7 3 | 95 4 | 14 5 | 6 | -------------------------------------------------------------------------------- /LUNCHBOX/returns_lunchbox.py: -------------------------------------------------------------------------------- 1 | 2 | def compare( aLeft, aRight ) : 3 | 4 | sRC = cmp( aLeft[1], aRight[1] ) 5 | if sRC != 0 : 6 | return sRC * -1 7 | else : 8 | sRC = cmp( aLeft[0], aRight[0] ) 9 | return sRC 10 | 11 | def getTime( aLunchList ) : 12 | 13 | sSortedLunchList = sorted( aLunchList, 14 | cmp = compare ) 15 | 16 | sLeftTime = 0 17 | sTime = 0 18 | 19 | for sItem in sSortedLunchList : 20 | 21 | sTime = sTime + sItem[0] 22 | sLeftTime = sLeftTime - sItem[0] 23 | 24 | if sLeftTime < 0 : 25 | sLeftTime = 0 26 | 27 | if sLeftTime < sItem[1] : 28 | sLeftTime = sItem[1] 29 | 30 | sTime = sTime + sLeftTime 31 | 32 | return sTime 33 | 34 | def solve() : 35 | 36 | sTestCount = input() 37 | 38 | for _ in range( sTestCount ) : 39 | sList = [] 40 | sParticipantCount = input() 41 | 42 | sWarmTime = raw_input().split() 43 | sEatTime = raw_input().split() 44 | 45 | for sIndex in range( sParticipantCount ) : 46 | sItem = ( int(sWarmTime[sIndex]), int(sEatTime[sIndex]) ) 47 | sList.append( sItem ) 48 | 49 | print getTime( sList ) 50 | 51 | solve() 52 | -------------------------------------------------------------------------------- /LUNCHBOX/rlakim5521_lunchbox.py: -------------------------------------------------------------------------------- 1 | +# LUNCHBOX 2 | +# Jaekyoung Kim (rlakim5521@naver.com) 3 | + 4 | +# Main function 5 | +if __name__ == "__main__": 6 | + for _ in xrange(int(raw_input())): 7 | + # Input 8 | + n = int(raw_input()) 9 | + heat = map(int, raw_input().split()) 10 | + eat = map(int, raw_input().split()) 11 | + 12 | + # Solve 13 | + eatAndHeat = zip(eat,heat) 14 | + eatAndHeat.sort() 15 | + eatAndHeat.reverse() 16 | + 17 | + endTime = [] 18 | + cookingTime = 0 19 | + 20 | + for eah in eatAndHeat: 21 | + cookingTime += eah[1] 22 | + endTime.append(cookingTime+eah[0]) 23 | + 24 | + # Output 25 | + print max(endTime) 26 | -------------------------------------------------------------------------------- /MORDOR/rlakim5521_mordor.java: -------------------------------------------------------------------------------- 1 | // MORDOR 2 | // Jaekyoung Kim(rlakim5521@naver.com) 3 | 4 | import java.util.Scanner; 5 | 6 | class minRMQ { 7 | int n; 8 | int[] rangeMin; 9 | 10 | public minRMQ(int[] array) { 11 | n = array.length; 12 | rangeMin = new int[4*n]; 13 | init(array, 0, n-1, 1); 14 | } 15 | 16 | private int init(int[] array, int left, int right, int node) { 17 | if(left == right) { 18 | rangeMin[node] = array[left]; 19 | return rangeMin[node]; 20 | } 21 | 22 | int mid = (left + right) / 2; 23 | int leftMin = init(array, left, mid, node*2); 24 | int rightMin = init(array, mid+1, right, node*2+1); 25 | rangeMin[node] = Math.min(leftMin, rightMin); 26 | return rangeMin[node]; 27 | } 28 | 29 | public int query(int left, int right) { 30 | return _query(left, right, 1, 0, n-1); 31 | } 32 | 33 | private int _query(int left, int right, int node, int nodeLeft, int nodeRight) { 34 | if(right < nodeLeft || nodeRight < left) { 35 | return Integer.MAX_VALUE; 36 | } 37 | if(left <= nodeLeft && nodeRight <= right) { 38 | return rangeMin[node]; 39 | } 40 | int mid = (nodeLeft + nodeRight) / 2; 41 | return Math.min(_query(left,right,node*2,nodeLeft,mid), _query(left,right,node*2+1,mid+1,nodeRight)); 42 | } 43 | } 44 | 45 | class maxRMQ { 46 | int n; 47 | int[] rangeMax; 48 | 49 | public maxRMQ(int[] array) { 50 | n = array.length; 51 | rangeMax = new int[4*n]; 52 | init(array, 0, n-1, 1); 53 | } 54 | 55 | private int init(int[] array, int left, int right, int node) { 56 | if(left == right) { 57 | rangeMax[node] = array[left]; 58 | return rangeMax[node]; 59 | } 60 | 61 | int mid = (left + right) / 2; 62 | int leftMin = init(array, left, mid, node*2); 63 | int rightMin = init(array, mid+1, right, node*2+1); 64 | rangeMax[node] = Math.max(leftMin, rightMin); 65 | return rangeMax[node]; 66 | } 67 | 68 | public int query(int left, int right) { 69 | return _query(left, right, 1, 0, n-1); 70 | } 71 | 72 | private int _query(int left, int right, int node, int nodeLeft, int nodeRight) { 73 | if(right < nodeLeft || nodeRight < left) { 74 | return Integer.MIN_VALUE; 75 | } 76 | if(left <= nodeLeft && nodeRight <= right) { 77 | return rangeMax[node]; 78 | } 79 | int mid = (nodeLeft + nodeRight) / 2; 80 | return Math.max(_query(left,right,node*2,nodeLeft,mid), _query(left,right,node*2+1,mid+1,nodeRight)); 81 | } 82 | } 83 | 84 | public class Main { 85 | public static void main(String[] args) { 86 | Scanner sc = new Scanner(System.in); 87 | int cases = sc.nextInt(); 88 | while(cases-- > 0) { 89 | // Input 90 | int N = sc.nextInt(); 91 | int Q = sc.nextInt(); 92 | sc.nextLine(); 93 | int [] h = new int[N]; 94 | for (int iter = 0; iter < N; iter++) { 95 | h[iter] = sc.nextInt(); 96 | } 97 | sc.nextLine(); 98 | minRMQ min = new minRMQ(h); 99 | maxRMQ max = new maxRMQ(h); 100 | while(Q-- > 0) { 101 | int a = sc.nextInt(); 102 | int b = sc.nextInt(); 103 | // Output 104 | System.out.println(max.query(a, b) - min.query(a, b)); 105 | sc.nextLine(); 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /MORDOR/rlakim5521_mordor_bruteforce.py: -------------------------------------------------------------------------------- 1 | # MORDOR 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | # Main function 5 | if __name__ == "__main__": 6 | for _ in range(int(raw_input())): 7 | N, Q = map(int, raw_input().split()) 8 | h = map(int, raw_input().split()) 9 | for _ in xrange(Q): 10 | a, b = map(int, raw_input().split()) 11 | max = -1 12 | min = 20001 13 | for iter in xrange(a, b+1): 14 | if h[iter] > max: 15 | max = h[iter] 16 | if h[iter] < min: 17 | min = h[iter] 18 | print max - min 19 | -------------------------------------------------------------------------------- /MORDOR/rlakim5521_mordor_rangeminimumquery: -------------------------------------------------------------------------------- 1 | # MORDOR 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | INT_MAX = 20001 5 | INT_MIN = -1 6 | 7 | class minRMQ: 8 | def __init__(self, array): 9 | self.n = len(array) 10 | self.rangeMin = [0 for _ in xrange(4*self.n)] 11 | self._init(array, 0, self.n-1, 1) 12 | 13 | def _init(self, array, left, right, node): 14 | if(left == right): 15 | self.rangeMin[node] = array[left] 16 | return self.rangeMin[node] 17 | mid = (left + right) / 2 18 | leftMin = self._init(array, left, mid, node * 2) 19 | rightMin = self._init(array, mid + 1, right, node * 2 + 1) 20 | self.rangeMin[node] = min(leftMin, rightMin) 21 | return self.rangeMin[node] 22 | 23 | def query(self, left, right): 24 | return self._query(left, right, 1, 0, self.n-1) 25 | 26 | def _query(self, left, right, node, nodeLeft, nodeRight): 27 | if(right < nodeLeft or nodeRight < left): 28 | return INT_MAX 29 | if(left <= nodeLeft and nodeRight <= right): 30 | return self.rangeMin[node] 31 | mid = (nodeLeft + nodeRight) / 2 32 | return min(self._query(left, right, node*2, nodeLeft, mid), self._query(left, right, node*2+1, mid+1, nodeRight)) 33 | 34 | class maxRMQ: 35 | def __init__(self, array): 36 | self.n = len(array) 37 | self.rangeMax = [0 for _ in xrange(4*self.n)] 38 | self._init(array, 0, self.n-1, 1) 39 | 40 | def _init(self, array, left, right, node): 41 | if(left == right): 42 | self.rangeMax[node] = array[left] 43 | return self.rangeMax[node] 44 | mid = (left + right) / 2 45 | leftMax = self._init(array, left, mid, node * 2) 46 | rightMax = self._init(array, mid + 1, right, node * 2 + 1) 47 | self.rangeMax[node] = max(leftMax, rightMax) 48 | return self.rangeMax[node] 49 | 50 | def query(self, left, right): 51 | return self._query(left, right, 1, 0, self.n-1) 52 | 53 | def _query(self, left, right, node, nodeLeft, nodeRight): 54 | if(right < nodeLeft or nodeRight < left): 55 | return INT_MIN 56 | if(left <= nodeLeft and nodeRight <= right): 57 | return self.rangeMax[node] 58 | mid = (nodeLeft + nodeRight) / 2 59 | return max(self._query(left, right, node*2, nodeLeft, mid), self._query(left, right, node*2+1, mid+1, nodeRight)) 60 | 61 | 62 | # Main function 63 | if __name__ == "__main__": 64 | for _ in range(int(raw_input())): 65 | # Input 66 | N, Q = map(int, raw_input().split()) 67 | h = map(int, raw_input().split()) 68 | minimumRMQ = minRMQ(h) 69 | maximumRMQ = maxRMQ(h) 70 | for _ in xrange(Q): 71 | a, b = map(int, raw_input().split()) 72 | print maximumRMQ.query(a, b) - minimumRMQ.query(a, b) 73 | -------------------------------------------------------------------------------- /MORDOR/rlakim5521_mordor_redblacktree: -------------------------------------------------------------------------------- 1 | # MORDOR 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | class rbnode(object): 5 | """ 6 | A node in a red black tree. See Cormen, Leiserson, Rivest, Stein 2nd edition pg 273. 7 | """ 8 | 9 | def __init__(self, key): 10 | "Construct." 11 | self._key = key 12 | self._red = False 13 | self._left = None 14 | self._right = None 15 | self._p = None 16 | 17 | key = property(fget=lambda self: self._key, doc="The node's key") 18 | red = property(fget=lambda self: self._red, doc="Is the node red?") 19 | left = property(fget=lambda self: self._left, doc="The node's left child") 20 | right = property(fget=lambda self: self._right, doc="The node's right child") 21 | p = property(fget=lambda self: self._p, doc="The node's parent") 22 | 23 | def __str__(self): 24 | "String representation." 25 | return str(self.key) 26 | 27 | 28 | def __repr__(self): 29 | "String representation." 30 | return str(self.key) 31 | 32 | class rbtree(object): 33 | """ 34 | A red black tree. See Cormen, Leiserson, Rivest, Stein 2nd edition pg 273. 35 | """ 36 | 37 | 38 | def __init__(self, create_node=rbnode): 39 | "Construct." 40 | 41 | self._nil = create_node(key=None) 42 | "Our nil node, used for all leaves." 43 | 44 | self._root = self.nil 45 | "The root of the tree." 46 | 47 | self._create_node = create_node 48 | "A callable that creates a node." 49 | 50 | 51 | root = property(fget=lambda self: self._root, doc="The tree's root node") 52 | nil = property(fget=lambda self: self._nil, doc="The tree's nil node") 53 | 54 | 55 | def search(self, key, x=None): 56 | """ 57 | Search the subtree rooted at x (or the root if not given) iteratively for the key. 58 | 59 | @return: self.nil if it cannot find it. 60 | """ 61 | if None == x: 62 | x = self.root 63 | while x != self.nil and key != x.key: 64 | if key < x.key: 65 | x = x.left 66 | else: 67 | x = x.right 68 | return x 69 | 70 | 71 | def minimum(self, x=None): 72 | """ 73 | @return: The minimum value in the subtree rooted at x. 74 | """ 75 | if None == x: 76 | x = self.root 77 | while x.left != self.nil: 78 | x = x.left 79 | return x 80 | 81 | 82 | def maximum(self, x=None): 83 | """ 84 | @return: The maximum value in the subtree rooted at x. 85 | """ 86 | if None == x: 87 | x = self.root 88 | while x.right != self.nil: 89 | x = x.right 90 | return x 91 | 92 | 93 | def insert_key(self, key): 94 | "Insert the key into the tree." 95 | self.insert_node(self._create_node(key=key)) 96 | 97 | 98 | def insert_node(self, z): 99 | "Insert node z into the tree." 100 | y = self.nil 101 | x = self.root 102 | while x != self.nil: 103 | y = x 104 | if z.key < x.key: 105 | x = x.left 106 | else: 107 | x = x.right 108 | z._p = y 109 | if y == self.nil: 110 | self._root = z 111 | elif z.key < y.key: 112 | y._left = z 113 | else: 114 | y._right = z 115 | z._left = self.nil 116 | z._right = self.nil 117 | z._red = True 118 | self._insert_fixup(z) 119 | 120 | 121 | def _insert_fixup(self, z): 122 | "Restore red-black properties after insert." 123 | while z.p.red: 124 | if z.p == z.p.p.left: 125 | y = z.p.p.right 126 | if y.red: 127 | z.p._red = False 128 | y._red = False 129 | z.p.p._red = True 130 | z = z.p.p 131 | else: 132 | if z == z.p.right: 133 | z = z.p 134 | self._left_rotate(z) 135 | z.p._red = False 136 | z.p.p._red = True 137 | self._right_rotate(z.p.p) 138 | else: 139 | y = z.p.p.left 140 | if y.red: 141 | z.p._red = False 142 | y._red = False 143 | z.p.p._red = True 144 | z = z.p.p 145 | else: 146 | if z == z.p.left: 147 | z = z.p 148 | self._right_rotate(z) 149 | z.p._red = False 150 | z.p.p._red = True 151 | self._left_rotate(z.p.p) 152 | self.root._red = False 153 | 154 | def delete_node(self, key): 155 | 156 | z = self.search(key) 157 | 158 | y = None 159 | x = None 160 | 161 | if z._left == self._nil or z._right == self._nil: 162 | y = z 163 | else: 164 | y = self.get_successor(z) 165 | 166 | if y._left == self._nil: 167 | x = y._right 168 | else: 169 | x = y._left 170 | 171 | if x != None and y != None: 172 | x._p = y._p 173 | if self._root == x._p: 174 | self._root._left = x 175 | else: 176 | if y == y._p._left: 177 | y._p._left = x 178 | else: 179 | y._p._right = x 180 | 181 | if y != z: 182 | if not y._red and x != None: 183 | self.delete_fixup(x) 184 | 185 | y._left = z._left 186 | y._right = z._right 187 | y._p = z._p 188 | y._red = z._red 189 | z._left._p = z._right._p = y 190 | if z == z._p._left: 191 | z._p._left = y 192 | else: 193 | z._p._right = y 194 | else: 195 | if not y._red and x != None: 196 | self.delete_fixup(x) 197 | 198 | if self._root == z: 199 | self._root = self._nil 200 | 201 | self._size = self._size - 1 202 | 203 | def delete_fixup(self, x): 204 | root = self._root._left 205 | w = None 206 | 207 | while not x._red and root != x: 208 | if x == x._p._left: 209 | w = x._p._right 210 | if w._red: 211 | w._red = False 212 | x._p._red = True 213 | self._left_rotate(x.p) 214 | w = x._p._right 215 | if not w._right._red and not w._left._red: 216 | w._red = True 217 | x = x._p 218 | else: 219 | if not w._right._red: 220 | w._left._red = False 221 | w._red = True 222 | self._right_rotate(w) 223 | w = x._p._right 224 | w._red = x._p._red 225 | x._p._red = False 226 | w._right._red = False 227 | self._left_rotate(x._p) 228 | x = root 229 | else: 230 | w = x._p._left 231 | if w._red: 232 | w._red = False 233 | x._p._red = True 234 | self._right_rotate(x._p) 235 | w = x._p._left 236 | if not w._right._red and not w._left._red: 237 | w._red = True 238 | x = x._p 239 | else: 240 | if not w._left._red: 241 | w._right._red = False 242 | w._red = True 243 | self._left_rotate(w) 244 | w = x._p._left 245 | w._red = x._p._red 246 | x._p._red = False 247 | w._left._red = False 248 | self._right_rotate(x._p) 249 | x = root 250 | 251 | x._red = False 252 | 253 | def get_successor(self, x): 254 | y = None 255 | 256 | y = x._right 257 | if self._nil != y: 258 | while y._left != self._nil: 259 | y = y._left 260 | return y 261 | else: 262 | y = x._p 263 | while x == y._right: 264 | x = y 265 | y = y._p 266 | if y == self._root: 267 | return self._nil 268 | return y 269 | 270 | def _left_rotate(self, x): 271 | "Left rotate x." 272 | y = x.right 273 | x._right = y.left 274 | if y.left != self.nil: 275 | y.left._p = x 276 | y._p = x.p 277 | if x.p == self.nil: 278 | self._root = y 279 | elif x == x.p.left: 280 | x.p._left = y 281 | else: 282 | x.p._right = y 283 | y._left = x 284 | x._p = y 285 | 286 | 287 | def _right_rotate(self, y): 288 | "Left rotate y." 289 | x = y.left 290 | y._left = x.right 291 | if x.right != self.nil: 292 | x.right._p = y 293 | x._p = y.p 294 | if y.p == self.nil: 295 | self._root = x 296 | elif y == y.p.right: 297 | y.p._right = x 298 | else: 299 | y.p._left = x 300 | x._right = y 301 | y._p = x 302 | 303 | 304 | def check_invariants(self): 305 | "@return: True iff satisfies all criteria to be red-black tree." 306 | 307 | def is_red_black_node(node): 308 | "@return: num_black" 309 | # check has _left and _right or neither 310 | if (node.left and not node.right) or (node.right and not node.left): 311 | return 0, False 312 | 313 | # check leaves are black 314 | if not node.left and not node.right and node.red: 315 | return 0, False 316 | 317 | # if node is red, check children are black 318 | if node.red and node.left and node.right: 319 | if node.left.red or node.right.red: 320 | return 0, False 321 | 322 | # descend tree and check black counts are balanced 323 | if node.left and node.right: 324 | 325 | # check children's parents are correct 326 | if self.nil != node.left and node != node.left.p: 327 | return 0, False 328 | if self.nil != node.right and node != node.right.p: 329 | return 0, False 330 | 331 | # check children are ok 332 | left_counts, left_ok = is_red_black_node(node.left) 333 | if not left_ok: 334 | return 0, False 335 | right_counts, right_ok = is_red_black_node(node.right) 336 | if not right_ok: 337 | return 0, False 338 | 339 | # check children's counts are ok 340 | if left_counts != right_counts: 341 | return 0, False 342 | return left_counts, True 343 | else: 344 | return 0, True 345 | 346 | num_black, is_ok = is_red_black_node(self.root) 347 | return is_ok and not self.root._red 348 | 349 | # Main function 350 | if __name__ == "__main__": 351 | for _ in range(int(raw_input())): 352 | # Input 353 | N, Q = map(int, raw_input().split()) 354 | h = map(int, raw_input().split()) 355 | for _ in xrange(Q): 356 | a, b = map(int, raw_input().split()) 357 | rbt = rbtree() 358 | for iter in xrange(a, b+1): 359 | rbt.insert_key(h[iter]) 360 | print rbt.maximum().key - rbt.minimum().key 361 | -------------------------------------------------------------------------------- /NERD2/rlakim5521_nerd2.py: -------------------------------------------------------------------------------- 1 | # NERD2 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | class rbnode(object): 5 | """ 6 | A node in a red black tree. See Cormen, Leiserson, Rivest, Stein 2nd edition pg 273. 7 | """ 8 | 9 | def __init__(self, problem, ramen): 10 | "Construct." 11 | self._problem = problem 12 | self._ramen = ramen 13 | self._red = False 14 | self._left = None 15 | self._right = None 16 | self._p = None 17 | 18 | problem = property(fget=lambda self: self._problem, doc="The node's problem") 19 | ramen = property(fget=lambda self: self._ramen, doc="The node's ramen") 20 | red = property(fget=lambda self: self._red, doc="Is the node red?") 21 | left = property(fget=lambda self: self._left, doc="The node's left child") 22 | right = property(fget=lambda self: self._right, doc="The node's right child") 23 | p = property(fget=lambda self: self._p, doc="The node's parent") 24 | 25 | def __str__(self): 26 | "String representation." 27 | return str(self.problem) + " " + str(self.ramen) 28 | 29 | 30 | def __repr__(self): 31 | "String representation." 32 | return str(self.problem) + " " + str(self.ramen) 33 | 34 | 35 | class rbtree(object): 36 | """ 37 | A red black tree. See Cormen, Leiserson, Rivest, Stein 2nd edition pg 273. 38 | """ 39 | 40 | 41 | def __init__(self, create_node=rbnode): 42 | "Construct." 43 | 44 | self._nil = create_node(problem=None, ramen=None) 45 | "Our nil node, used for all leaves." 46 | 47 | self._root = self.nil 48 | "The root of the tree." 49 | 50 | self._create_node = create_node 51 | "A callable that creates a node." 52 | 53 | self._size = 0 54 | 55 | 56 | root = property(fget=lambda self: self._root, doc="The tree's root node") 57 | nil = property(fget=lambda self: self._nil, doc="The tree's nil node") 58 | 59 | 60 | def size(self): 61 | return self._size 62 | 63 | def search(self, problem, x=None): 64 | """ 65 | Search the subtree rooted at x (or the root if not given) iteratively for the key. 66 | 67 | @return: self.nil if it cannot find it. 68 | """ 69 | if None == x: 70 | x = self.root 71 | while x != self.nil and problem != x.problem: 72 | if problem < x.problem: 73 | x = x.left 74 | else: 75 | x = x.right 76 | return x 77 | 78 | 79 | def minimum(self, x=None): 80 | """ 81 | @return: The minimum value in the subtree rooted at x. 82 | """ 83 | if None == x: 84 | x = self.root 85 | while x.left != self.nil: 86 | x = x.left 87 | return x 88 | 89 | 90 | def maximum(self, x=None): 91 | """ 92 | @return: The maximum value in the subtree rooted at x. 93 | """ 94 | if None == x: 95 | x = self.root 96 | while x.right != self.nil: 97 | x = x.right 98 | return x 99 | 100 | 101 | def insert_key(self, problem, ramen): 102 | "Insert the key into the tree." 103 | self.insert_node(self._create_node(problem=problem, ramen=ramen)) 104 | 105 | 106 | def insert_node(self, z): 107 | "Insert node z into the tree." 108 | y = self._nil 109 | x = self._root 110 | while x != self._nil: 111 | y = x 112 | if z.problem > x.problem and z.ramen > x.ramen: 113 | # x is not a nerd. So, delete x and try inserting z again. 114 | self.delete_node(x) 115 | self.insert_node(z) 116 | return 117 | elif z.problem <= x.problem and z.ramen >= x.ramen: 118 | x = x.left 119 | elif z.problem >= x.problem and z.ramen <= x.ramen: 120 | x = x.right 121 | else: 122 | pass 123 | z._p = y 124 | if y == self.nil: 125 | self._root = z 126 | elif z.problem < y.problem: 127 | y._left = z 128 | else: 129 | y._right = z 130 | z._left = self.nil 131 | z._right = self.nil 132 | z._red = True 133 | self._insert_fixup(z) 134 | self._size = self._size + 1 135 | 136 | def delete_node(self, z): 137 | y = None 138 | x = None 139 | 140 | if z._left == self._nil or z._right == self._nil: 141 | y = z 142 | else: 143 | y = self.get_successor(z) 144 | 145 | if y._left == self._nil: 146 | x = y._right 147 | else: 148 | x = y._left 149 | 150 | if x != None and y != None: 151 | x._p = y._p 152 | if self._root == x._p: 153 | self._root._left = x 154 | else: 155 | if y == y._p._left: 156 | y._p._left = x 157 | else: 158 | y._p._right = x 159 | 160 | if y != z: 161 | if not y._red and x != None: 162 | self.delete_fixup(x) 163 | 164 | y._left = z._left 165 | y._right = z._right 166 | y._p = z._p 167 | y._red = z._red 168 | z._left._p = z._right._p = y 169 | if z == z._p._left: 170 | z._p._left = y 171 | else: 172 | z._p._right = y 173 | else: 174 | if not y.red and x != None: 175 | self.delete_fixup(x) 176 | 177 | if self._root == z: 178 | self._root = self._nil 179 | 180 | self._size = self._size - 1 181 | 182 | def delete_fixup(self, x): 183 | root = self._root._left 184 | w = None 185 | 186 | while not x._red and root != x: 187 | if x == x._p._left: 188 | w = x._p._right 189 | if w._red: 190 | w._red = False 191 | x._p._red = True 192 | self._left_rotate(x.p) 193 | w = x._p._right 194 | if not w._right._red and not w.left.red: 195 | w._red = True 196 | x = x._p 197 | else: 198 | if not w._right._red: 199 | w._left._red = False 200 | w._red = True 201 | self._right_rotate(w) 202 | w = x._p._right 203 | w._red = x._p._red 204 | x._p._red = False 205 | w._right._red = False 206 | self._left_rotate(x._p) 207 | x = root 208 | else: 209 | w = x._p._left 210 | if w._red: 211 | w._red = False 212 | x._p._red = True 213 | self._right_rotate(x._p) 214 | w = x._p._left 215 | if not w._right._red and not w._left._red: 216 | w._red = True 217 | x = x._p 218 | else: 219 | if not w._left._red: 220 | w._right._red = False 221 | w._red = True 222 | self._left_rotate(w) 223 | w = x._p._left 224 | w._red = x._p._red 225 | x._p._red = False 226 | w._left._red = False 227 | self._right_rotate(x._p) 228 | x = root 229 | 230 | x._red = False 231 | 232 | def get_successor(self, x): 233 | y = None 234 | 235 | y = x._right 236 | if self._nil != y: 237 | while y._left != self._nil: 238 | y = y._left 239 | return y 240 | else: 241 | y = x._p 242 | while x == y._right: 243 | x = y 244 | y = y._p 245 | if y == self._root: 246 | return self._nil 247 | return y 248 | 249 | def _insert_fixup(self, z): 250 | "Restore red-black properties after insert." 251 | while z.p.red: 252 | if z.p == z.p.p.left: 253 | y = z.p.p.right 254 | if y.red: 255 | z.p._red = False 256 | y._red = False 257 | z.p.p._red = True 258 | z = z.p.p 259 | else: 260 | if z == z.p.right: 261 | z = z.p 262 | self._left_rotate(z) 263 | z.p._red = False 264 | z.p.p._red = True 265 | self._right_rotate(z.p.p) 266 | else: 267 | y = z.p.p.left 268 | if y.red: 269 | z.p._red = False 270 | y._red = False 271 | z.p.p._red = True 272 | z = z.p.p 273 | else: 274 | if z == z.p.left: 275 | z = z.p 276 | self._right_rotate(z) 277 | z.p._red = False 278 | z.p.p._red = True 279 | self._left_rotate(z.p.p) 280 | self.root._red = False 281 | 282 | def _left_rotate(self, x): 283 | "Left rotate x." 284 | y = x.right 285 | x._right = y.left 286 | if y.left != self.nil: 287 | y.left._p = x 288 | y._p = x.p 289 | if x.p == self.nil: 290 | self._root = y 291 | elif x == x.p.left: 292 | x.p._left = y 293 | else: 294 | x.p._right = y 295 | y._left = x 296 | x._p = y 297 | 298 | 299 | def _right_rotate(self, y): 300 | "Left rotate y." 301 | x = y.left 302 | y._left = x.right 303 | if x.right != self.nil: 304 | x.right._p = y 305 | x._p = y.p 306 | if y.p == self.nil: 307 | self._root = x 308 | elif y == y.p.right: 309 | y.p._right = x 310 | else: 311 | y.p._left = x 312 | x._right = y 313 | y._p = x 314 | 315 | 316 | def check_invariants(self): 317 | "@return: True iff satisfies all criteria to be red-black tree." 318 | 319 | def is_red_black_node(node): 320 | "@return: num_black" 321 | # check has _left and _right or neither 322 | if (node.left and not node.right) or (node.right and not node.left): 323 | return 0, False 324 | 325 | # check leaves are black 326 | if not node.left and not node.right and node.red: 327 | return 0, False 328 | 329 | # if node is red, check children are black 330 | if node.red and node.left and node.right: 331 | if node.left.red or node.right.red: 332 | return 0, False 333 | 334 | # descend tree and check black counts are balanced 335 | if node.left and node.right: 336 | 337 | # check children's parents are correct 338 | if self.nil != node.left and node != node.left.p: 339 | return 0, False 340 | if self.nil != node.right and node != node.right.p: 341 | return 0, False 342 | 343 | # check children are ok 344 | left_counts, left_ok = is_red_black_node(node.left) 345 | if not left_ok: 346 | return 0, False 347 | right_counts, right_ok = is_red_black_node(node.right) 348 | if not right_ok: 349 | return 0, False 350 | 351 | # check children's counts are ok 352 | if left_counts != right_counts: 353 | return 0, False 354 | return left_counts, True 355 | else: 356 | return 0, True 357 | 358 | num_black, is_ok = is_red_black_node(self.root) 359 | return is_ok and not self.root._red 360 | 361 | # Main function 362 | if __name__ == "__main__": 363 | for _ in range(int(raw_input())): 364 | # Input 365 | N = int(raw_input()) 366 | result = 0 367 | rbt = rbtree() 368 | 369 | # Solve 370 | for _ in xrange(N): 371 | p, q = map(int, raw_input().split()) 372 | rbt.insert_key(p, q) 373 | result = result + rbt.size() 374 | 375 | # Output 376 | print result 377 | -------------------------------------------------------------------------------- /NUMB3RS/cccc612_numb3rs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | author: Minchul Jung(ccc612@gmail.com) 3 | problem: NUMB3RS 4 | link: https://algospot.com/judge/problem/read/NUMB3RS 5 | solution description 6 | 1) push 1.0 probability on start town 7 | 2) retrive last probability dictionary (prob) 8 | 2-1) calculate next probability 9 | [current towns probability] * 1.0 / [sum of roads to next town] 10 | 2-2) if there is aready calculated probability, sum up each probability 11 | 3) repeat 2) until last day 12 | 4) return probabilities want to know (r_town) 13 | ''' 14 | 15 | def get_numb3rs(towns, r_town, start, day): 16 | prob = {start:1.0} 17 | 18 | for _ in xrange(day): 19 | tmp_prob = {} 20 | for town in prob.keys(): 21 | tot = float(sum(towns[town])) 22 | for i, isRoad in enumerate(towns[town]): 23 | if isRoad == 1: 24 | c_prob = prob[town] * (1.0 / tot) 25 | if i not in tmp_prob: 26 | tmp_prob[i] = c_prob 27 | else: 28 | tmp_prob[i] += c_prob 29 | prob = tmp_prob 30 | 31 | result = [] 32 | for t in r_town: 33 | if t in prob: 34 | result.append(prob[t]) 35 | else: 36 | result.append(0.0) 37 | 38 | return result 39 | 40 | 41 | # process input 42 | splitInput = lambda :map(int, raw_input().split()) 43 | 44 | tc = int(raw_input()) 45 | 46 | for _ in xrange(tc): 47 | town, day, start = splitInput() 48 | 49 | # read town roads 50 | towns = [] 51 | for _ in xrange(town): 52 | towns.append( splitInput() ) 53 | 54 | raw_input() # pass the number of town to print result 55 | r_town = splitInput() 56 | 57 | result = get_numb3rs(towns, r_town, start, day) 58 | 59 | print(" ".join( map(lambda x : "%.8f" % round(x, 8), result))) 60 | -------------------------------------------------------------------------------- /NUMB3RS/in.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 5 2 0 3 | 0 1 1 1 0 4 | 1 0 0 0 1 5 | 1 0 0 0 0 6 | 1 0 0 0 0 7 | 0 1 0 0 0 8 | 3 9 | 0 2 4 10 | 8 2 3 11 | 0 1 1 1 0 0 0 0 12 | 1 0 0 1 0 0 0 0 13 | 1 0 0 1 0 0 0 0 14 | 1 1 1 0 1 1 0 0 15 | 0 0 0 1 0 0 1 1 16 | 0 0 0 1 0 0 0 1 17 | 0 0 0 0 1 0 0 0 18 | 0 0 0 0 1 1 0 0 19 | 4 20 | 3 1 2 6 21 | -------------------------------------------------------------------------------- /NUMB3RS/input.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 5 2 0 3 | 0 1 1 1 0 4 | 1 0 0 0 1 5 | 1 0 0 0 0 6 | 1 0 0 0 0 7 | 0 1 0 0 0 8 | 3 9 | 0 2 4 10 | 8 2 3 11 | 0 1 1 1 0 0 0 0 12 | 1 0 0 1 0 0 0 0 13 | 1 0 0 1 0 0 0 0 14 | 1 1 1 0 1 1 0 0 15 | 0 0 0 1 0 0 1 1 16 | 0 0 0 1 0 0 0 1 17 | 0 0 0 0 1 0 0 0 18 | 0 0 0 0 1 1 0 0 19 | 4 20 | 3 1 2 6 21 | -------------------------------------------------------------------------------- /NUMB3RS/output.txt: -------------------------------------------------------------------------------- 1 | 0.83333333 0.00000000 0.16666667 2 | 0.43333333 0.06666667 0.06666667 0.06666667 -------------------------------------------------------------------------------- /NUMB3RS/returns_numb3rs.py: -------------------------------------------------------------------------------- 1 | 2 | class City : 3 | def __init__( self, aID ) : 4 | self.mID = aID 5 | self.mConnectCityList = [] 6 | self.mConnectCityCount = 0 7 | 8 | def addConnectCity( self, aID ) : 9 | self.mConnectCityList.append( aID ) 10 | self.mConnectCityCount = self.mConnectCityCount + 1 11 | 12 | def getID( self ) : 13 | return self.mID 14 | 15 | def getConnectCityCount( self ) : 16 | return self.mConnectCityCount 17 | 18 | def getConnectCityList( self ) : 19 | return self.mConnectCityList 20 | 21 | 22 | def printDebug( aList ) : 23 | sStr = '' 24 | for i in range( len(aList) ) : 25 | if aList[i] != 0 : 26 | sStr = sStr + " Index: " + str(i) + " Data: " + str(aList[i]) + " " 27 | 28 | print sStr 29 | 30 | def getChanceRate( aCityList, 31 | aCityIndex, 32 | aChance ) : 33 | 34 | sBaseCity = aCityList[aCityIndex] 35 | sConnectCityList = sBaseCity.getConnectCityList(); 36 | sChanceList = [ 0.0 ] * len( aCityList ) 37 | 38 | for sIndex in range( len(sConnectCityList) ) : 39 | sCityIndex = sConnectCityList[sIndex] 40 | sID = aCityList[sCityIndex].getID() 41 | sChance = aChance / sBaseCity.getConnectCityCount() 42 | sChanceList[sID] = sChance 43 | 44 | return sChanceList 45 | 46 | 47 | def getChanceList( aCityList, 48 | aRemainDay, 49 | aChanceList ) : 50 | 51 | if aRemainDay == 0 : 52 | return aChanceList 53 | 54 | sSumChanceList = [ 0.0 ] * len( aCityList ) 55 | 56 | for sCityIndex in range( len(aChanceList) ) : 57 | if ( aChanceList[sCityIndex] != 0 ) : 58 | 59 | sChanceList = getChanceRate( aCityList, 60 | sCityIndex, 61 | aChanceList[sCityIndex] ) 62 | 63 | sSumChanceList = [ n1 + n2 for n1, n2 in zip( sSumChanceList, sChanceList ) ] 64 | 65 | return getChanceList( aCityList, aRemainDay-1, sSumChanceList ) 66 | 67 | def solve( ) : 68 | sTestCaseCount = input() 69 | 70 | for i in range( sTestCaseCount ) : 71 | 72 | sInput = raw_input() 73 | sInputList = sInput.split() 74 | 75 | sRowCount = int( sInputList[0] ) 76 | sRemainDay = int( sInputList[1] ) 77 | sStartCity = int( sInputList[2] ) 78 | 79 | sCityList = [ 0 ] * sRowCount 80 | 81 | for sRowIndex in range( sRowCount ) : 82 | sInput = raw_input() 83 | sInputList = sInput.split() 84 | 85 | sCity = City( int(sRowIndex) ) 86 | 87 | for sColumnIndex in range( sRowCount ) : 88 | sTempIndex = int( sInputList[sColumnIndex] ) 89 | if sTempIndex != 0 : 90 | sCity.addConnectCity( sColumnIndex ) 91 | 92 | sCityList[sRowIndex] = sCity 93 | 94 | sChanceList = getChanceRate( sCityList, 95 | sStartCity, 96 | 1.0 ) 97 | 98 | sChanceList = getChanceList( sCityList, 99 | sRemainDay - 1, 100 | sChanceList ) 101 | 102 | sOutputCout = input() 103 | sInput = raw_input() 104 | sInputList = sInput.split() 105 | 106 | print ' '.join( format( sChanceList[int(sItem)], '.8f' ) for sItem in sInputList ) 107 | 108 | solve() 109 | -------------------------------------------------------------------------------- /NUMB3RS/rlakim5521_numb3rs.py: -------------------------------------------------------------------------------- 1 | # NUMB3RS 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | # Main function 5 | def MainFunction(): 6 | if __name__ == "__main__": 7 | for _ in xrange(input()): 8 | # Input 9 | numberOfTowns, daysAfterEscaping, townNumberOfPrison = map(int, raw_input().split()) 10 | mapOfTowns = [[0.0] * numberOfTowns for _ in range(numberOfTowns)] 11 | 12 | for row in xrange(numberOfTowns): 13 | mapOfTowns[row] = map(float, raw_input().split()) 14 | 15 | sumOfCol = [sum(mapOfTowns[col]) for col in range(numberOfTowns)] 16 | 17 | for col in xrange(numberOfTowns): 18 | for row in range(numberOfTowns): 19 | mapOfTowns[row][col] = mapOfTowns[row][col] / sumOfCol[col] 20 | 21 | numberOfCalculations = int(raw_input()) 22 | townNumberOfCalculatedTown = [0] * numberOfCalculations 23 | townNumberOfCalculatedTown = map(int, raw_input().split()) 24 | probabilitiesDrDunibalHiding = [[0.0] * numberOfTowns for _ in range(daysAfterEscaping + 1)] 25 | 26 | # Sets a initial value 27 | probabilitiesDrDunibalHiding[0][townNumberOfPrison] = 1.0 28 | 29 | # Gets the numbers of cases that Dr. Dunibal hided in each town at each moment 30 | for dayAfterEscaping in xrange(1, daysAfterEscaping + 1): 31 | for townNumber in xrange(numberOfTowns): 32 | probabilitiesDrDunibalHiding[dayAfterEscaping][townNumber] = \ 33 | sum([a*b for a,b in zip(probabilitiesDrDunibalHiding[dayAfterEscaping - 1], mapOfTowns[townNumber])]) 34 | 35 | # Output 36 | for _ in range(len(townNumberOfCalculatedTown)): 37 | print probabilitiesDrDunibalHiding[daysAfterEscaping][townNumberOfCalculatedTown[_]], 38 | print 39 | 40 | MainFunction() 41 | -------------------------------------------------------------------------------- /NUMBERGAME/cjm9236_NUMBERGAME.py: -------------------------------------------------------------------------------- 1 | # NUMBERGAME problem 2 | # Author: JeongminCha (cjm9236@me.com) 3 | cache = None 4 | seq = None 5 | 6 | def optimal_score(left, right): 7 | if (right-left) == 0: 8 | return seq[left] 9 | elif (right-left) == 1: 10 | return abs(seq[left]-seq[right]) 11 | 12 | found = cache[left][right] 13 | if found != -1: 14 | return found 15 | 16 | possible_score = [0] * 4 17 | possible_score[0] = seq[left] - optimal_score(left+1, right) 18 | possible_score[1] = seq[right] - optimal_score(left, right-1) 19 | possible_score[2] = 0 - optimal_score(left+2, right) 20 | possible_score[3] = 0 - optimal_score(left, right-2) 21 | 22 | mx = max(possible_score) 23 | cache[left][right] = mx 24 | return mx 25 | 26 | if __name__ == "__main__": 27 | test_case = int(raw_input()) 28 | 29 | for case in range(test_case): 30 | n = int(raw_input()) 31 | seq = map(int, raw_input().split(' ')) 32 | cache = [[-1]*n for _ in range(n)] 33 | 34 | result = optimal_score(0, n-1) 35 | print(result) 36 | -------------------------------------------------------------------------------- /NUMBERGAME/input.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 5 3 | -1000 -1000 -3 -1000 -1000 4 | 6 5 | 100 -1000 -1000 100 -1000 -1000 6 | 10 7 | 7 -5 8 5 1 -4 -8 6 7 9 -------------------------------------------------------------------------------- /NUMBERGAME/markers_NUMBERGAME.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 1. 26. 5 | ''' 6 | 7 | import sys 8 | 9 | rl = lambda : sys.stdin.readline() 10 | 11 | numberList = None 12 | check_number = None 13 | 14 | 15 | def number_game(left,right): 16 | 17 | result = [ -sys.maxint ] * 4 18 | 19 | if left > right: 20 | return 0 21 | 22 | if check_number[left][right] != None: 23 | return check_number[left][right] 24 | 25 | result[0] = (numberList[left]-number_game(left+1,right)) 26 | result[1] = (numberList[right]-number_game(left,right-1)) 27 | 28 | if right - left + 1 >= 2: 29 | result[2] = (0-number_game(left+2,right)) 30 | result[3] = (0-number_game(left,right-2)) 31 | 32 | check_number[left][right] = max(result) 33 | 34 | return check_number[left][right] 35 | 36 | 37 | 38 | if __name__ == "__main__": 39 | testCase = int(rl()) 40 | for tc in xrange(testCase): 41 | numberSize = int(rl()) 42 | 43 | numberList = map(int, rl().split()) 44 | 45 | check_number = [ [ None for x in range(numberSize) ] for x in range( 46 | numberSize) ] 47 | 48 | print number_game(0, numberSize-1) 49 | -------------------------------------------------------------------------------- /NUMBERGAME/output.txt: -------------------------------------------------------------------------------- 1 | -1000 2 | 1100 3 | 7 -------------------------------------------------------------------------------- /PACKING/rlakim5521_packing.py: -------------------------------------------------------------------------------- 1 | # PACKING 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | 5 | def pack(capacity, item, numberOfItem, optimalTable, itemVolume, itemUrgency): 6 | if(item > numberOfItem): return 0 7 | if(optimalTable[item][capacity] != 0): return optimalTable[item][capacity]; 8 | optimalTable[item][capacity] = pack(capacity, item + 1, numberOfItem, optimalTable, itemVolume, itemUrgency) 9 | if(capacity >= itemVolume[item]): 10 | optimalTable[item][capacity] = max(optimalTable[item][capacity], pack(capacity - itemVolume[item], item + 1, numberOfItem, optimalTable, itemVolume, itemUrgency) + itemUrgency[item]) 11 | return optimalTable[item][capacity] 12 | 13 | def reconstruct(capacity, item, portableItems, numberOfItem, optimalTable, itemVolume, itemUrgency, itemName): 14 | if(item > numberOfItem): return portableItems 15 | if(pack(capacity, item, numberOfItem, optimalTable, itemVolume, itemUrgency) == pack(capacity, item + 1, numberOfItem, optimalTable, itemVolume, itemUrgency)): 16 | reconstruct(capacity, item + 1, portableItems, numberOfItem, optimalTable, itemVolume, itemUrgency, itemName) 17 | else: 18 | portableItems.append(itemName[item]) 19 | reconstruct(capacity - itemVolume[item], item + 1, portableItems, numberOfItem, optimalTable, itemVolume, itemUrgency, itemName) 20 | return portableItems 21 | 22 | # Main function 23 | def MainFunction(): 24 | if __name__ == "__main__": 25 | for _ in xrange(input()): 26 | numberOfItem, maxCapacity = map(int, raw_input().split()) 27 | 28 | # First row is a row for the maximum urgency and 29 | # the others are used to show whether the item is packed or not. 30 | optimalTable = [[0] * (maxCapacity + 1) for _ in range(numberOfItem + 1)] 31 | itemName = {} 32 | itemVolume = {} 33 | itemUrgency = {} 34 | 35 | # Inserts input data into dictionaries 36 | for item in xrange(1, numberOfItem + 1): 37 | itemName[item], tempVolume, tempUrgency = raw_input().split() 38 | itemVolume[item] = int(tempVolume) 39 | itemUrgency[item] = int(tempUrgency) 40 | 41 | maxUrgency = pack(maxCapacity, 1, numberOfItem, optimalTable, itemVolume, itemUrgency) 42 | 43 | # Adds used items into list 44 | portableItems = [] 45 | portableItems = reconstruct(maxCapacity, 1, portableItems, numberOfItem, optimalTable, itemVolume, itemUrgency, itemName) 46 | 47 | # Output 48 | print maxUrgency, len(portableItems) 49 | for item in range(len(portableItems)): 50 | print portableItems[item] 51 | 52 | MainFunction() 53 | -------------------------------------------------------------------------------- /PACKING/rlakim5521_packing_jk.py: -------------------------------------------------------------------------------- 1 | # PACKING 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | # Gets a max capacity of received capacity and returns the optimal table 5 | def getMaxCapacity(maxCapacity, optimalTable, itemVolume, itemUrgency, numberOfItem): 6 | 7 | for capacity in xrange(1, maxCapacity + 1): 8 | # Default case is adding nothing. 9 | for item in xrange(numberOfItem + 1): 10 | optimalTable[item][capacity] = optimalTable[item][capacity - 1] 11 | 12 | # Compares urgencies of all possible cases. 13 | for item in xrange(1, numberOfItem + 1): 14 | if(capacity - itemVolume[item] >= 0): 15 | if(optimalTable[item][capacity - itemVolume[item]] == 0): 16 | if(optimalTable[0][capacity] < optimalTable[0][capacity - itemVolume[item]] + itemUrgency[item]): 17 | optimalTable[0][capacity] = optimalTable[0][capacity - itemVolume[item]] + itemUrgency[item] 18 | for item2 in xrange(1, numberOfItem + 1): 19 | optimalTable[item2][capacity] = optimalTable[item2][capacity - itemVolume[item]] 20 | optimalTable[item][capacity] = 1 21 | 22 | # Main function 23 | def MainFunction(): 24 | if __name__ == "__main__": 25 | for _ in xrange(input()): 26 | numberOfItem, maxCapacity = map(int, raw_input().split()) 27 | 28 | # First row is a row for the maximum urgency and 29 | # the others are used to show whether the item is packed or not. 30 | optimalTable = [[0] * (maxCapacity + 1) for _ in range(numberOfItem + 1)] 31 | itemName = {} 32 | itemVolume = {} 33 | itemUrgency = {} 34 | 35 | # Inserts input data into dictionaries 36 | for item in xrange(1, numberOfItem + 1): 37 | itemName[item], tempVolume, tempUrgency = raw_input().split() 38 | itemVolume[item] = int(tempVolume) 39 | itemUrgency[item] = int(tempUrgency) 40 | 41 | getMaxCapacity(maxCapacity, optimalTable, itemVolume, itemUrgency, numberOfItem) 42 | 43 | # Adds used items into list 44 | portableItems = [] 45 | for item in xrange(1, numberOfItem + 1): 46 | if(optimalTable[item][maxCapacity]): 47 | portableItems.append(itemName[item]) 48 | 49 | # Output 50 | print optimalTable[0][maxCapacity], len(portableItems) 51 | for item in range(len(portableItems)): 52 | print portableItems[item] 53 | 54 | MainFunction() 55 | -------------------------------------------------------------------------------- /PI/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/PI/.gitkeep -------------------------------------------------------------------------------- /PI/cjm9236_PI.cpp: -------------------------------------------------------------------------------- 1 | // PI problem 2 | // Author: JeongminCha (cjm9236@me.com) 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | int memo[10001]; 13 | 14 | // Returns True if all elements are same. 15 | bool is_all_same(string str) { 16 | char ch = str.at(0); 17 | for(int index = 0; index < str.size(); index++) { 18 | if (ch != str.at(index)) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | 25 | // Returns True if the input sequence is 26 | // monotonically decreasing or increasing by 1 27 | bool is_monotonic_by_one(string str) { 28 | int diff = str.at(1) - str.at(0); 29 | if (diff != 1 && diff != -1) { 30 | return false; 31 | } 32 | for(int index = 1; index < str.size(); index++) { 33 | char prev = str.at(index-1); 34 | char curr = str.at(index); 35 | if ((curr-prev) != diff) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | 42 | // Returns True if elements in input sequence are alternate. 43 | bool is_alternate(string str) { 44 | for(int index = 2; index < str.size(); index++) { 45 | if (str.at(index) != str.at(index - 2)) { 46 | return false; 47 | } 48 | } 49 | return true; 50 | } 51 | 52 | // Returns True if the input sequence is an arithmetical progression. 53 | bool is_ap(string str) { 54 | for (int index = 1; index < str.size()-1; index++) { 55 | char prev = str.at(index-1); 56 | char curr = str.at(index-0); 57 | char next = str.at(index+1); 58 | if ((next-curr) != (curr-prev)) { 59 | return false; 60 | } 61 | } 62 | return true; 63 | } 64 | 65 | int calc_cost(string target) { 66 | if (is_all_same(target)) { 67 | return 1; 68 | } else if (is_monotonic_by_one(target)) { 69 | return 2; 70 | } else if (is_alternate(target)) { 71 | return 4; 72 | } else if (is_ap(target)) { 73 | return 5; 74 | } else { 75 | return 10; 76 | } 77 | } 78 | 79 | int find_optimal_cost(string str) { 80 | int length = str.size(); 81 | 82 | for(int unit = 3; unit <= 5; unit++) { 83 | memo[unit] = calc_cost(str.substr(0, unit)); 84 | } 85 | 86 | for(int idx = 3; idx < length; idx += 3) { 87 | for(int unit = 3; unit <= 5; unit++) { 88 | int next_idx = idx + unit; 89 | if (next_idx > length) { 90 | break; 91 | } 92 | for(int next_unit = 3; next_unit <= 5; next_unit++) { 93 | int rest = next_idx - next_unit; 94 | if (rest >= 3) { 95 | int cost = memo[rest] + calc_cost(str.substr(rest, next_unit)); 96 | if (memo[next_idx] == 0) { 97 | memo[next_idx] = cost; 98 | } else { 99 | memo[next_idx] = min(cost, memo[next_idx]); 100 | } 101 | } 102 | } 103 | } 104 | } 105 | return memo[length]; 106 | } 107 | 108 | int main() 109 | { 110 | int t; 111 | 112 | cin >> t; 113 | while(t--) { 114 | string input; 115 | cin >> input; 116 | cout << find_optimal_cost(input) << endl; 117 | memset(memo, 0, sizeof(memo)); 118 | } 119 | 120 | return 0; 121 | } -------------------------------------------------------------------------------- /PI/cjm9236_PI.py: -------------------------------------------------------------------------------- 1 | # PI problem 2 | # Author: JeongminCha (cjm9236@me.com) 3 | 4 | # Returns True if all elements are same. 5 | def is_all_same(seq): 6 | return all(cur == next for cur, next in zip(seq[:-1], seq[1:])) 7 | 8 | # Returns True if the input sequence is 9 | # monotonically decreasing or increasing by 1 10 | def is_monotonic_by_one(seq): 11 | return all(next == cur+1 for cur, next in zip(seq[:-1], seq[1:])) \ 12 | or all(next == cur-1 for cur, next in zip(seq[:-1], seq[1:])) 13 | 14 | # Returns True if elements in input sequence are alternate. 15 | def is_alternate(seq): 16 | # If an element and next of next one are always the same, 17 | # the sequence is alternate. 18 | return all(cur == next_next for cur, next_next in zip(seq[:-2], seq[2:])) 19 | 20 | # Returns True if the input sequence is an arithmetical progression. 21 | def is_ap(seq): 22 | return all((next-cur) == (cur-prev) for prev,cur,next in zip(seq[:-2],seq[1:-1],seq[2:])) 23 | 24 | def calculate_cost(seq): 25 | if is_all_same(seq): 26 | return 1 27 | elif is_monotonic_by_one(seq): 28 | return 2 29 | elif is_alternate(seq): 30 | return 4 31 | elif is_ap(seq): 32 | return 5 33 | else: 34 | return 10 35 | 36 | cache = [0 for _ in range(10001)] 37 | 38 | def calculate_min_cost(seq): 39 | for unit in range(3,6): 40 | cache[unit] = calculate_cost(seq[0:unit]) 41 | 42 | for idx in range(3,len(seq),3): 43 | for unit in range(3,6): 44 | next_idx = idx + unit; 45 | if next_idx > len(seq): 46 | break 47 | for next_unit in range(3,6): 48 | rest = next_idx - next_unit; 49 | if rest >= 3: 50 | cost = cache[rest] + calculate_cost(seq[rest: next_idx]) 51 | if cache[next_idx] == 0: 52 | cache[next_idx] = cost 53 | else: 54 | cache[next_idx] = min(cost, cache[next_idx]) 55 | 56 | return cache[len(seq)] 57 | 58 | if __name__ == "__main__": 59 | test_case = int(raw_input()) 60 | 61 | for case in range(test_case): 62 | seq = map(int, list(raw_input())) 63 | result = calculate_min_cost(seq) 64 | print(result) -------------------------------------------------------------------------------- /POLY/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/POLY/.gitkeep -------------------------------------------------------------------------------- /POLY/POLY_JK.py: -------------------------------------------------------------------------------- 1 | # POLY 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | MOD = 10000000 5 | 6 | # Returns a matrix of numbers of polyomino 7 | def getPolyomino(matrix): 8 | for iter in range(1, 101): 9 | matrix[iter][iter] = 1 10 | matrix[1][0] = 1 11 | 12 | for row in range(2, 101): 13 | for col in range(1, row): 14 | matrix[row][1] = matrix[row][1] + col * matrix[row - 1][col] 15 | for col in range(2, 101 - row + 1): 16 | matrix[row + col - 1][col] = matrix[row + col - 2][col - 1] + matrix[row - 1][0] 17 | for col in range(1, row + 1): 18 | matrix[row][0] = matrix[row][0] + matrix[row][col] 19 | 20 | return matrix 21 | 22 | # Create a cache for memoization 23 | matrix = [[0 for col in range(101)] for row in range(101)] 24 | 25 | # Gets a matrix of numbers of polyomino 26 | matrix = getPolyomino(matrix) 27 | 28 | # Main function 29 | if __name__ == "__main__": 30 | caseNumber = int(raw_input()) 31 | 32 | for case in range(caseNumber): 33 | n = int(raw_input()) 34 | 35 | print (matrix[n][0] % MOD) 36 | -------------------------------------------------------------------------------- /POLY/in.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 2 3 | 4 4 | 92 5 | 100 6 | -------------------------------------------------------------------------------- /POLY/jonnung_poly.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | 3 | def poly(remain, prev=None): 4 | global mm 5 | if remain == 0: 6 | return 1 7 | 8 | if mm[prev-1][remain-1]: 9 | return mm[prev-1][remain-1] 10 | 11 | case_sum = 0 12 | for cnt in range(1, remain+1): 13 | case = prev + (cnt - 1) # 가진 정사각형으로 구할 수 있는 경우의 수 14 | next_case = poly(remain - cnt, cnt) 15 | case_sum += case * next_case 16 | 17 | mm[prev-1][remain-1] = case_sum 18 | 19 | return case_sum 20 | 21 | 22 | if __name__ == '__main__': 23 | tc = int(raw_input()) 24 | mm = [[0 for j in xrange(100 - i)] for i in xrange(100) if i > 0] 25 | 26 | for t in xrange(tc): 27 | square_cnt = int(raw_input()) 28 | p_sum = range(square_cnt+1) 29 | 30 | for n in range(1, square_cnt+1): 31 | m = square_cnt - n 32 | p_sum[n] = poly(m, n) # n 를 기준으로 아래오는 정사각형들의 조합의 수를 반환 33 | 34 | total_sum = sum(p_sum) 35 | 36 | if total_sum >= 10000000: 37 | print(total_sum % 10000000) 38 | else: 39 | print(total_sum) 40 | -------------------------------------------------------------------------------- /POLY/returns_poly.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/POLY/returns_poly.cpp -------------------------------------------------------------------------------- /POLY/returns_poly.py: -------------------------------------------------------------------------------- 1 | 2 | gPolyMatrix = [ [ int(0) for i in range(101) ] for i in range(101) ] 3 | 4 | 5 | def getPolyMatrixValue( aColumn, aTarget ) : 6 | 7 | global gPolyMatrix 8 | sValue = 0 9 | 10 | for sColumnIndex in range( 1, aTarget - aColumn + 1 ) : 11 | sTempValue = gPolyMatrix[aTarget-aColumn][sColumnIndex] * ( aColumn + sColumnIndex - 1 ) 12 | sValue = sValue + sTempValue 13 | 14 | return sValue % 10000000 15 | 16 | def getPolyValue( aValue ) : 17 | 18 | global gPolyMatrix 19 | sValue = 0 20 | 21 | for i in range( 1, aValue + 1 ): 22 | sValue += gPolyMatrix[aValue][i] 23 | 24 | return sValue % 10000000 25 | 26 | def getPolyMatrix( aCount ) : 27 | 28 | global gPolyMatrix 29 | sValue = 0 30 | 31 | for sRowIndex in range( 1, aCount + 1 ) : 32 | for sColumnIndex in range( 1, sRowIndex + 1 ) : 33 | if sRowIndex is sColumnIndex : 34 | sValue = 1 35 | else : 36 | sValue = getPolyMatrixValue( sColumnIndex, sRowIndex ) 37 | 38 | gPolyMatrix[sRowIndex][sColumnIndex] = sValue 39 | 40 | gPolyMatrix[sRowIndex][0] = getPolyValue( sRowIndex ) 41 | 42 | def solve() : 43 | 44 | global gPolyMatrix 45 | 46 | sCount = input() 47 | 48 | for i in range( sCount ) : 49 | sValue = input() 50 | 51 | if gPolyMatrix[sValue][0] is 0 : 52 | getPolyMatrix( sValue ) 53 | 54 | print gPolyMatrix[sValue][0] 55 | 56 | solve() 57 | -------------------------------------------------------------------------------- /POTION/j2h_Potion.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Potion(): 4 | def doSolve(self, n, p): # n: Ratio, p: Now input 5 | minRatio = self.getMinRatio(n) 6 | maxP = max(p) 7 | maxIdx = p.index(maxP) 8 | 9 | powerOf = maxP/minRatio[maxIdx] 10 | ratio = map(lambda x: powerOf*x, minRatio) 11 | 12 | while True: 13 | minIdx = ratio.index(min(ratio)) 14 | if self.list1BiggerThenList2(ratio, p): 15 | return [a - b for a, b in zip(ratio, p)] 16 | else: 17 | powerOf = powerOf + 1 18 | ratio = map(lambda x: powerOf*x, minRatio) 19 | 20 | def list1BiggerThenList2(self, l1, l2): 21 | for idx in range(len(l1)): 22 | if l1[idx] < l2[idx]: 23 | return False 24 | return True 25 | 26 | def _getGCD(self, a, b): # Euclidean Algorithm 27 | while (b != 0): 28 | t = a%b 29 | a = b 30 | b = t 31 | return abs(a) 32 | 33 | def getGCD(self, l): 34 | gcd = l[:] 35 | while(len(gcd) > 1): 36 | first = gcd.pop() 37 | second = gcd.pop() 38 | gcd.append(self._getGCD(first, second)) 39 | return gcd[0] 40 | 41 | def getMinRatio(self, l): 42 | gcd = self.getGCD(l) 43 | return map(lambda x: x / gcd, l) 44 | 45 | if __name__ == '__main__': 46 | TC = int(raw_input()) 47 | INDEX = 0 48 | answerList = [] 49 | 50 | while INDEX < TC: 51 | raw_input() # skip 52 | n = [int(x) for x in raw_input().split(" ")] 53 | p = [int(x) for x in raw_input().split(" ")] 54 | answerList.append(Potion().doSolve(n, p)) 55 | INDEX = INDEX + 1 56 | 57 | for answer in answerList: 58 | print(' '.join(str(p) for p in answer).strip()) 59 | -------------------------------------------------------------------------------- /POTION/j2h_PotionTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import time 4 | import unittest 5 | from j2h_Potion import Potion 6 | 7 | class PotionTest(unittest.TestCase): 8 | n_1 = [4, 6, 2, 4] 9 | p_1 = [6, 4, 2, 4] 10 | n_2 = [4, 6, 2, 4] 11 | p_2 = [7, 4, 2, 4] 12 | n_3 = [4, 5, 6] 13 | p_3 = [1, 2, 3] 14 | 15 | answer_1 = [0, 5, 1, 2] 16 | answer_2 = [1, 8, 2, 4] 17 | answer_3 = [3, 3, 3] 18 | 19 | def setUp(self): 20 | self.startTime = time.time() 21 | print 22 | 23 | def tearDown(self): 24 | print("{0}: {1}".format(self.id(), time.time() - self.startTime)) 25 | 26 | def testCase1(self): 27 | self.assertEquals(self.answer_1, Potion().doSolve(self.n_1, self.p_1)) 28 | 29 | def testCase2(self): 30 | self.assertEquals(self.answer_2, Potion().doSolve(self.n_2, self.p_2)) 31 | 32 | def testCase3(self): 33 | self.assertEquals(self.answer_3, Potion().doSolve(self.n_3, self.p_3)) 34 | 35 | def testGetMinRatio(self): 36 | self.assertEquals([1,1,2], Potion().getMinRatio([2,2,4])) 37 | self.assertEquals([1,2,3], Potion().getMinRatio([10,20,30])) 38 | self.assertEquals([2,1,4], Potion().getMinRatio([2,1,4])) 39 | self.assertEquals([2,3,1,2], Potion().getMinRatio([4,6,2,4])) 40 | self.assertEquals([4,5,6], Potion().getMinRatio([4,5,6])) 41 | 42 | 43 | def testGetGCD(self): 44 | self.assertEquals(3, Potion().getGCD([3,6])) 45 | self.assertEquals(3, Potion().getGCD([3,6,9])) 46 | self.assertEquals(5, Potion().getGCD([10,15,20,30,25])) 47 | self.assertNotEquals(5, Potion().getGCD([10,13])) 48 | self.assertNotEquals(2, Potion().getGCD([10,13,5])) 49 | 50 | if __name__ == '__main__': 51 | totalSuite = unittest.TestLoader().loadTestsFromTestCase(PotionTest) 52 | suite = unittest.TestSuite() 53 | suite.addTest(PotionTest('testGetGCD')) 54 | suite.addTest(PotionTest('testGetMinRatio')) 55 | suite.addTest(PotionTest('testCase1')) 56 | suite.addTest(PotionTest('testCase2')) 57 | suite.addTest(PotionTest('testCase3')) 58 | unittest.TextTestRunner(verbosity=2).run(suite) 59 | unittest.TextTestRunner(verbosity=2).run(totalSuite) 60 | 61 | -------------------------------------------------------------------------------- /POTION/rlakim5521_potion.py: -------------------------------------------------------------------------------- 1 | # POTION 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | import copy 5 | 6 | def gcd(a, b): 7 | while (b != 0): 8 | temp = a % b 9 | a = b 10 | b = temp 11 | return abs(a) 12 | 13 | # Main function 14 | if __name__ == "__main__": 15 | for _ in range(int(raw_input())): 16 | # Input 17 | n = int(raw_input()) 18 | materials = map(int, raw_input().split()) 19 | pots = map(int, raw_input().split()) 20 | 21 | # Solve 22 | # Get the greatest common divisor of materials. 23 | gcdOfMaterials = materials[0] 24 | for material in materials: 25 | gcdOfMaterials = gcd(gcdOfMaterials, material) 26 | 27 | # By divide materials by gcd, get the minimum ratios for the potion. 28 | minRatios = copy.deepcopy(materials) 29 | for iter in xrange(n): 30 | minRatios[iter] = minRatios[iter] / gcdOfMaterials 31 | 32 | # To get the magnification, get pots divided by minRatios and round them up. 33 | # The results and gcd are candidates of the magnification. 34 | # After that, make the maximum value of candidates a final magnification. 35 | minMagnifications = copy.deepcopy(pots) 36 | for iter in xrange(n): 37 | minMagnifications[iter] = (minMagnifications[iter] + minRatios[iter] - 1) / minRatios[iter] 38 | finalMagnification = max(gcdOfMaterials,max(minMagnifications)) 39 | 40 | # Calculate the final ratios by multiplying minRatios by finalMagnification. 41 | finalRatios = copy.deepcopy(minRatios) 42 | for iter in xrange(n): 43 | finalRatios[iter] = finalRatios[iter] * finalMagnification 44 | 45 | # Output 46 | # Subtract pots from finalRatios, and print them. 47 | for iter in xrange(n): 48 | print finalRatios[iter] - pots[iter], 49 | print 50 | -------------------------------------------------------------------------------- /PROMISES/free-lunch_PROMISES.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define MAX 987654321 10 | int V, adj[201][201]; 11 | 12 | void floyd(){ 13 | for(int i = 0; i < V; i++ ){ 14 | for(int j = 0; j < V; j++){ 15 | for(int k = 0; k < V; k++){ 16 | adj[i][j] = min(adj[i][j], adj[i][k]+adj[k][j]); 17 | } 18 | } 19 | } 20 | } 21 | 22 | void update(int v1, int v2, int cost){ 23 | for(int i = 0; i < V; i++ ){ 24 | for(int j = 0; j < V; j++){ 25 | adj[i][j] = min(adj[i][j], \ 26 | min(adj[i][v1]+adj[v2][j]+cost,adj[i][v2]+adj[v1][j]+cost)); 27 | } 28 | } 29 | } 30 | 31 | int main(){ 32 | cin.sync_with_stdio(false); 33 | 34 | int T = 0; 35 | int M,N; 36 | 37 | cin >> T; 38 | while(T--){ 39 | cin >> V >> M >> N; 40 | V++; 41 | for(int i = 0; i < V; i++) 42 | for(int j = 0; j < V; j++) 43 | adj[i][j] = MAX; 44 | for(int i = 0; i < V; i++) 45 | adj[i][i] = 0; 46 | 47 | int v1,v2,cost; 48 | for(int i= 0; i < M; i++){ 49 | cin >> v1 >> v2 >> cost; 50 | adj[v1][v2] = cost; 51 | adj[v2][v1] = cost; 52 | } 53 | 54 | int count = 0; 55 | for(int i= 0; i < N; i++){ 56 | cin >> v1 >> v2 >> cost; 57 | if(adj[v1][v2] <= cost) { 58 | count += 1; 59 | continue; 60 | } 61 | update(v1,v2,cost); 62 | } 63 | 64 | cout << count < 8 | 9 | def reverse_quadtree(str_list): 10 | head = str_list.pop(0) 11 | 12 | if head != 'x': 13 | return head 14 | 15 | quad_list = [reverse_quadtree(str_list) for i in range(4)] 16 | 17 | quad_list[0], quad_list[2] = quad_list[2], quad_list[0] 18 | quad_list[1], quad_list[3] = quad_list[3], quad_list[1] 19 | 20 | return 'x' + str.join('', quad_list) 21 | 22 | 23 | if __name__ == '__main__': 24 | test_case = int(raw_input()) 25 | for tc in range(test_case): 26 | compression = list(raw_input()) 27 | print(reverse_quadtree(compression)) 28 | -------------------------------------------------------------------------------- /QUADTREE/jonnung_quadtree_RTE.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | # Songorithm Season3 - Algorithm Problem Solving 3 | # 4 | # algostpot problem: QUADTREE 5 | # date: 15/12/15 6 | # author: jonnung 7 | 8 | 9 | class QuadTree(object): 10 | def __init__(self): 11 | self.parent = None 12 | self.children = [] 13 | self.r_children = [] 14 | self.reverse_node = '' 15 | 16 | def add_child(self, node): 17 | if len(self.children) < 4: 18 | self.children.append(node) 19 | else: 20 | self.parent.add_child(node) 21 | 22 | def reverse_children(self): 23 | self.r_children = self.children[:] 24 | self.r_children[0], self.r_children[2] = self.r_children[2], self.r_children[0] 25 | self.r_children[1], self.r_children[3] = self.r_children[3], self.r_children[1] 26 | 27 | return 'x' + str.join('', [r.reverse_children() if isinstance(r, QuadTree) else r for r in self.r_children]) 28 | 29 | 30 | if __name__ == '__main__': 31 | test_case = int(raw_input()) # 입력1 32 | 33 | for tc in xrange(test_case): 34 | input_line = raw_input() # 입력2 35 | 36 | if not input_line: 37 | print '' 38 | continue 39 | 40 | if input_line[0] != 'x': 41 | print(input_line[0]) 42 | continue 43 | 44 | top_parent_node = None 45 | current_tree = None 46 | 47 | for char in input_line: 48 | if char == 'x': 49 | quad = QuadTree() 50 | if current_tree: 51 | quad.parent = current_tree 52 | current_tree.add_child(quad) 53 | else: 54 | top_parent_node = quad 55 | current_tree = quad 56 | else: 57 | current_tree.add_child(char) 58 | 59 | print(top_parent_node.reverse_children()) 60 | -------------------------------------------------------------------------------- /QUANTIZE/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/QUANTIZE/.gitkeep -------------------------------------------------------------------------------- /QUANTIZE/cjm9236_QUANTIZE.py: -------------------------------------------------------------------------------- 1 | # QUANTIZE problem 2 | # Author: JeongminCha (cjm9236@me.com) 3 | 4 | MAX_VAL = 987654321 5 | 6 | class Quantizer: 7 | def __init__(self, seq, length_seq): 8 | self.length = length_seq 9 | self.p_sum = self.parital_sum(seq) 10 | self.p_squared_sum = self.partial_sqaured_sum(seq) 11 | self.memo = [[-1 for _ in range(10)] for _ in range(self.length)] 12 | 13 | def parital_sum(self, seq): 14 | p_sum = [0 for _ in range(self.length)] 15 | p_sum[0] = seq[0] 16 | for index in range(1, self.length): 17 | p_sum[index] = p_sum[index-1] + seq[index] 18 | return p_sum 19 | 20 | def partial_sqaured_sum(self, seq): 21 | return self.parital_sum([elem ** 2 for elem in seq]) 22 | 23 | # Returns SSE (Sum of Squared Errors) 24 | def calc_sse(self, start, end): 25 | sum = self.p_sum[end] 26 | sq_sum = self.p_squared_sum[end] 27 | if start != 0: 28 | sum = sum - self.p_sum[start-1] 29 | sq_sum = sq_sum - self.p_squared_sum[start-1] 30 | avg = int (float(sum)/(end-start+1) + 0.5) 31 | return sq_sum - 2*avg*sum + avg*avg*(end-start+1) 32 | 33 | # Returns MSSE (Minimum Sum of Squared Errors) for executing the quantization. 34 | def quantize(self, start_idx, num_class): 35 | if start_idx == self.length: 36 | return 0 37 | if num_class == 0: 38 | return MAX_VAL 39 | msse = self.memo[start_idx][num_class - 1] 40 | if msse != -1: 41 | return msse 42 | 43 | msse = self.memo[start_idx][num_class - 1] = MAX_VAL 44 | for end_idx in range(start_idx, self.length): 45 | msse = min(msse, self.calc_sse(start_idx, end_idx) + self.quantize(end_idx+1, num_class-1)) 46 | self.memo[start_idx][num_class-1] = msse 47 | return msse 48 | 49 | if __name__ == "__main__": 50 | # 1. Input the number of test cases. 51 | test_case = int(raw_input()) 52 | 53 | for case in range(test_case): 54 | input = map(int, raw_input().split(' ')) 55 | (length_seq, num_class) = (input[0], input[1]) 56 | 57 | # 3. Input the elements of the sequence. 58 | sorted_seq = sorted(map(int, raw_input().split(' '))) 59 | 60 | quantizer = Quantizer(sorted_seq, length_seq) 61 | result = quantizer.quantize(0, num_class) 62 | print(result) -------------------------------------------------------------------------------- /QUANTIZE/input.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 10 3 3 | 3 3 3 1 2 3 2 2 2 1 4 | 9 3 5 | 1 744 755 4 897 902 890 6 777 -------------------------------------------------------------------------------- /QUANTIZE/jonnung_quantize_RTE.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | 3 | if __name__ == '__main__': 4 | tc = int(raw_input()) 5 | for t in range(tc): 6 | sequence_length, quantize_count = map(int, raw_input().split()) 7 | n_sequence = map(int, raw_input().split()) 8 | 9 | # n_seq를 정렬한다. 10 | n_sequence.sort() 11 | # print(n_sequence) 12 | 13 | # 정렬된 seq를 그룹화 한다. 14 | diff_sequence = [[i-1, i, n_sequence[i] - n_sequence[i-1]] for i in range(1, sequence_length)] 15 | diff_sequence.sort(None, key=lambda diff: diff[2], reverse=True) 16 | 17 | # print(diff_sequence) 18 | 19 | min_sum = 99999999999 20 | for q in range(quantize_count): 21 | grouping = [] 22 | if not q: 23 | grouping.append(n_sequence) 24 | else: 25 | q_cut = diff_sequence[:q] 26 | q_cut.sort(None, key=lambda cut: cut[0]) 27 | 28 | start = 0 29 | for c in range(q): 30 | end = q_cut[c][1] 31 | grouping.append(n_sequence[start:end]) 32 | start = end 33 | grouping.append(n_sequence[start:]) 34 | 35 | # print(grouping) 36 | 37 | group_length = len(grouping) 38 | tmp_min = 0 39 | for g in range(group_length): 40 | avg = int(round(sum(grouping[g]) / float(len(grouping[g])))) 41 | 42 | for s in range(len(grouping[g])): 43 | if avg > grouping[g][s]: 44 | tmp_min += (avg - grouping[g][s])**2 45 | else: 46 | tmp_min += (grouping[g][s] - avg)**2 47 | 48 | if min_sum > tmp_min: 49 | min_sum = tmp_min 50 | 51 | print(min_sum) 52 | -------------------------------------------------------------------------------- /QUANTIZE/output.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 651 -------------------------------------------------------------------------------- /RATIO/input.txt: -------------------------------------------------------------------------------- 1 | 7 2 | 10 8 3 | 100 80 4 | 47 47 5 | 99000 0 6 | 1000000000 470000000 7 | 100 99 8 | 1000000000 0 9 | -------------------------------------------------------------------------------- /RATIO/markers_RATIO.py: -------------------------------------------------------------------------------- 1 | # -*- encoding=utf-8 -*- 2 | # author : markers 3 | ''' 4 | Created by Markers on 2016. 3. 20. 5 | ''' 6 | 7 | from __future__ import division 8 | import sys 9 | import math 10 | 11 | rl = lambda : sys.stdin.readline() 12 | 13 | class Ratio: 14 | 15 | def __init__(self, num_game, win): 16 | self.num_game = num_game 17 | self.win = win 18 | self.ratio = int(self.win * 100 / self.num_game) # int로 변환하면 통과. 19 | # 이유가? 20 | self.low = 0 21 | self.high = 1000000000 22 | 23 | def bisection(self): 24 | """ 25 | 이분법 26 | :return: 27 | """ 28 | if self.ratio >= 99.0: 29 | return -1 30 | 31 | while self.low + 1 < self.high: 32 | self.mid = (self.low+self.high)/2 33 | if self.ratio+1 >= (self.win+self.mid)*100/( 34 | self.num_game+self.mid): 35 | self.low = self.mid 36 | else: 37 | self.high = self.mid 38 | 39 | return round(self.high) 40 | 41 | 42 | def calculate(self): 43 | """ 44 | This method is to find ratio number 45 | X >= N^2 / (99N-100M) 46 | N is num of game 47 | M is win game 48 | 49 | :return: 50 | X 51 | """ 52 | 53 | result = 0 54 | # 기저 사례 검사 -1 55 | # 20억이 넘는 게임을 하면 포기. 56 | if self.ratio >= 99.0: 57 | return -1 58 | 59 | 60 | # result = self.num_game / float( 99 - self.ratio ) 61 | 62 | result = math.ceil((100*self.win-(self.ratio+1)*self.num_game)/(self.ratio-99)) 63 | # 계산 64 | # result = self.num_game**2 / ( 99 * self.num_game - 100 * self.win) 65 | # print "num_game : {} , win_game : {}".format(self.num_game, self.win) 66 | # print "ration : {} ".format(self.ratio) 67 | 68 | if result >= 2000000000: 69 | return -1 70 | 71 | return result 72 | 73 | 74 | 75 | import unittest 76 | 77 | class TestRatio(unittest.TestCase): 78 | 79 | def test_calculate(self): 80 | self.assertEqual(1,Ratio(10,8).calculate()) 81 | self.assertEqual(6,Ratio(100,80).calculate()) 82 | self.assertEqual(-1,Ratio(47,47).calculate()) 83 | self.assertEqual(1000,Ratio(99000,0).calculate()) 84 | self.assertEqual(19230770,Ratio(1000000000,470000000).calculate()) 85 | self.assertEqual(-1,Ratio(100,99).calculate()) 86 | self.assertEqual(10101011,Ratio(1000000000,0).calculate()) 87 | 88 | def test_bisection(self): 89 | self.assertEqual(1,Ratio(10,8).bisection()) 90 | self.assertEqual(6,Ratio(100,80).bisection()) 91 | self.assertEqual(-1,Ratio(47,47).bisection()) 92 | self.assertEqual(1000,Ratio(99000,0).bisection()) 93 | self.assertEqual(19230770,Ratio(1000000000,470000000).bisection()) 94 | self.assertEqual(-1,Ratio(100,99).bisection()) 95 | self.assertEqual(10101011,Ratio(1000000000,0).bisection()) 96 | 97 | 98 | 99 | if __name__ == "__main__": 100 | for tc in xrange(int(rl())): 101 | num_game, win = map(float, rl().rstrip().split()) 102 | # print int(Ratio(num_game, win).calculate()) 103 | print int(Ratio(num_game, win).bisection()) 104 | 105 | 106 | 107 | # unit test 108 | # suite = unittest.TestSuite() 109 | # suite.addTest(TestRatio.test_calculate()) 110 | # suite.addTest(TestRatio.test_bisection()) 111 | 112 | # suite = unittest.TestLoader().loadTestsFromTestCase(TestRatio) 113 | # unittest.TextTestRunner(verbosity=2).run(suite) 114 | -------------------------------------------------------------------------------- /RATIO/output.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 6 3 | -1 4 | 1000 5 | 19230770 6 | -1 7 | 10101011 -------------------------------------------------------------------------------- /RATIO/rlakim5521_ratio.py: -------------------------------------------------------------------------------- 1 | # RATIO 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | # Main function 5 | if __name__ == "__main__": 6 | for _ in range(int(raw_input())): 7 | # Input 8 | N, M = map(int, raw_input().split()) 9 | 10 | baseWinningRate = (M * 100) / N 11 | 12 | # Solve 13 | # If a winning rate is more than 99%, there is no possibility to get a name of 'mighty lord' 14 | if(baseWinningRate >= 99): 15 | print -1 16 | continue 17 | 18 | k = 1073741824 19 | n = N 20 | m = M 21 | # If player winning k times serially can get a name of 'mighty lord', pass. 22 | # Else, add the k. Then we can get the highest rate which can not get a name of 'mighty lord'. 23 | while(k!=0): 24 | if(100*(m+k)/(n+k) > 100*m/n): 25 | pass 26 | else: 27 | m=m+k 28 | n=n+k 29 | k = k / 2 30 | 31 | # Output 32 | print m - M + 1 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [손고리즘-시즌3] 알고리즘 문제 해결 스터디 2 | 3 | 손고리즘 시즌2 진행하면서 학습했던 알고리즘 이론을 복습하는 차원에서 다양한 문제들을 스스로 풀어보고, 코드 리뷰를 통해 풀이과정을 공유하는 시간을 갖는다. 4 | 5 | 6 | 7 | - 일정: 2015.12.08 ~ 2016.02.23 8 | - 시간: 매주 화요일 19시 30분 ~ 22시 00분 9 | - 장소: 강남역 근처 10 | - 교재: [알고리즘 문제 해결 전략](http://www.yes24.com/24/goods/8006522) (저자: 구종만) 11 | - 방식: 12 | 1. 교재의 6장부터 한주 1개의 챕터씩 2개의 문제 해결 13 | 2. 문제는 [알고스팟](https://algospot.com)을 통해 제출 및 평가 14 | 3. 알고스팟에 통과한 답안은 '**{알고스팟 ID}_{문제이름:소문자}.py**' 같은 형태의 파일로 commit & push 15 | 4. 사용하는 언어는 Python2 또는 Python3 16 | 5. 각 문제마다 담당자 1명씩 배치하여 문제 풀이(코드리뷰)를 발표 (발표는 1시간내) 17 | 6. 알고리즘 이론에 대한 발표는 없으나 하고 싶다면 말리지는 않음 18 | 19 | ## 일정 20 | #### 2015.12.08 - 오리엔테이션 21 | - 게임판 덮기(BOARDCOVER) [[link](https://algospot.com/judge/problem/read/BOARDCOVER)] 22 | - 시계 맞추기(CLOCKSYNC) [[link](https://algospot.com/judge/problem/read/CLOCKSYNC)] 23 | 24 | #### 2015.12.15 25 | - 쿼드 트리 뒤집기 (QUADTREE) [[link](https://algospot.com/judge/problem/read/QUADTREE)] 26 | - 울타리 잘라내기 (FENCE) [[link](https://algospot.com/judge/problem/read/FENCE)] 27 | 28 | #### 2015.12.22 29 | - ~~팬미팅 (FANMEETING)~~ [[link](https://algospot.com/judge/problem/read/FANMEETING)] 30 | - 와일드카드 (WILDCARD) [[link](https://algospot.com/judge/problem/read/WILDCARD)] 31 | - 합친 LIS (JLIS) [[link](https://algospot.com/judge/problem/read/JLIS)] 32 | 33 | #### 2015.12.29 34 | - 원주율 외우기 (PI) [[link](https://algospot.com/judge/problem/read/PI)] 35 | - Qantization (QUANTIZE) [[link](https://algospot.com/judge/problem/read/QUANTIZE)] 36 | 37 | #### 2016.01.05 38 | - 비대칭 타일링 (ASYMTILING) [[link](https://algospot.com/judge/problem/read/ASYMTILING)] 39 | - 폴리오미노 (POLY) [[link](https://algospot.com/judge/problem/read/POLY)] 40 | 41 | #### 2016.01.12 42 | - 두니발 박사의 탈옥 (NUMB3RS) [[link](https://algospot.com/judge/problem/read/NUMB3RS)] 43 | - 여행 짐 싸기 (PACKING) [[link](https://algospot.com/judge/problem/read/PACKING)] 44 | 45 | #### 2016.01.19 46 | - 드래곤 커브 (DRAGON) [[link](https://algospot.com/judge/problem/read/DRAGON)] 47 | - 실험 데이터 복구하기 (RESTORE) [[link](https://algospot.com/judge/problem/read/RESTORE)] 48 | 49 | #### 2016.02.02 50 | - 숫자 게임 (NUMBERGAME) [[link](https://algospot.com/judge/problem/read/NUMBERGAME)] 51 | - 블록 게임 (BLOCKG) [[link](https://algospot.com/judge/problem/read/BLOCKG)] 52 | 53 | #### 2016.02.16 54 | - 회전초밥 (SUSHI) [[link](https://algospot.com/judge/problem/read/SUSHI)] 55 | - 지니어스 (GENIUS) [[link](https://algospot.com/judge/problem/read/GENIUS)] 56 | 57 | #### 2016.02.23 58 | - 도시락데우기(LUNCHBOX) [[link](https://algospot.com/judge/problem/read/LUNCHBOX)] 59 | - 문자열합치기(STRJOI) [[link](https://algospot.com/judge/problem/read/STRJOI)] 60 | 61 | #### 2016.03.08 62 | - 게임판덮기2(BOARDCOVER2) [[link](https://algospot.com/judge/problem/read/BOARDCOVER2)] 63 | - 알러지가심한친구들(ALLERGY) [[link](https://algospot.com/judge/problem/read/ALLERGY)] 64 | 65 | #### 2016.03.15 66 | - 남극기지(ARCTIC) [[link](https://algospot.com/judge/problem/read/ARCTIC)] 67 | - 캐나다 여행(CANADATRIP) [[link](https://algospot.com/judge/problem/read/CANADATRIP)] 68 | 69 | #### 2016.03.22 70 | - 승률 올리기 (RATIO) [[link](https://algospot.com/judge/problem/read/RATIO)] 71 | - 마법의약(POTION) [[link](https://algospot.com/judge/problem/read/POTION)] 72 | 73 | #### 2016.03.29 74 | - 핀볼 시뮬레이션(PINBALL) [[link](https://algospot.com/judge/problem/read/PINBALL)] : 정민철 75 | - 보물섬(TREASURE) [[link](https://algospot.com/judge/problem/read/TREASURE)] : 장재형 76 | 77 | #### 2016.04.05 78 | - 비트마스트(GRADURATION) [[link](https://algospot.com/judge/problem/read/GRADURATION)] : 김재경 79 | - 크리스마스 인형(CHRISTMAS) [[link](https://algospot.com/judge/problem/read/CHRISTMAS)] : 배성호 80 | 81 | #### 2016.04.12 82 | - 조세푸스(JOSHEPUS) [[link](https://algospot.com/judge/problem/read/JOSHEPUS)] 83 | - 짝이 맞지 않는 괄호(BRACKETS2) [[link](https://algospot.com/judge/problem/read/BRACKETS2)] 84 | 85 | #### 2016.04.19 86 | - 외계신호분석(ITES) [[link](https://algospot.com/judge/problem/read/ITES)] 87 | - 재하의 금고(JAEHASAFE) [[link](https://algospot.com/judge/problem/read/JAEHASAFE)] 88 | 89 | #### 2016.04.26 90 | - 말버릇(HABIT) [[link](https://algospot.com/judge/problem/read/HABIT)] 91 | - 트리순회순서변경(TRAVERSAL) [[link](https://algospot.com/judge/problem/read/TRAVERSAL)] 92 | 93 | #### 2016.05.10 94 | - 요새(FORTRESS) [[link](https://algospot.com/judge/problem/read/FORTRESS)] : 이동환 95 | - 너드인가, 너드가 아닌가?2 (NERD2) [[link](https://algospot.com/judge/problem/read/NERD2)] : 김재경 96 | 97 | ~~#### 2016.05.17~~ 98 | #### 2016.05.24 99 | - 변화하는 중간 값 (RUNNINGMEDIAN) [[link](https://algospot.com/judge/problem/read/RUNNINGMEDIAN)] : 이동환 100 | - 등산로 (MORDOR) [[link](https://algospot.com/judge/problem/read/MORDOR)] : 장재형 101 | 102 | #### 2016.05.31 103 | - 삽입 정렬 시간 재기 (MEASURETIME) [[link](https://algospot.com/judge/problem/read/MEASURETIME)] : 이동환 104 | - 에디터 전쟁 (EDITORWARS) [[link](https://algospot.com/judge/problem/read/EDITORWARS)] : 임성광 105 | 106 | #### 2016.06.07 107 | - 안녕히, 그리고 물고기는 고마웠어요 (SOLONG) [[link](https://algospot.com/judge/problem/read/SOLONG)] : 임성광 108 | - 단어제한 끝말잇기 (WORDCHAIN) [[link](https://algospot.com/judge/problem/read/WORDCHAIN)] : 이동환 109 | 110 | #### 2016.06.14 111 | - 감시카메라 설치(GALLERY) [[link](https://algospot.com/judge/problem/read/GALLERY)] : 김재경 112 | - 소팅게임(SORTGAME) [[link](https://algospot.com/judge/problem/read/SORTGAME)] : 조은우 113 | 114 | #### 2016.06.28 115 | - 어린이날(CHILDRENDAY) [[link](https://algospot.com/judge/problem/read/CHILDRENDAY)] : 조은우 116 | - 하노이의 탑(HANOI4) [[link](https://algospot.com/judge/problem/read/HANOI4)] : 임성광 117 | 118 | #### 2016.07.05 119 | - 신호 라우팅(ROUTING) [[link](https://algospot.com/judge/problem/read/ROUTING)] : 장정훈 120 | - 소방차(FIRETRUCKS) [[link](https://algospot.com/judge/problem/read/FIRETRUCKS)] : 이동환 121 | 122 | #### 2016.07.12 123 | - 시간여행(TIMETRIP) [[link](https://algospot.com/judge/problem/read/TIMETRIP)] : 임성광 124 | - 음주 단속(DRUCKEN) [[link](https://algospot.com/judge/problem/read/DRUNKEN)] : 김재경 125 | 126 | #### 2016.07.19 127 | - 선거 공약(PROMISES, 난이도: 중) [[link](https://algospot.com/judge/problem/read/PROMISES)] : 장정훈 128 | - 근거리 네트워크(LAN, 난이도: 하) [[link](https://algospot.com/judge/problem/read/LAN)] : 이동환 129 | 130 | #### 2016.07.26 131 | - 여행 경로 정하기(TPATH, 난이도: 상) [[link](https://algospot.com/judge/problem/read/TPATH)] : 장정훈 132 | - ~~승부조작(MATCHFIX, 난이도: 중) [[link](https://algospot.com/judge/problem/read/MATCHFIX)] : 임성광~~ 133 | 134 | #### 2016.08.02 135 | - ~~국채 사업(PROJECTS, 난이도: 상) [[link](https://algospot.com/judge/problem/read/PROJECTS)] : 000~~ 136 | - 비숍(BISHOPS, 난이도: 중) [[link](https://algospot.com/judge/problem/read/BISHOPS)] : 이동환 137 | - 승부조작(MATCHFIX, 난이도: 중) [[link](https://algospot.com/judge/problem/read/MATCHFIX)] : 임성광 138 | 139 | #### 2016.08.09 140 | - 함정 설치(TRAPCARD, 난이도: 상) [[link](https://algospot.com/judge/problem/read/TRAPCARD)] : 장재형 141 | -------------------------------------------------------------------------------- /ROUTING/free-lunch_ROUTING.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from heapq import * 3 | import gc 4 | 5 | rl = lambda: sys.stdin.readline() 6 | 7 | for i in xrange(int(rl())): 8 | n, m = map(int, rl().split()) 9 | gc.collect() 10 | e = [[] for _ in xrange(n)] 11 | for k in xrange(m): 12 | input = rl().split() 13 | v1, v2, value = int(input[0]), int(input[1]), float(input[2]) 14 | e[v1].append((v2,value)) 15 | e[v2].append((v1,value)) 16 | 17 | start = 0 18 | end = n - 1 19 | 20 | visited = [False] * n 21 | dist = [1e200] * n 22 | q = [] 23 | heappush(q, (1.0,start)) 24 | 25 | while q: 26 | cost, v1 = heappop(q) 27 | if v1 == end: 28 | break 29 | 30 | visited[v1] = True 31 | 32 | for v2,c in e[v1]: 33 | dist[v2] = min(cost * c, dist[v2]) 34 | if not visited[v2]: 35 | heappush(q,(dist[v2],v2)) 36 | 37 | 38 | print "{:.10f}".format(dist[end]) 39 | -------------------------------------------------------------------------------- /RUNNINGMEDIAN/rlakim5521_runningmedian.py: -------------------------------------------------------------------------------- 1 | # RUNNINGMEDIAN 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | from heapq import * 5 | 6 | class minHeap(): 7 | def __init__(self): 8 | self.heap = [] 9 | self.size = 0 10 | 11 | def push(self, item): 12 | self.size = self.size + 1 13 | heappush(self.heap, item) 14 | 15 | def pop(self): 16 | self.size = self.size - 1 17 | return heappop(self.heap) 18 | 19 | def top(self): 20 | return self.heap[0] 21 | 22 | class maxHeap(): 23 | def __init__(self): 24 | self.heap = [] 25 | self.size = 0 26 | 27 | def push(self, item): 28 | self.size = self.size + 1 29 | heappush(self.heap, -1 * item) 30 | 31 | def pop(self): 32 | self.size = self.size - 1 33 | return -1 * heappop(self.heap) 34 | 35 | def top(self): 36 | return -1 * self.heap[0] 37 | 38 | class medianHeap(): 39 | def __init__(self): 40 | self.bigger = minHeap() 41 | self.smaller = maxHeap() 42 | self.size = 0 43 | 44 | def push(self, item): 45 | self.size = self.size + 1 46 | 47 | if self.bigger.size == self.smaller.size: 48 | self.smaller.push(item) 49 | else: 50 | self.bigger.push(item) 51 | 52 | if self.bigger.size > 0 and self.bigger.top() < self.smaller.top(): 53 | self.bigger.push(self.smaller.pop()) 54 | self.smaller.push(self.bigger.pop()) 55 | 56 | def getMedian(self): 57 | return self.smaller.top() 58 | 59 | 60 | # Main function 61 | if __name__ == "__main__": 62 | for _ in range(int(raw_input())): 63 | # Input 64 | N, a, b = map(int, raw_input().split()) 65 | A = [ 0 for _ in xrange(N) ] 66 | A[0] = 1983 67 | for _ in xrange(1, N): 68 | A[_] = (A[_-1] * a + b) % 20090711 69 | 70 | # Solve 71 | ret = 0 72 | mHeap = medianHeap() 73 | for _ in xrange(N): 74 | mHeap.push(A[_]) 75 | ret = ret + mHeap.getMedian() 76 | 77 | # Output 78 | print ret % 20090711 79 | -------------------------------------------------------------------------------- /SORTGAME/free-lunch_SORTGAME.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import collections 3 | 4 | 5 | def reverse_sublist(s,start,end): 6 | ret = str(s) 7 | ret = ret[:start]+ret[start:end+1][::-1]+ret[end+1:] 8 | return ret 9 | 10 | distance = dict() 11 | def preCalc(n): 12 | global distance 13 | perm = '01234567'[:n] 14 | 15 | q = collections.deque() 16 | q.append(perm) 17 | distance[perm] = 0 18 | 19 | while(len(q)): 20 | here = q.popleft() 21 | cost = distance[here] 22 | for i in xrange(n): 23 | for j in xrange(i+1, n): 24 | rvs_list = reverse_sublist(here, i, j) 25 | if not rvs_list in distance: 26 | distance[rvs_list] = cost+1 27 | q.append(rvs_list) 28 | #Finish 29 | 30 | def covert_list(lst): 31 | sorted_list = list(lst) 32 | ret = [] 33 | sorted_list.sort() 34 | 35 | for i in lst: 36 | ret.append(sorted_list.index(i)) 37 | return ''.join(map(str,ret)) 38 | 39 | def solve(input): 40 | preCalc(len(input)) 41 | return distance[covert_list(input)] 42 | 43 | if __name__ == "__main__": 44 | 45 | rl = lambda: sys.stdin.readline() 46 | inputList = [] 47 | 48 | for _ in xrange(int(rl())): 49 | rl() 50 | input = map(int, rl().split(' ')) 51 | inputList.append(covert_list(input)) 52 | 53 | counter = collections.Counter() 54 | for input in inputList: 55 | counter[len(input)] = len(input) 56 | 57 | 58 | for i in counter: 59 | preCalc(i) 60 | 61 | for input in inputList: 62 | print(distance[input]) 63 | -------------------------------------------------------------------------------- /SORTGAME/free-lunch_SORTGAME_Unittest.py: -------------------------------------------------------------------------------- 1 | test = __import__('free-lunch_SORTGAME') 2 | import unittest 3 | 4 | class Test_SORTGAME(unittest.TestCase): 5 | def test_exam1(self): 6 | input = [1, 2, 3, 4, 8, 7, 6, 5] 7 | self.assertEqual(test.solve(input), 1 ) 8 | 9 | 10 | def test_exam2(self): 11 | input = [3, 4, 1, 2] 12 | self.assertEqual(test.solve(input), 2 ) 13 | 14 | def test_exam3(self): 15 | input = [1, 2, 3] 16 | self.assertEqual(test.solve(input), 0 ) 17 | 18 | 19 | if __name__ == "__main__": 20 | unittest.main() 21 | -------------------------------------------------------------------------------- /STRJOIN/j2h_StrJoin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class StrJoin(): 4 | def calCostWithSortMethod(self, sortedList, sortMethod): # For Test 5 | totalCost = 0 6 | sortedList.sort() 7 | while len(sortedList) >= 2: 8 | sortedList = sortMethod(sortedList) # Custom 9 | firstMin = sortedList[0] 10 | secondMin = sortedList[1] 11 | cost = firstMin + secondMin 12 | totalCost = totalCost + cost 13 | sortedList = sortedList[2:] 14 | sortedList.append(cost) 15 | return totalCost 16 | 17 | def calCost(self, sortedList): 18 | totalCost = 0 19 | while len(sortedList) >= 2: 20 | sortedList.sort() # Default 21 | firstMin = sortedList[0] 22 | secondMin = sortedList[1] 23 | cost = firstMin + secondMin 24 | totalCost = totalCost + cost 25 | sortedList = sortedList[2:] 26 | sortedList.append(cost) 27 | return totalCost 28 | 29 | if __name__ == '__main__': 30 | caseNum = int(input()) 31 | answer = [] 32 | for i in xrange(caseNum): 33 | n = int(input()) 34 | inputList = map(int, raw_input().split()) 35 | answer.append(StrJoin().calCost(inputList)) 36 | 37 | while answer: 38 | print(answer.pop(0)) 39 | -------------------------------------------------------------------------------- /STRJOIN/j2h_StrJoinTest.py: -------------------------------------------------------------------------------- 1 | import time 2 | import unittest 3 | from j2h_StrJoin import StrJoin 4 | 5 | class StrJoinTest(unittest.TestCase): 6 | def defaultSort(self, l): 7 | l.sort() 8 | return l 9 | 10 | def mySort(self, l): 11 | newValue = l.pop() 12 | for idx in xrange(len(l)): 13 | if l[idx] > newValue: 14 | l.insert(idx, newValue) 15 | return l 16 | l.append(newValue) 17 | return l 18 | 19 | def myImproveSort(self, l): 20 | newValue = l.pop() 21 | start = 0 22 | end = len(l) - 1 23 | 24 | while True: 25 | if start == end: 26 | if l[start] > newValue: 27 | l.insert(start, newValue) 28 | break 29 | else: 30 | l.insert(start+1, newValue) 31 | break 32 | if start > end: 33 | l.insert(start, newValue) 34 | 35 | mid = (start+end)/2 36 | if l[mid] < newValue: 37 | start = mid + 1 38 | elif l[mid] > newValue: 39 | end = mid + 1 40 | else: 41 | l.insert(mid, newValue) 42 | break 43 | 44 | return l 45 | 46 | def setUp(self): 47 | self.startTime = time.time() 48 | print 49 | 50 | def tearDown(self): 51 | print("{0}: {1}".format(self.id(), 52 | (time.time() - self.startTime)*10000)) # * 10000 53 | 54 | def testSolve(self): 55 | self.assertEquals(12, StrJoin().calCost([2,4,2])) 56 | 57 | def testSolve2(self): 58 | self.assertEquals(12, StrJoin().calCostWithSortMethod([2,4,2], sorted)) 59 | 60 | def testSolve3(self): 61 | self.assertEquals(12, StrJoin().calCostWithSortMethod([2,4,2], self.mySort)) 62 | 63 | def testSolve4(self): 64 | self.assertEquals(26, StrJoin().calCostWithSortMethod([3,1,3,4,1], self.mySort)) 65 | 66 | def testSolve5(self): 67 | self.assertEquals(27, StrJoin().calCostWithSortMethod([1,1,1,1,1,1,1,2], self.mySort)) 68 | 69 | def testSolve6(self): 70 | self.assertEquals(27, StrJoin().calCost([1,1,1,1,1,1,1,2])) 71 | 72 | def testSolveWithCustomMethod(self): 73 | self.assertEquals(3222, StrJoin().calCostWithSortMethod( 74 | [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 75 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 76 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 77 | 1,1,1,1,1,1,1,1,2], self.mySort)) 78 | 79 | def testSolveWithCustomImproveMethod(self): 80 | self.assertEquals(3222, StrJoin().calCostWithSortMethod( 81 | [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 82 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 83 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 84 | 1,1,1,1,1,1,1,1,2], self.myImproveSort)) 85 | 86 | 87 | def testSolveWithCustomDefaultMethod(self): 88 | self.assertEquals(3222, StrJoin().calCostWithSortMethod( 89 | [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 90 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 91 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 92 | 1,1,1,1,1,1,1,1,2], self.defaultSort)) 93 | 94 | def testSolveWithDefaultSort(self): 95 | self.assertEquals(3222, StrJoin().calCost( 96 | [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 97 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 98 | 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8, 99 | 1,1,1,1,1,1,1,1,2])) 100 | 101 | 102 | if __name__ == '__main__': 103 | # suite = unittest.TestLoader().loadTestsFromTestCase(StrJoinTest) 104 | suite = unittest.TestSuite() 105 | # suite.addTest(StrJoinTest('testSolve3')) 106 | suite.addTest(StrJoinTest('testSolveWithCustomMethod')) 107 | suite.addTest(StrJoinTest('testSolveWithCustomImproveMethod')) 108 | suite.addTest(StrJoinTest('testSolveWithCustomDefaultMethod')) 109 | suite.addTest(StrJoinTest('testSolveWithDefaultSort')) 110 | unittest.TextTestRunner(verbosity=2).run(suite) 111 | -------------------------------------------------------------------------------- /STRJOIN/returns_strjoin.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def getMinCost( aLengthList ) : 4 | 5 | if len(aLengthList) == 1 : 6 | return 0 7 | 8 | aLengthList.sort(); 9 | 10 | sMinCost = aLengthList[0] + aLengthList[1] 11 | 12 | del aLengthList[1] 13 | del aLengthList[0] 14 | 15 | aLengthList.append( sMinCost ) 16 | 17 | return sMinCost + getMinCost( aLengthList ) 18 | 19 | def solve() : 20 | 21 | sTestCount = input() 22 | 23 | for _ in range( sTestCount ) : 24 | _ = input() 25 | sInput = raw_input().split() 26 | sLengthList = [ int(num) for num in sInput ] 27 | 28 | print getMinCost( sLengthList ) 29 | 30 | solve() 31 | -------------------------------------------------------------------------------- /STRJOIN/rlakim5521_strjoin.py: -------------------------------------------------------------------------------- 1 | # STRJOIN 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | # Main function 5 | if __name__ == "__main__": 6 | for _ in xrange(int(raw_input())): 7 | # Input 8 | n = int(raw_input()) 9 | length = map(int, raw_input().split()) 10 | 11 | # Solve 12 | cost = 0 13 | for _ in xrange(n-1): 14 | length.sort() 15 | cost += length[0] + length[1] 16 | length.append(length[0]+length[1]) 17 | length.remove(length[0]) 18 | length.remove(length[0]) 19 | 20 | # Output 21 | print cost 22 | -------------------------------------------------------------------------------- /SUSHI/free-lunch_SUSHI.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def solve(n,m,menu): 4 | max_value = 0 5 | if m > 400: 6 | best = menu[0] 7 | # print menu 8 | x, y = divmod(m-400,best[1]) 9 | max_value = best[2] * (x+1) 10 | m -= best[1] * (x+1) 11 | 12 | cache = [0] * 401 13 | ret = 0 14 | for budget in xrange(1,m+1): 15 | result = 0 16 | for r, c, p in menu: 17 | if budget >= c: 18 | result = max(result, cache[(budget-c)%401] + p) 19 | cache[budget%401] = result 20 | 21 | return cache[m] + max_value 22 | 23 | 24 | if __name__ == "__main__": 25 | rl = lambda : sys.stdin.readline() 26 | for _ in xrange(int(rl())): 27 | n, m = map(int, rl().split()) 28 | m = int(m/100) 29 | menu = [()]*n 30 | for i in xrange(n): 31 | c, p = map(int, rl().split()) 32 | c = int(c/100) 33 | r = 1.0*c/p 34 | menu[i] = r,c,p 35 | menu = sorted(menu) 36 | print solve(n,m,menu) 37 | -------------------------------------------------------------------------------- /TIMETRIP/free-lunch_TIMETRIP.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import gc 3 | import collections 4 | """ 5 | v : number of galaxy 6 | w : number of wormhole 7 | e : wormhole graph 8 | """ 9 | def solve(v, w, e, reachable): 10 | gc.collect() 11 | dist = [sys.maxint] * v 12 | 13 | dist[0] = 0 14 | for k in xrange(v-1): 15 | for here in xrange(v): 16 | for there, cost in e[here]: 17 | if dist[there] > dist[here] + cost: 18 | dist[there] = dist[here] + cost 19 | 20 | for here in xrange(v): 21 | for there, cost in e[here]: 22 | if dist[there] > dist[here] + cost: 23 | if reachable[0][here] and reachable[here][1]: 24 | return sys.maxint 25 | 26 | return dist[1] 27 | 28 | 29 | if __name__ == "__main__": 30 | rl = lambda: sys.stdin.readline() 31 | 32 | for i in xrange(int(rl())): 33 | v, w = map(int, rl().split()) 34 | e = [[] for _ in xrange(v)] 35 | e_neg = [[] for _ in xrange(v)] 36 | reachable = [[False] * v for _ in xrange(v)] 37 | for i in xrange(v): 38 | reachable[i][i] = True 39 | 40 | for _ in xrange(w): 41 | i, j, value = map(int, rl().split()) 42 | e[i].append((j,value)) 43 | e_neg[i].append((j,-value)) 44 | reachable[i][j] = True 45 | 46 | for k in xrange(v): 47 | for i in xrange(v): 48 | for j in xrange(v): 49 | reachable[i][j] = reachable[i][j] or (reachable[i][k] and reachable[k][j]) 50 | 51 | if not reachable[0][1] : 52 | print 'UNREACHABLE' 53 | continue 54 | 55 | 56 | ret1 = solve(v,w,e,reachable) 57 | ret2 = -solve(v,w,e_neg,reachable) 58 | max_value = 10**10 59 | if ret1 > max_value: 60 | ret1 = 'INFINITY' 61 | if abs(ret2) > max_value: 62 | ret2 = 'INFINITY' 63 | 64 | print ret1, ret2 65 | -------------------------------------------------------------------------------- /TPATH/free-lunch_TPATH.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | #define MAX 987654321 11 | int V, E; 12 | 13 | 14 | bool dfs(int start, vector > > adj, \ 15 | int lo, int hi, vector visited){ 16 | 17 | if(start == V-1) 18 | return true; 19 | 20 | visited[start] = true; 21 | for(int i = 0; i < adj[start].size(); i++){ 22 | int v2 = adj[start][i].first; 23 | int cost = adj[start][i].second; 24 | if(!visited[v2] && lo <= cost && cost <= hi){ 25 | if(dfs(v2, adj, lo, hi, visited)) { 26 | return true; 27 | } 28 | } 29 | } 30 | return false; 31 | } 32 | 33 | int solve(vector > >adj, vector order){ 34 | int lo = 0; 35 | int hi = 0; 36 | int ret = MAX; 37 | 38 | while(true){ 39 | vector visited(V, false); 40 | if(dfs(0, adj, order[lo], order[hi], visited)){ 41 | ret = min(ret, order[hi]-order[lo]); 42 | lo++; 43 | } 44 | else{ 45 | if(hi == order.size()-1){ 46 | break; 47 | } 48 | hi++; 49 | } 50 | } 51 | return ret; 52 | } 53 | 54 | // Kruskal 55 | struct DisjointSet { 56 | vector parent, rank; 57 | 58 | DisjointSet(int n) : parent(n), rank(n, 1) { 59 | for(int i = 0; i < n; i++) 60 | parent[i] = i; 61 | } 62 | 63 | int find(int u) { 64 | if(u == parent[u]) 65 | return u; 66 | return parent[u] = find(parent[u]); 67 | } 68 | 69 | void merge(int u, int v) { 70 | u = find(u); v = find(v); 71 | if(u == v) 72 | return; 73 | 74 | if(rank[u] > rank[v]) 75 | swap(u, v); 76 | 77 | if(rank[u] == rank[v]) 78 | rank[v]++; 79 | 80 | parent[u] = v; 81 | } 82 | }; 83 | 84 | 85 | vector > > order; 86 | 87 | int minUpperBound(int lo){ 88 | DisjointSet sets(V); 89 | for(int i = 0; i < E; i++) { 90 | if(order[i].first < lo) 91 | continue; 92 | 93 | sets.merge(order[i].second.first, order[i].second.second); 94 | if(sets.find(0) == sets.find(V-1)) 95 | return order[i].first; 96 | } 97 | 98 | return MAX; 99 | } 100 | 101 | int solve2(vector > >adj) { 102 | int ret = MAX; 103 | for(int i = 0; i < E; i++){ 104 | ret = min(ret, minUpperBound(order[i].first)-order[i].first); 105 | } 106 | return ret; 107 | } 108 | 109 | int main(){ 110 | cin.sync_with_stdio(false); 111 | 112 | int T = 0; 113 | cin >> T; 114 | 115 | while(T--){ 116 | cin >> V >> E; 117 | int v1,v2,cost; 118 | vector > > adj(V); 119 | order.resize(E); 120 | for(int i= 0; i < E; i++){ 121 | cin >> v1 >> v2 >> cost; 122 | adj[v1].push_back(make_pair(v2, cost)); 123 | adj[v2].push_back(make_pair(v1, cost)); 124 | // order.push_back(cost); 125 | order[i] = make_pair(cost, make_pair(v1, v2)); 126 | } 127 | // order.erase( unique(order.begin(), order.end()), order.end() ); 128 | sort(order.begin(), order.end()); 129 | 130 | cout << solve2(adj) <= 0: 19 | if min_v == -1: 20 | dfs1(n, i, graph[start][i], graph[start][i]) 21 | else: 22 | dfs1(n,i,min(min_v,graph[start][i]), max(max_v,graph[start][i])) 23 | 24 | graph[start][start] = -1 25 | 26 | def solve1(n, m): 27 | dfs(n, 0, -1, -1) 28 | return graph[n-1][n-1] 29 | 30 | def dfs2(n, start, min_v, max_v): 31 | if start == n-1: 32 | return True 33 | 34 | # Check visited 35 | graph[start][start] = 1 36 | for i in xrange(n): 37 | # Visit not visted adjacent node 38 | if graph[i][i] == -1 and min_v <= graph[start][i] <= max_v: 39 | if dfs2(n, i, min_v, max_v): 40 | graph[start][start] = -1 41 | return True 42 | graph[start][start] = -1 43 | return False 44 | 45 | def solve2(n, m, orders): 46 | lo, hi, ret = 0, 0, sys.maxint 47 | while True: 48 | if dfs2(n, 0, orders[lo], orders[hi]): 49 | ret = min(ret, orders[hi]-orders[lo]) 50 | lo += 1 51 | else: 52 | if hi == len(orders)-1: 53 | break 54 | hi += 1 55 | return ret 56 | 57 | if __name__ == "__main__": 58 | rl = lambda : sys.stdin.readline().rstrip(' \t\r\n\0') 59 | for _ in xrange(int(rl())): 60 | n, m = map(int, rl().split()) 61 | if m == 1: 62 | rl() 63 | print(0) 64 | continue 65 | 66 | for i in xrange(n): 67 | for j in xrange(n): 68 | graph[i][j] = -1 69 | 70 | orders = set() 71 | for i in xrange(m): 72 | v1, v2, cost = map(int, rl().split()) 73 | graph[v1][v2] = cost 74 | graph[v2][v1] = cost 75 | orders.add(cost) 76 | 77 | print(solve2(n, m, sorted(list(orders)))) 78 | -------------------------------------------------------------------------------- /TRAVERSAL/rlakim5521_traversal.py: -------------------------------------------------------------------------------- 1 | # TRAVERSAL 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | class Node: 5 | def __init__(self, key): 6 | self.key = key; 7 | self.left = None 8 | self.right = None 9 | 10 | def makeTree(preorders, inorders): 11 | if(len(preorders) == 0): 12 | return None 13 | node = Node(preorders[0]) 14 | slicePosition = inorders.index(preorders[0]) 15 | node.left = makeTree(preorders[1:slicePosition+1], inorders[0:slicePosition]) 16 | node.right = makeTree(preorders[slicePosition+1:], inorders[slicePosition+1:]) 17 | return node 18 | 19 | def postorderTraversal(node): 20 | if(node == None): 21 | return 22 | postorderTraversal(node.left) 23 | postorderTraversal(node.right) 24 | print node.key, 25 | 26 | # Main function 27 | if __name__ == "__main__": 28 | for _ in range(int(raw_input())): 29 | # Input 30 | # Number of node 31 | N = int(raw_input()) 32 | # Preorder traversal case 33 | preorders = map(int, raw_input().split()) 34 | # Inorder traversal case 35 | inorders = map(int, raw_input().split()) 36 | 37 | # Solve 38 | root = makeTree(preorders, inorders) 39 | 40 | # Output 41 | postorderTraversal(root) 42 | print 43 | -------------------------------------------------------------------------------- /TREASURE/rlakim5521_treasure.py: -------------------------------------------------------------------------------- 1 | # TREASURE 2 | # Jaekyoung Kim (rlakim5521@naver.com) 3 | 4 | import math 5 | from PIL.GimpGradientFile import EPSILON 6 | 7 | PI = 2.0 * math.acos(0.0) 8 | 9 | class vector: 10 | def __init__(self, x, y): 11 | self.x = x 12 | self.y = y 13 | 14 | def __str__(self): 15 | return str(self.x) + " " + str(self.y) 16 | 17 | def __eq__(self, rhs): 18 | return self.x == rhs.x and self.y == rhs.y 19 | 20 | def __lt__(self, rhs): 21 | if self.x != rhs.x: 22 | return self.x < rhs.x 23 | else: 24 | return self.y < rhs.y 25 | 26 | def __add__(self, rhs): 27 | return vector(self.x + rhs.x, self.y + rhs.y) 28 | 29 | def __sub__(self, rhs): 30 | return vector(self.x - rhs.x, self.y - rhs.y) 31 | 32 | def __mul__(self, rhs): 33 | return vector(self.x * rhs, self.y * rhs) 34 | 35 | # Returns a length of vector. 36 | def norm(self): 37 | return math.hypot(self.x, self.y) 38 | 39 | # Returns an unit vector which has a same direction. 40 | def normalize(self): 41 | return vector(self.x / self.norm(), self.y / self.norm()) 42 | 43 | def polar(self): 44 | return math.fmod(math.atan2(self.y, self.x) + 2 * PI, 2 * PI) 45 | 46 | # Inner product 47 | def dot(self, rhs): 48 | return self.x * rhs.x + self.y * rhs.y 49 | 50 | # Cross product 51 | def cross(self, rhs): 52 | return self.x * rhs.y - rhs.x * self.y 53 | 54 | # what??? 55 | def project(self, rhs): 56 | r = rhs.normalize() 57 | return r * r.dot(self) 58 | 59 | # Returns a result of cross product of vector a and vector b. 60 | # If vector b is laid on a counterclockwise direction of vector a from the starting point, 61 | # returns a positive number. 62 | # If vector b is laid on a clockwise direction of vector a from the starting point, 63 | # returns a negative number. 64 | # If vector a and vector b are parallel, returns 0. 65 | def ccw2(a, b): 66 | return a.cross(b) 67 | 68 | # Returns a result of cross product of vector a and vector b. 69 | # If vector b is laid on a counterclockwise direction of vector a from vector p, 70 | # returns a positive number. 71 | # If vector b is laid on a clockwise direction of vector a from vector p, 72 | # returns a negative number. 73 | # If vector a and vector b are parallel, returns 0. 74 | def ccw3(p, a, b): 75 | return ccw2(a-p, b-p) 76 | 77 | # Returns an intersection point of two lines which a line including vector a and vector b 78 | # and a line including vector c and vector d. 79 | # If two lines are parallel, returns an vector of (-1,-1). 80 | def lineIntersection(a, b, c, d): 81 | det = (b - a).cross(d - c) 82 | if(math.fabs(det) < EPSILON): return vector(-1,-1) 83 | return a + (b - a) * ((c - a).cross(d - c) / det) 84 | 85 | # Returns an area of an simple polygon. 86 | def area(vectors): 87 | ret = 0.0 88 | length = len(vectors) 89 | for i in xrange(length): 90 | j = (i+1) % length 91 | ret += vectors[i].x * vectors[j].y - vectors[j].x * vectors[i].y 92 | return math.fabs(ret) / 2.0 93 | 94 | # If point is inside of islands, returns true. 95 | # Else, returns false. 96 | def isInside(point, islands): 97 | crosses = 0 98 | length = len(islands) 99 | for i in xrange(length): 100 | j = (i+1) % length 101 | if((islands[i].y > point.y) != (islands[j].y > point.y)): 102 | atX = (islands[j].x - islands[i].x) * (point.y - islands[i].y) / (islands[j].y - islands[i].y) + islands[i].x 103 | if(point.x < atX): 104 | crosses += 1 105 | return crosses % 2 > 0 106 | 107 | # After cutting a polygon by a line including vector a and vector b, 108 | # returns the left parts of the line. 109 | def cutPoly(p, a, b): 110 | n = len(p) 111 | inside = [] 112 | for i in xrange(n): 113 | inside.append(ccw3(a, b, p[i]) >= 0) 114 | ret = [] 115 | for i in xrange(n): 116 | j = (i+1) % n 117 | if(inside[i]): ret.append(p[i]) 118 | if(inside[i] != inside[j]): 119 | cross = lineIntersection(p[i], p[j], a, b) 120 | ret.append(cross) 121 | return ret 122 | 123 | # An polygon clipping using an Sutherland-Hodgman algorithm. 124 | def intersection(p, x1, y1, x2, y2): 125 | a = vector(x1, y1) 126 | b = vector(x2, y1) 127 | c = vector(x2, y2) 128 | d = vector(x1, y2) 129 | ret = cutPoly(p, a, b) 130 | ret = cutPoly(ret, b, c) 131 | ret = cutPoly(ret, c, d) 132 | ret = cutPoly(ret, d, a) 133 | return ret 134 | 135 | # Main function 136 | if __name__ == "__main__": 137 | for _ in xrange(input()): 138 | # Input 139 | x1, y1, x2, y2, N = map(float, raw_input().split()) 140 | islands = [] 141 | for _ in xrange(int(N)): 142 | xi, yi = map(float, raw_input().split()) 143 | islands.append(vector(xi,yi)) 144 | 145 | # Solve 146 | rectangles = [vector(x1,y2),vector(x1,y1),vector(x2,y1),vector(x2,y2)] 147 | investgateds = intersection(islands, x1, y1, x2, y2) 148 | 149 | # Output 150 | print area(investgateds) 151 | -------------------------------------------------------------------------------- /WILDCARD/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/songorithm/algorithm-problem-solving/0d9d1338ca2b2d8fcb555e4d46a6ada9c9e3587a/WILDCARD/.gitkeep --------------------------------------------------------------------------------