diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..dbd9e23 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Current File", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..c6733b6 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "C:\\anaconda3\\python.exe" +} \ No newline at end of file diff --git a/0827_check_bit.py b/0827_check_bit.py deleted file mode 100644 index 5d37473..0000000 --- a/0827_check_bit.py +++ /dev/null @@ -1,39 +0,0 @@ - -def check(nums:list) -> int: - sum_minus = 0 - check_zero = {i:0 for i in range(16)} - for num in nums: - for i in range(16): - if num & (1< 1: - if s[0]=='b' and s[-1]=='b': - delete_cnt = 0 - while len(s) > 1 and s[0]=='b' and s[-1]=='b': - s = s[1:-1] - a_cnt += 1 - if delete_cnt % a_cnt: - return False - - elif s[0]=='a' or s[-1]=='a': - if s[0]=='a': - s = s[1:] - a_cnt -= 1 - else: - s = s[:-1] - a_cnt -= 1 - else: - if s=='a': - return True - else: - return False - - -def solution(a): - answer = [] - for string in a: - answer.append(check(string)) - return answer - - - -print(solution(["bbbbabbbb","abab","abbbbbbbabababbbabbbb","bbaa","bababa","bbbabababbbaa"])) \ No newline at end of file diff --git a/0827_make_dice_1.py b/0827_make_dice_1.py deleted file mode 100644 index f874e59..0000000 --- a/0827_make_dice_1.py +++ /dev/null @@ -1,26 +0,0 @@ -def dfs(depth,target,nums,n,check,dice): - if depth == target: - answers.append(int(nums)) - return - for dice_number in range(n): - if not check[dice_number]: - for number in dice[dice_number]: - if not depth and not number: - continue - check[dice_number] = True - dfs(depth+1,target,nums+str(number),n,check,dice) - check[dice_number] = False - - -def solution(dice): - global answers - dice_n = len(dice) - dice_check = [False for _ in range(dice_n)] - answers = [] - for i in range(1,dice_n+1): - dfs(0,i,'',dice_n,dice_check,dice) - for i in range(1,10**dice_n): - if i not in answers: - return i - -print(solution([[1, 6, 2, 5, 3, 4], [9, 9, 1, 0, 7, 8]])) \ No newline at end of file diff --git a/0827_make_predix_sum.py b/0827_make_predix_sum.py deleted file mode 100644 index db69d87..0000000 --- a/0827_make_predix_sum.py +++ /dev/null @@ -1,52 +0,0 @@ - -from collections import deque - -def check(x,y): - if sum(x) != sum(y): - return False - queue = deque() - l_y = len(y) - l_x = len(x) - for i in range(l_x): - for j in range(l_y): - if x[i]==y[j]: - x[i] = 0 - y[j] = 0 - n_x = [num for num in x if num] - n_y = [num for num in y if num] - l_y = len(n_y) - l_x = len(n_x) - y_check = [False for _ in range(l_y)] - for i in range(l_x): - queue.append([1< rm: - print(2) - else: +t = int(input()) +for i in range(t): + x1, y1, r1, x2, y2, r2 = map(int, input().split()) + d = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 + rs = r1 + r2 + rm = abs(r1 - r2) + if d == 0: + if r1 == r2: + print(-1) + else: + print(0) + else: + if d == rs or d == rm: + print(1) + elif d < rs and d > rm: + print(2) + else: print(0) \ No newline at end of file diff --git "a/10026\354\240\201\353\241\235\354\203\211\354\225\275.py" "b/10026\354\240\201\353\241\235\354\203\211\354\225\275.py" deleted file mode 100644 index 6baf420..0000000 --- "a/10026\354\240\201\353\241\235\354\203\211\354\225\275.py" +++ /dev/null @@ -1,53 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(x,y,color): - visited[x][y] = True - q = deque() - q.append([x,y]) - while q: - x,y = q.popleft() - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0<=nx r: - P[i] = 0 - else: - P[i] = min(P[2*c-i],r-i) - cnt[s[i-P[i]:i+P[i]+1]] += 1 - while i-P[i]-1 > 0 and i+P[i]+1 < n and s[i+P[i]+1] == s[i-P[i]-1]: - P[i] += 1 - cnt[s[i-P[i]:i+P[i]+1]] += 1 - if r < i + P[i]: - r = i + P[i] - c = i - return cnt - -st = input().rstrip() -cnt_table = manacher('#' + '#'.join(st) + '#') -max_value = 0 -for p in cnt_table: - if p == '#': - continue - if p[0]!='#': - max_value = max(max_value,(len(p)//2+1)*cnt_table[p]) - else: - max_value = max(max_value,(len(p)//2)*cnt_table[p]) -print(max_value) \ No newline at end of file diff --git "a/1007\353\262\241\355\204\260\353\247\244\354\271\255.py" "b/1007\353\262\241\355\204\260\353\247\244\354\271\255.py" deleted file mode 100644 index ecfdf93..0000000 --- "a/1007\353\262\241\355\204\260\353\247\244\354\271\255.py" +++ /dev/null @@ -1,50 +0,0 @@ -import math - -ax = [] -ay = [] -c = [False] * 21 - -com = [2147483647.0] - -def dfs(count, index, N): - if (count == N / 2): - x = 0 - y = 0 - for i in range(0, N): - if c[i]: - x = x - ax[i] - y = y - ay[i] - else: - x = x + ax[i] - y = y + ay[i] - - com[0] = min(com[0], math.sqrt(x * x + y * y)) - return - - if (index == N): - return - - dfs(count, index + 1, N) - c[index] = True - dfs(count+1, index + 1, N) - c[index] = False - -def solution(): - ax.clear() - ay.clear() - c = [False] * 21 - com[0] = 2147483647.0 - - N = int(input()) - for i in range(N): - x, y = map(int, input().split(' ')) - ax.append(x) - ay.append(y) - dfs(0, 0, N) - - print(round(com[0], 6)) - -T = int(input()) - -for i in range(T): - solution() \ No newline at end of file diff --git a/1010.py b/1010.py index 1007025..5493057 100644 --- a/1010.py +++ b/1010.py @@ -1,14 +1,14 @@ - -T = int(input()) - -for test in range(T): - N,M = map(int,input().split()) - a,b = 1,1 - for i in range(N): - a = a*(M-i) - for i in range(1,N+1): - b = b*i - - ans = int(a/b) - + +T = int(input()) + +for test in range(T): + N,M = map(int,input().split()) + a,b = 1,1 + for i in range(N): + a = a*(M-i) + for i in range(1,N+1): + b = b*i + + ans = int(a/b) + print(ans) \ No newline at end of file diff --git "a/1012\354\234\240\352\270\260\353\206\215\353\260\260\354\266\224.py" "b/1012\354\234\240\352\270\260\353\206\215\353\260\260\354\266\224.py" deleted file mode 100644 index 4b1be90..0000000 --- "a/1012\354\234\240\352\270\260\353\206\215\353\260\260\354\266\224.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -dx=[0,1,0,-1] -dy=[1,0,-1,0] - -def BFS(x,y): - queue=deque() - queue.append([x,y]) - radish[x][y]=0 - while queue: - x,y=queue.popleft() - for i in range(4): - nx=x+dx[i] - ny=y+dy[i] - if 0<=nx= path1[i][1]: - visited[path1[i][2]] = False - # 마찬가지로 right 안쪽이면 다 삭제. - if path1[i][1] <= right: - visited[path1[i][2]] = False - # 포함 안됐으면 간선 추가시킴. - else: - right = path1[i][1] - -# 0거쳐가는애들도 오른쪽 끝이랑 0이랑 비교해서 점점 범위 늘려나감(시작점, 끝점.) -right = 0 -for i in range(len(path2)): - if path2[i][1] <= right: - visited[path2[i][2]] = False - else: - right = path2[i][1] - -for i in range(1,M+1): - if visited[i]: - print(i,end=' ') \ No newline at end of file diff --git "a/1016\354\240\234\352\263\261\343\204\264\343\204\264\354\210\230.py" "b/1016\354\240\234\352\263\261\343\204\264\343\204\264\354\210\230.py" deleted file mode 100644 index fac762f..0000000 --- "a/1016\354\240\234\352\263\261\343\204\264\343\204\264\354\210\230.py" +++ /dev/null @@ -1,17 +0,0 @@ -min, max = map(int, input().split()) - -chk = [1] * (max - min + 1) -# 2부터 max의 제곱근 수까지만 체크하면 충분. -for n in range(2, int(max ** 0.5) + 1): - square = n ** 2 - i = min // square - # 제곱수의 배수가 min보다 크도록 나눈몫+1해줌. - # 거기서부터 쭉 i증가시키며 돌고 n번째 수 다 끝나면 다음 n으로 넘어가며 check배열에 0으로 바꿔줌. - if square * i < min: - i += 1 - while square * i <= max: - chk[square * i - min] = 0 - i += 1 -print(sum(chk)) - - diff --git "a/1017 \354\206\214\354\210\230\354\214\215.py" "b/1017 \354\206\214\354\210\230\354\214\215.py" deleted file mode 100644 index 5b2c5f9..0000000 --- "a/1017 \354\206\214\354\210\230\354\214\215.py" +++ /dev/null @@ -1,50 +0,0 @@ -import sys -input = sys.stdin.readline -n = int(input()) -s = list(map(int, input().split())) -sa = [0] -sb = [0] -e = [True for i in range(2000)] -result = [] -def era(): - e[1] = False - for i in range(2, 50): - if e[i] == True: - for j in range(i * 2, 2000, i): - e[j] = False -era() -def dfs(start): - if visit[start] == 1: - return 0 - visit[start] = 1 - for i in s_[start]: - if d[i] == 0 or dfs(d[i]): - d[i] = start - return 1 - return 0 -for i in range(n): - if s[0] % 2 == s[i] % 2: - sa.append(s[i]) - else: - sb.append(s[i]) -s_ = [[] for i in range(len(sa))] -for i in range(1, len(sa)): - for j in range(1, len(sb)): - if e[sa[i] + sb[j]]: - s_[i].append(j) -for i in s_[1]: - d = [0 for _ in range(len(sb))] - d[i] = 1 - cnt = 1 - for j in range(1, len(sa)): - visit = [0 for _ in range(len(sa))] - visit[1] = 1 - cnt += dfs(j) - if cnt == n // 2: - result.append(sb[i]) -if not result: - print(-1) -else: - result.sort() - for i in result: - print(i, end=" ") \ No newline at end of file diff --git "a/1018\354\262\264\354\212\244\355\214\220 \353\213\244\354\213\234 \354\271\240\355\225\230\352\270\260.py" "b/1018\354\262\264\354\212\244\355\214\220 \353\213\244\354\213\234 \354\271\240\355\225\230\352\270\260.py" deleted file mode 100644 index 43d49a0..0000000 --- "a/1018\354\262\264\354\212\244\355\214\220 \353\213\244\354\213\234 \354\271\240\355\225\230\352\270\260.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M = map(int,input().split()) -chess = [list(input().rstrip()) for _ in range(N)] - -dp = [[0]*M for _ in range(N)] - -for i in range(N): - for j in range(M): - if i%2 == j%2: - if chess[0][0] != chess[i][j]: - dp[i][j]=1 - else: - if chess[0][0] == chess[i][j]: - dp[i][j]=1 - -min_change = float('inf') -for i in range(N-7): - for j in range(M-7): - sum_count = 0 - for k in range(i,i+8): - sum_count += sum(dp[k][j:j+8]) - if sum_count > 32: - sum_count = 64 - sum_count - if min_change > sum_count: - min_change = sum_count - -print(min_change) \ No newline at end of file diff --git "a/1019 \354\261\205 \355\216\230\354\235\264\354\247\200.py" "b/1019 \354\261\205 \355\216\230\354\235\264\354\247\200.py" deleted file mode 100644 index 92a5141..0000000 --- "a/1019 \354\261\205 \355\216\230\354\235\264\354\247\200.py" +++ /dev/null @@ -1,56 +0,0 @@ -import sys -input = sys.stdin.readline - - -# calc : a,b가 9또는 0으로 끝나지 않을 때 -# 각 자리수를 ans에 카운트 시키는 함수 -def count_page(x,point): - while x: - ans[x % 10] += point - x //= 10 - -end = int(input()) -ans = [0] * 10 -# 위 글에서 k의 역할을 하는 point -point = 1 -# 문제의 조건에 따라 1부터 시작 -start = 1 - -while start <= end: - # 끝 숫자 9 맞춰주기 - while end % 10 != 9: - count_page(end, point) - end -= 1 - - if end < start: - break - # 시작점 10의 배수 맞춰주기 - while start % 10 != 0: - count_page(start, point) - start += 1 - - start //= 10 - end //= 10 - - for i in range(10): - ans[i] += (end - start + 1) * point - point *= 10 - -print(*ans) - - -""" -1. a가 9로 끝나는가 - -1- 1. 그렇지 않다면 각 자릿수를 세준다 + a를 1씩 빼준다 - -2. b가 0으로 끝나는가 - -2- 1. 그렇지 않다면 각 자릿수를 세준다 + b를 1씩 더해준다 - -3. a,b 모두 10으로 나눠준다 - -4. 위 식을 계산한다 - -5. 다시 1로 돌아가 반복 -""" \ No newline at end of file diff --git "a/1021 \355\232\214\354\240\204\355\225\230\353\212\224 \355\201\220.py" "b/1021 \355\232\214\354\240\204\355\225\230\353\212\224 \355\201\220.py" deleted file mode 100644 index 70ba739..0000000 --- "a/1021 \355\232\214\354\240\204\355\225\230\353\212\224 \355\201\220.py" +++ /dev/null @@ -1,36 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -n, m = map(int, input().split()) -position = list(map(int, input().split())) -q = deque([i for i in range(1, n+1)]) - -move = 0 -for num in position: - if q.index(num) < len(q)/2: - while q[0] != num: - q.rotate(-1) - move += 1 - else: - while q[0] != num: - q.rotate(1) - move += 1 - if q[0] == num: - q.popleft() - continue -print(move) - - -# 다른풀이 / 안돌리고 연산후 삭제. -n, m = map(int, input().split()) -dq = [i for i in range(1, n+1)] - -ans = 0 - -for find in map(int, input().split()): - ix = dq.index(find) - ans += min(len(dq[ix:]), len(dq[:ix])) - dq = dq[ix+1:] + dq[:ix] - -print(ans) \ No newline at end of file diff --git "a/1030\355\224\204\353\240\211\355\203\210\355\217\211\353\251\264.py" "b/1030\355\224\204\353\240\211\355\203\210\355\217\211\353\251\264.py" deleted file mode 100644 index 6409f46..0000000 --- "a/1030\355\224\204\353\240\211\355\203\210\355\217\211\353\251\264.py" +++ /dev/null @@ -1,5 +0,0 @@ -import sys -input = sys.stdin.readline - - -s, N, K, R1, R2, C1, C2 = map(int, input().split()) \ No newline at end of file diff --git "a/10430\354\227\260\354\202\260.py" "b/10430\354\227\260\354\202\260.py" index d62f55a..fae95e2 100644 --- "a/10430\354\227\260\354\202\260.py" +++ "b/10430\354\227\260\354\202\260.py" @@ -1,6 +1,12 @@ -A, B, C = map(int,input().split()) - -print((A+B)%C) -print(((A%C)+(B%C))%C) -print((A*B)%C) -print(((A%C)*(B%C))%C) \ No newline at end of file +A, B= map(int,input().split()) +C, D=A,B + +while A%B != 0: + if A>B: + A = A%B + if B>A: + B = B%A + +print(A) + +print((C/A)*D) \ No newline at end of file diff --git "a/1043\352\261\260\354\247\223\353\247\220.py" "b/1043\352\261\260\354\247\223\353\247\220.py" index fa70c0e..2381faf 100644 --- "a/1043\352\261\260\354\247\223\353\247\220.py" +++ "b/1043\352\261\260\354\247\223\353\247\220.py" @@ -1,44 +1,44 @@ -# BOJ 1043 거짓말 -# 분리 집합, 그래프 이론 -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) - -# 거짓말을 하면 안 될 사람들을 담는 스택 -# 진실을 아는 사람의 수는 필요가 없어 슬라이싱 함 -know = list(map(int, input().split()))[1:] - -# 스택에 추가된 적이 있는지 확인하기 위한 리스트 -visit = [0] * N -for k in know: - visit[k-1] = 1 - -parties = [] -for _ in range(M): - guests = list(map(int, input().split()))[1:] # 파티 손님의 수는 필요가 없어 슬라이싱 함 - parties.append(guests) - -party_visit = [0] * M # 진실을 말해야 하는 파티일 경우 1이라고 표기 - -# 스택이 빌때까지 과정 반복 -while know: - known_guest = know.pop() - - candidate = set() # pop된 사람들과 같은 파티에 있는 사람들을 담는 집합 - - # pop된 사람과 같은 파티에 있는 사람들을 찾아 집합에 추가한다. - for party_idx in range(len(parties)): - party = set(parties[party_idx]) - if known_guest in party: # pop된 사람이 현재 파티에 있을 경우 - candidate = candidate.union(party) # 파티의 사람들을 집합에 추가 - party_visit[party_idx] = 1 # 현재 파티를 진실을 말해야 하는 파티라고 표기 - - # 찾은 사람들 중 스택에 추가된 적이 없는 사람들을 스택에 추가 - for guest in candidate: - if not visit[guest - 1]: - know.append(guest) - visit[guest - 1] = 1 - -# 표기되지 않은 파티의 개수를 출력 +# BOJ 1043 거짓말 +# 분리 집합, 그래프 이론 +import sys +input = sys.stdin.readline + +N, M = map(int, input().split()) + +# 거짓말을 하면 안 될 사람들을 담는 스택 +# 진실을 아는 사람의 수는 필요가 없어 슬라이싱 함 +know = list(map(int, input().split()))[1:] + +# 스택에 추가된 적이 있는지 확인하기 위한 리스트 +visit = [0] * N +for k in know: + visit[k-1] = 1 + +parties = [] +for _ in range(M): + guests = list(map(int, input().split()))[1:] # 파티 손님의 수는 필요가 없어 슬라이싱 함 + parties.append(guests) + +party_visit = [0] * M # 진실을 말해야 하는 파티일 경우 1이라고 표기 + +# 스택이 빌때까지 과정 반복 +while know: + known_guest = know.pop() + + candidate = set() # pop된 사람들과 같은 파티에 있는 사람들을 담는 집합 + + # pop된 사람과 같은 파티에 있는 사람들을 찾아 집합에 추가한다. + for party_idx in range(len(parties)): + party = set(parties[party_idx]) + if known_guest in party: # pop된 사람이 현재 파티에 있을 경우 + candidate = candidate.union(party) # 파티의 사람들을 집합에 추가 + party_visit[party_idx] = 1 # 현재 파티를 진실을 말해야 하는 파티라고 표기 + + # 찾은 사람들 중 스택에 추가된 적이 없는 사람들을 스택에 추가 + for guest in candidate: + if not visit[guest - 1]: + know.append(guest) + visit[guest - 1] = 1 + +# 표기되지 않은 파티의 개수를 출력 print(party_visit.count(0)) \ No newline at end of file diff --git "a/1052\353\254\274\353\263\221.py" "b/1052\353\254\274\353\263\221.py" deleted file mode 100644 index df7d22f..0000000 --- "a/1052\353\254\274\353\263\221.py" +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) - -answer = 0 -while bin(N).count('1') > K: - plus = 2 ** (N&~N) - answer += plus - N += plus -print(answer) \ No newline at end of file diff --git "a/10546\353\260\260\353\266\200\353\245\270\353\247\210\353\235\274\355\206\240\353\204\210.py" "b/10546\353\260\260\353\266\200\353\245\270\353\247\210\353\235\274\355\206\240\353\204\210.py" deleted file mode 100644 index c4f05d6..0000000 --- "a/10546\353\260\260\353\266\200\353\245\270\353\247\210\353\235\274\355\206\240\353\204\210.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -# person : 참가한 사람들의 dict -# finish : 완주한 사람들의 dict -person = dict() -finish = dict() -answer = "" -for _ in range(N) : - name = input().rstrip() - if name in person : - person[name] += 1 - else : - person[name] = 1 - -for _ in range(N-1) : - name = input().rstrip() - if name in finish : - finish[name] += 1 - else : - finish[name] = 1 - - -for n in person.keys() : - # 참가자에는 있지만 완주자에는 없다면 해당 키가 정답 - if n not in finish : - answer = n - break - else : - # 참가자의 value와 완주자의 value가 다르다면 해당 키가 정답 - if person[n] != finish[n] : - answer = n - break -print(answer) \ No newline at end of file diff --git "a/10597\354\210\234\354\227\264\354\236\245\353\202\234.py" "b/10597\354\210\234\354\227\264\354\236\245\353\202\234.py" index 1c750ff..a2bda42 100644 --- "a/10597\354\210\234\354\227\264\354\236\245\353\202\234.py" +++ "b/10597\354\210\234\354\227\264\354\236\245\353\202\234.py" @@ -1,37 +1,34 @@ -import sys -from collections import deque - - -def DFS(idx): - # idx 1부터 시작 kriii의 검사가 모두 끝나면 수열의 가장 큰 값을 찾는다. - if idx == len(kriii): - high = 0 - for i in range(len(sequence)): - high = max(high,int(sequence[i])) - # 가장 큰 값이 수열의 길이와 같으면 출력, 아니면 회귀 - if high == len(sequence): - print(*list(map(int,(sequence)))) - sys.exit() - return - # dfs로 배열에 하나넣거나 두개는경우를 동시에 둘 다 조사하며 재귀 진행.(분기가 있는 DFS) - # 글자 하나만 조사.idx 하나 건너뛴다. - if idx < len(kriii) and int(kriii[idx]) <= 50 and not visited[int(kriii[idx])]: - visited[int(kriii[idx])] = 1 - sequence.append(kriii[idx]) - DFS(idx+1) - sequence.pop() - visited[int(kriii[idx])] = 0 - - # 글자 두개조사. 두개짤랐을때 50이하. 그리고 그 숫자가 전에 방문한적 없었을때 방문.idx 2개 건너뛴다. - if idx + 1 < len(kriii) and int(kriii[idx:idx+2]) <= 50 and not visited[int(kriii[idx:idx+2])]: - visited[int(kriii[idx:idx+2])] = 1 - sequence.append(kriii[idx:idx+2]) - DFS(idx+2) - visited[int(kriii[idx:idx+2])] = 0 - sequence.pop() - - -kriii = input() -sequence = deque() -visited = [0] * 51 -DFS(0) +import sys +from collections import deque + + +def DFS(idx): + if idx == len(kriii): + high = 0 + for i in range(len(sequence)): + high = max(high,int(sequence[i])) + + if high == len(sequence): + print(*list(map(int,(sequence)))) + sys.exit() + return + + if idx < len(kriii) and int(kriii[idx]) <= 50 and not visited[int(kriii[idx])]: + visited[int(kriii[idx])] = 1 + sequence.append(kriii[idx]) + DFS(idx+1) + sequence.pop() + visited[int(kriii[idx])] = 0 + + if idx + 1 < len(kriii) and int(kriii[idx:idx+2]) <= 50 and not visited[int(kriii[idx:idx+2])]: + visited[int(kriii[idx:idx+2])] = 1 + sequence.append(kriii[idx:idx+2]) + DFS(idx+2) + visited[int(kriii[idx:idx+2])] = 0 + sequence.pop() + + +kriii = input() +sequence = deque() +visited = [0] * 51 +DFS(0) diff --git "a/1059\354\242\213\354\235\200\352\265\254\352\260\204.py" "b/1059\354\242\213\354\235\200\352\265\254\352\260\204.py" deleted file mode 100644 index 1a73c7e..0000000 --- "a/1059\354\242\213\354\235\200\352\265\254\352\260\204.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect - -L = int(input()) -AB_list = list(map(int,input().split())) -AB_list.sort() -N = int(input()) -if N < AB_list[0]: - answer = max(0,(AB_list[0]-N)*(N)-1) -else: - index= bisect(AB_list,N) - answer = max(0,(AB_list[index]-N)*(N-AB_list[index-1])-1) -print(answer) \ No newline at end of file diff --git "a/1061\354\202\274\352\260\201\355\230\225.py" "b/1061\354\202\274\352\260\201\355\230\225.py" deleted file mode 100644 index 88a9010..0000000 --- "a/1061\354\202\274\352\260\201\355\230\225.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -from collections import Counter -input = sys.stdin.readline - -def triangle_area(tri): - y_list = [tri[0][1], tri[1][1], tri[2][1]] - x_list = [tri[0][0], tri[1][0], tri[2][0]] - height = max(y_list) - min(y_list) - width = max(x_list) - min(x_list) - return height * width / 2 - -n,m = map(int,input().split()) - -matrix = [list(input().rstrip()) for _ in range(n)] -counter = {'R': 0, 'G':0 , 'B':0} -for i in range(n): - A = list(Counter(matrix[i]).items()) - for colors in A: - key,value = colors - counter[key] += value - -max_cnt = 1 -for color in 'RGB': - max_cnt*=counter[color] - -for i in range(n): - for j in range(m): diff --git "a/1062\352\260\200\353\245\264\354\271\250.py" "b/1062\352\260\200\353\245\264\354\271\250.py" deleted file mode 100644 index da873f0..0000000 --- "a/1062\352\260\200\353\245\264\354\271\250.py" +++ /dev/null @@ -1,38 +0,0 @@ -from itertools import combinations -n, k = map(int, input().split()) -# 글자가 5개 미만이면 antic도 못배우니까 어떤 글자도 배울 수 없다. -if k < 5: - print(0) -else: - # 일단 5개배우고 시작. - k -= 5 - nece_chars = {'a', 'n', 't', 'i', 'c'} - input_chars = [] - # a~z중 antic뺀 나머지 chr들.을 index와 짝지어 딕셔너리 형태로 저장.(a:0,b:1....)숫자가 임의로 설정되어있음. - alpha = {ky: v for v, ky in enumerate( - (set(map(chr, range(ord('a'), ord('z')+1))) - nece_chars))} - print(alpha) - cnt = 0 - # n번의 글자입력 - for _ in range(n): - tmp = 0 - # 배운 글자를 뺀 나머지 글자c들에 대해 순회하며 비트마스킹 한 숫자를(필요한 숫자에 마스킹) tmp에 표기해 input_chars에 저장..(나온 글자들에 불을 켜.) - for c in set(input())-nece_chars: - tmp |= (1 << alpha[c]) - input_chars.append(tmp) - # antic을 뺀 나머지 21개글자를 나타내는 숫자들(2의 n승이 비트마스킹에서 각자리 1을 나타내기 때문)(그 숫자들중 k개를 뽑는 조합을 다 순회.) - power_by_2 = (2**i for i in range(21)) - for comb in combinations(power_by_2, k): - # 조합의 sum은 input_chars에 들어있는 비트마스킹된 숫자들과 비교할 test에 저장. - test = sum(comb) - -# input_chars에 넣어둔 필요한 알파뱃 조합들과 test로 생성한 남은 알파뱃중 만들수 있는 모든 조합과 비교해 일치하면 cnt하나 상승. -# test 문자(합이 문자)와 input_char에서 그 test숫자로 만들수있는 단어의 수를 세어ct에 저장하고 cnt에 최댓값 저장. -# (각 문자 셋을 조합으로 만들어 비교 후 최대 몇개 만족하나 저장.) - ct = 0 - for cb in input_chars: - if test & cb == cb: - ct += 1 - - cnt = max(cnt, ct) - print(cnt) \ No newline at end of file diff --git "a/1065 \355\225\234\354\210\230.py" "b/1065 \355\225\234\354\210\230.py" deleted file mode 100644 index edeb8d7..0000000 --- "a/1065 \355\225\234\354\210\230.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -answer = 0 -for num in range(1, N + 1): - if num < 100: - answer += 1 - else: - digits = list(map(int, str(num))) - if digits[0] - digits[1] == digits[1] - digits[2]: - answer += 1 -print(answer) \ No newline at end of file diff --git "a/10653\353\247\210\353\235\274\355\206\2442.py" "b/10653\353\247\210\353\235\274\355\206\2442.py" deleted file mode 100644 index eaf6628..0000000 --- "a/10653\353\247\210\353\235\274\355\206\2442.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys - - -INF = 1e10 -if __name__ == "__main__": - n, k = map(int, sys.stdin.readline().split()) - point = [list(map(int, sys.stdin.readline().split())) for _ in range(n)] - - distance = [[0 for _ in range(n)] for _ in range(n)] - for i in range(n): - for j in range(n): - distance[i][j] = abs(point[i][0] - point[j][0]) + abs(point[i][1] - point[j][1]) - - dp = [[INF for _ in range(n)] for _ in range(k + 1)] - dp[0][0] = 0 - - # k = 0 - for i in range(1, n): - dp[0][i] = dp[0][i - 1] + distance[i - 1][i] - - # k = 1, 2, ... k - for i in range(1, k + 1): - dp[i][0], dp[i][1] = 0, dp[i - 1][1] - dp[i][i] = distance[0][i] - for j in range(1, n): - for m in range(i, 0, -1): - if j - m - 1 < 0: - continue - dp[i][j] = min(dp[i][j], dp[i - m][j - m - 1] + distance[j][j - m - 1], dp[i][j - 1] + distance[j - 1][j]) - - print(dp[-1][-1]) \ No newline at end of file diff --git "a/1068 \355\212\270\353\246\254.py" "b/1068 \355\212\270\353\246\254.py" deleted file mode 100644 index 774a25c..0000000 --- "a/1068 \355\212\270\353\246\254.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -nodes = set([i for i in range(N)]) -childs = {i: [] for i in range(-1,N)} -parents = list(map(int, input().split())) -parent_node = set() -for i in range(N): - childs[parents[i]].append(i) - parent_node.add(parents[i]) -leafs = nodes - parent_node -del_node = int(input()) -q = [del_node] -while q: - x = q.pop() - if x in leafs: - leafs.discard(x) - for child in childs[x]: - q.append(child) -print(len(leafs)+1 if parents[del_node] != -1 and len(childs[parents[del_node]])==1 else len(leafs)) \ No newline at end of file diff --git a/1074Z.py b/1074Z.py deleted file mode 100644 index 055c05b..0000000 --- a/1074Z.py +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -# 핵심은 배열을 4등분하는 분할을 통해 -# 배열의 크기가 1인 사각형들의 모임으로 만드는 것. -def Z(n,r,c): - # 배열의 크기가 1이 되면 0을 정복하여 반환한다. - if n==0: - return 0 - # 배열의 크기를 반을 기준으로 4영역으로 분할한다. - harf = 2**(n-1) - if r < harf and c=harf: - return harf**2 + Z(n-1,r,c-harf) - elif r >=harf and cmax: - answer = '-1 ' + answer - arr2.append(a) - max = a - break - else: - answer = '-1 ' + answer - arr2.append(a) - max = a - -print(answer) \ No newline at end of file diff --git "a/1080 \355\226\211\353\240\254.py" "b/1080 \355\226\211\353\240\254.py" deleted file mode 100644 index 35759fc..0000000 --- "a/1080 \355\226\211\353\240\254.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -A = [list(map(int, list(input().rstrip()))) for _ in range(N)] -B = [list(map(int, list(input().rstrip()))) for _ in range(N)] -cnt = 0 -for i in range(N): - for j in range(M): - if i < N - 2 and j < M - 2: - if A[i][j] != B[i][j]: - for x in range(i, i + 3): - for y in range(j, j + 3): - A[x][y] ^= 1 - cnt += 1 - else: - if A[i][j] != B[i][j]: - print(-1) - exit() -print(cnt) \ No newline at end of file diff --git "a/10808\354\225\214\355\214\214\353\261\203\352\260\234\354\210\230.py" "b/10808\354\225\214\355\214\214\353\261\203\352\260\234\354\210\230.py" index 315ff2e..076cf33 100644 --- "a/10808\354\225\214\355\214\214\353\261\203\352\260\234\354\210\230.py" +++ "b/10808\354\225\214\355\214\214\353\261\203\352\260\234\354\210\230.py" @@ -1,9 +1,10 @@ - -S = input() -alpha = [0]*26 - -for ch in S: - alpha[ord(ch)-ord('a')] += 1 - -for i in alpha: + +S = input() +alpha = [-1]*26 + +for i in range(len(S)): + if(alpha[ord(S[i])-ord('a')] == -1): + alpha[ord(S[i])-ord('a')] = i + +for i in alpha: print(i,end=" ") \ No newline at end of file diff --git a/10809.py b/10809.py deleted file mode 100644 index 3d896ea..0000000 --- a/10809.py +++ /dev/null @@ -1,10 +0,0 @@ -T = int(input()) -for test in range(T): - N, W = input().split() - W = list(W) - ans = [] - for i in range(len(W)): - for _ in range(int(N)): - ans.append(W[i]) - - print("".join(ans)) \ No newline at end of file diff --git "a/10809\354\225\214\355\214\214\353\261\203\354\260\276\352\270\260.py" "b/10809\354\225\214\355\214\214\353\261\203\354\260\276\352\270\260.py" index a16556d..076cf33 100644 --- "a/10809\354\225\214\355\214\214\353\261\203\354\260\276\352\270\260.py" +++ "b/10809\354\225\214\355\214\214\353\261\203\354\260\276\352\270\260.py" @@ -1,10 +1,10 @@ - -S = input() -alpha = [-1]*26 - -for i in range(len(S)): - if(alpha[ord(S[i])-ord('a')] == -1): - alpha[ord(S[i])-ord('a')] = i - -for i in alpha: + +S = input() +alpha = [-1]*26 + +for i in range(len(S)): + if(alpha[ord(S[i])-ord('a')] == -1): + alpha[ord(S[i])-ord('a')] = i + +for i in alpha: print(i,end=" ") \ No newline at end of file diff --git "a/10819\353\235\274\354\235\264\353\270\214\353\237\254\353\246\254\354\227\206\354\235\264.py" "b/10819\353\235\274\354\235\264\353\270\214\353\237\254\353\246\254\354\227\206\354\235\264.py" index 58e0874..07245f5 100644 --- "a/10819\353\235\274\354\235\264\353\270\214\353\237\254\353\246\254\354\227\206\354\235\264.py" +++ "b/10819\353\235\274\354\235\264\353\270\214\353\237\254\353\246\254\354\227\206\354\235\264.py" @@ -1,57 +1,57 @@ -import sys - - -def next_permutation(list_a): - k = -1 - m = -1 - - # 증가하는 마지막 부분을 가리키는 index k 찾기 - for i in range(len(list_a)-1): - if list_a[i] < list_a[i+1]: - k = i - - # 전체 내림차순일 경우, 반환 - if k == -1: - return [-1] - - # index k 이후 부분 중 값이 k보다 크면서 가장 멀리 있는 index m 찾기 - for i in range(k, len(list_a)): - if list_a[k] < list_a[i]: - m = i - - # k와 m의 값 바꾸기 - list_a[k], list_a[m] = list_a[m], list_a[k] - - # k index 이후 오름차순 정렬 - list_a = list_a[:k+1] + sorted(list_a[k+1:]) - return list_a - - -# 주어진 값 입력 & 정렬 -n = int(sys.stdin.readline()) -a = list(map(int, sys.stdin.readline().split())) -a.sort() - -ans = 0 -# 첫 순열 내 값 차이를 더해(s), ans 보다 크면 ans를 update -s = 0 -for j in range(len(a) - 1): - s += abs(a[j] - a[j+1]) -if s > ans: - ans = s - -arr = a - -while True: - arr = next_permutation(arr) - if arr == [-1]: - break - s = 0 - - # 순열마다 차이를 더해(s), ans 보다 크면 ans를 update - for j in range(len(arr) - 1): - s += abs(arr[j] - arr[j+1]) - if s > ans: - ans = s - +import sys + + +def next_permutation(list_a): + k = -1 + m = -1 + + # 증가하는 마지막 부분을 가리키는 index k 찾기 + for i in range(len(list_a)-1): + if list_a[i] < list_a[i+1]: + k = i + + # 전체 내림차순일 경우, 반환 + if k == -1: + return [-1] + + # index k 이후 부분 중 값이 k보다 크면서 가장 멀리 있는 index m 찾기 + for i in range(k, len(list_a)): + if list_a[k] < list_a[i]: + m = i + + # k와 m의 값 바꾸기 + list_a[k], list_a[m] = list_a[m], list_a[k] + + # k index 이후 오름차순 정렬 + list_a = list_a[:k+1] + sorted(list_a[k+1:]) + return list_a + + +# 주어진 값 입력 & 정렬 +n = int(sys.stdin.readline()) +a = list(map(int, sys.stdin.readline().split())) +a.sort() + +ans = 0 +# 첫 순열 내 값 차이를 더해(s), ans 보다 크면 ans를 update +s = 0 +for j in range(len(a) - 1): + s += abs(a[j] - a[j+1]) +if s > ans: + ans = s + +arr = a + +while True: + arr = next_permutation(arr) + if arr == [-1]: + break + s = 0 + + # 순열마다 차이를 더해(s), ans 보다 크면 ans를 update + for j in range(len(arr) - 1): + s += abs(arr[j] - arr[j+1]) + if s > ans: + ans = s + print(ans) \ No newline at end of file diff --git "a/10819\354\260\250\354\235\264\353\245\274\354\265\234\353\214\200\353\241\234.py" "b/10819\354\260\250\354\235\264\353\245\274\354\265\234\353\214\200\353\241\234.py" index 6f188dc..ea917d0 100644 --- "a/10819\354\260\250\354\235\264\353\245\274\354\265\234\353\214\200\353\241\234.py" +++ "b/10819\354\260\250\354\235\264\353\245\274\354\265\234\353\214\200\353\241\234.py" @@ -1,15 +1,15 @@ -import sys -input = sys.stdin.readline -from itertools import permutations - -N = int(input()) -A = list(map(int,input().split())) -p = permutations(A) -ans = [] -for nums in p: - sum_nums = 0 - for i in range(0,len(nums)-1): - sum_nums += abs(nums[i]-nums[i+1]) - ans.append(sum_nums) - +import sys +input = sys.stdin.readline +from itertools import permutations + +N = int(input()) +A = list(map(int,input().split())) +p = permutations(A) +ans = [] +for nums in p: + sum_nums = 0 + for i in range(0,len(nums)-1): + sum_nums += abs(nums[i]-nums[i+1]) + ans.append(sum_nums) + print(max(ans)) \ No newline at end of file diff --git a/10820.py b/10820.py index f6d2531..2782e78 100644 --- a/10820.py +++ b/10820.py @@ -1,19 +1,19 @@ -import sys - -while True: - line = sys.stdin.readline().rstrip('\n') - up, lo, sp, nu = 0, 0, 0, 0 - if not line: - break - for l in line: - if l.isupper(): - up += 1 - elif l.islower(): - lo += 1 - elif l.isdigit(): - nu += 1 - elif l.isspace(): - sp += 1 - - sys.stdout.write("{} {} {} {}\n".format(lo, up, nu, sp)) - +import sys + +while True: + line = sys.stdin.readline().rstrip('\n') + up, lo, sp, nu = 0, 0, 0, 0 + if not line: + break + for l in line: + if l.isupper(): + up += 1 + elif l.islower(): + lo += 1 + elif l.isdigit(): + nu += 1 + elif l.isspace(): + sp += 1 + + sys.stdout.write("{} {} {} {}\n".format(lo, up, nu, sp)) + diff --git "a/10824\353\204\244\354\210\230.py" "b/10824\353\204\244\354\210\230.py" index 253ee7e..dbc6285 100644 --- "a/10824\353\204\244\354\210\230.py" +++ "b/10824\353\204\244\354\210\230.py" @@ -1,6 +1,3 @@ -num = list(input().split()) - -A = int(num[0] + num[1]) -B = int(num[2] + num[3]) - -print(A+B) +S = ["a","b","c"] +B = ["a"] +print(S-B) \ No newline at end of file diff --git a/10828.py b/10828.py deleted file mode 100644 index ed4ff42..0000000 --- a/10828.py +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline -n = int(input()) -s = [list(input().split()) for i in range(n)] -print(s) -for i in range(n): - for j in s[i]: - print(''.join(reversed(list(j))), end=" ") - print() - - diff --git "a/10844\354\211\254\354\232\264\352\263\204\353\213\250\354\210\230.py" "b/10844\354\211\254\354\232\264\352\263\204\353\213\250\354\210\230.py" deleted file mode 100644 index 56c727c..0000000 --- "a/10844\354\211\254\354\232\264\352\263\204\353\213\250\354\210\230.py" +++ /dev/null @@ -1,16 +0,0 @@ -N = int(input()) -dp = [[0 for _ in range(10)] for _ in range(N)] - -for i in range(1,10): - dp[0][i] = 1 -if N>1: - for i in range(1,N): - for j in range(10): - if j==0: - dp[i][j] = (dp[i-1][j+1])%1000000000 - elif j==9: - dp[i][j] = (dp[i-1][j-1])%1000000000 - else: - dp[i][j] = (dp[i-1][j-1] + dp[i-1][j+1])%1000000000 - -print(sum(dp[N-1])%1000000000) \ No newline at end of file diff --git "a/10845_deque\354\227\260\354\212\265.py" "b/10845_deque\354\227\260\354\212\265.py" deleted file mode 100644 index aef99cd..0000000 --- "a/10845_deque\354\227\260\354\212\265.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys,collections -input = sys.stdin.readline - - -N,K = map(int,input().split()) -nums = [i for i in range(1,N+1)] -answer = [] - -for i in range(N*K): - if i%K==K-1: - answer.append(nums[i%N]) - del nums[i%N] - if not nums: - break - - -answer = ', '.join(list(map(str,answer))) -print(f"<{answer}>") - - diff --git a/10845_queue.py b/10845_queue.py deleted file mode 100644 index c35eaa2..0000000 --- a/10845_queue.py +++ /dev/null @@ -1,35 +0,0 @@ -import collections, sys -input = sys.stdin.readline - - - -N = int(input()) -queue = collections.deque() - -for order in range(N): - p = list(input().split()) - if p[0] == 'push': - queue.append(p[1]) - elif p[0] == 'pop': - if queue: - print(queue.popleft()) - else: - print(-1) - elif p[0] == 'size': - print(len(queue)) - elif p[0] == 'empty': - if queue: - print(0) - else: - print(1) - elif p[0] =='front': - if queue: - print(queue[0]) - else: - print(-1) - elif p[0] =='back': - if queue: - print(queue[-1]) - else: - print(-1) - diff --git "a/10868\354\265\234\354\206\237\352\260\222.py" "b/10868\354\265\234\354\206\237\352\260\222.py" deleted file mode 100644 index c20c3e7..0000000 --- "a/10868\354\265\234\354\206\237\352\260\222.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -from math import ceil, log -input = sys.stdin.readline - -def minimum(left, right, node_left, node_right, node_num): - if left > node_right or right < node_left: - return 1000000000 - if left <= node_left and right >= node_right: - return arr[node_num] - mid = (node_left + node_right)//2 - return min(minimum(left, right, node_left, mid, node_num*2), minimum(left, right, mid+1, node_right, node_num*2 + 1)) - -def init(size): - for i in range(size - 1, 0, -1): - arr[i] = min(arr[i*2], arr[i*2 + 1]) - -if __name__ == "__main__": - N, M = map(int,input().split()) - size = 2**ceil(log(N,2)) - size_max = size * 2 - arr = [1000000000]*(size_max) - for i in range(N): - arr[size+i]=int(input()) - init(size) - for _ in range(M): - s, e = map(int,input().split()) - print(minimum(s-1, e-1, 0, size - 1,1)) - diff --git "a/10868\354\265\234\354\206\237\352\260\222_\354\240\225\354\204\235.py" "b/10868\354\265\234\354\206\237\352\260\222_\354\240\225\354\204\235.py" deleted file mode 100644 index 6ea3659..0000000 --- "a/10868\354\265\234\354\206\237\352\260\222_\354\240\225\354\204\235.py" +++ /dev/null @@ -1,36 +0,0 @@ -import sys -input = sys.stdin.readline -from math import ceil,log2 - -def init(node,start,end): - if start==end: - tree[node] = arr[start] - return tree[node] - - mid = (start+end)//2 - tree[node] = min(init(node*2,start,mid),init(node*2+1,mid+1,end)) - return tree[node] - -def query(node,start,end,left,right): - if start > right or end < left: - return float('inf') - if left <=start and end <= right: - return tree[node] - - mid = (start+end)//2 - return min(query(node*2,start,mid,left,right),query(node*2+1,mid+1,end,left,right)) - -N,M = map(int,input().split()) -h = int(ceil(log2(N))) -t_size = 1<<(h+1) -arr = [] -tree = [0] * t_size - -for _ in range(N): - arr.append(int(input())) - -init(1,0,N-1) - -for _ in range(M): - a,b = map(int,input().split()) - print(query(1,0,N-1,a-1,b-1)) \ No newline at end of file diff --git "a/10872\355\214\251\355\206\240\353\246\254\354\226\274.py" "b/10872\355\214\251\355\206\240\353\246\254\354\226\274.py" index 9135c32..1f08090 100644 --- "a/10872\355\214\251\355\206\240\353\246\254\354\226\274.py" +++ "b/10872\355\214\251\355\206\240\353\246\254\354\226\274.py" @@ -1,8 +1,8 @@ -N = int(input()) - -ans=1 -if N>1: - for i in range(2,N+1): - ans *= i - +N = int(input()) + +ans=1 +if N>1: + for i in range(2,N+1): + ans *= i + print(ans) \ No newline at end of file diff --git "a/1094\353\247\211\353\214\200\352\270\260.py" "b/1094\353\247\211\353\214\200\352\270\260.py" deleted file mode 100644 index 4ccf20e..0000000 --- "a/1094\353\247\211\353\214\200\352\270\260.py" +++ /dev/null @@ -1,2 +0,0 @@ - -print(str(bin(int(input()))[2:]).count('1')) \ No newline at end of file diff --git "a/10971\354\231\270\355\214\220\354\233\220_\353\271\204\355\212\270\353\247\210\354\212\244\355\201\254.py" "b/10971\354\231\270\355\214\220\354\233\220_\353\271\204\355\212\270\353\247\210\354\212\244\355\201\254.py" deleted file mode 100644 index 66b34ac..0000000 --- "a/10971\354\231\270\355\214\220\354\233\220_\353\271\204\355\212\270\353\247\210\354\212\244\355\201\254.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -def find(now, before): - # 남아있는 경로를 이미 방문한 적이 있음 (지금 있는곳과 켜진 경로와 꺼진 경로가 예전꺼랑 같으면)그냥 반환. - if dp[now][before]: - return dp[now][before] - # # 모두 방문한 경우 내가 있는 마을에서 1번 마을로 갈 길이 있다면(비용이 있다면) 그 비용에 대해 반환 -> 반환되면 cost에 path[now][i]와 합쳐저 최솟값을 찾아감. - if before == (1< 0: - return path[now][0] - else: - # 못가면 무한대 반환. -> 결국 min연산에 의해 경로 삭제됨. - return sys.maxsize - # # 현재 지점에서 이동할 수 있는 지점들을 탐색 - cost = sys.maxsize - # 결국 모든 경로에 대해 조사하는 dfs느낌이지만 메모이제이션이나 dp를 사용해 메모리나 속도가 압도적. - # 시작점에서 나오는 모든 dfs재귀순환 연산이 끝나면.cost에는 모든경로와 비교한 최솟값이 저장됨. - for i in range(1, n): - # 여기서 i로 가는 길이 있고 (before를 i만큼 땡겨서 i번째 마을을 1의 자리에 놓고 2로 나눈 나머지가 0일때) 즉 i번째 마을을 들리지 않은 상태였을때. - if not (before>>i)%2 and path[now][i]: - # i부터 0까지 순회를 만든 최소 비용 i번 마을에 들러서 탐색을 시작한다. - tmp = find(i, before|(1< s[-i-1]: - for j in range(1,i): - if s[-i-1] < s[-j]: - s[-i-1],s[-j] = s[-j],s[-i-1] - s = s[:-i] + sorted(s[-i:]) - flag = 1 - break - if flag: - print(*s) - break - -if not flag: - print(-1) - - - -12345 -12354 -12534 -12543 -15234 -15243 -15324 -15342 -15423 -15432 +import sys +input = sys.stdin.readline + +N = int(input()) +s = list(map(int,input().split())) +flag = 0 +for i in range(1,N): + if s[-i] > s[-i-1]: + for j in range(1,i): + if s[-i-1] < s[-j]: + s[-i-1],s[-j] = s[-j],s[-i-1] + s = s[:-i-1] + sorted(s[-i-1:]) + flag = 1 + break + if flag: + print(*s) + break + +if not flag: + print(-1) + diff --git "a/10973\354\235\264\354\240\204\354\210\234\354\227\264.py" "b/10973\354\235\264\354\240\204\354\210\234\354\227\264.py" index 22dcf14..38e56ba 100644 --- "a/10973\354\235\264\354\240\204\354\210\234\354\227\264.py" +++ "b/10973\354\235\264\354\240\204\354\210\234\354\227\264.py" @@ -1,20 +1,20 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -pers = list(map(int,input().split())) -ans = [] - -for i in range(N-1,0,-1): - if pers[i] < pers[i-1]: - for j in range(N-1,i-1,-1): - if pers[i-1] >pers[j]: - pers[i-1],pers[j] = pers[j],pers[i-1] - ans = pers[:i] + sorted(pers[i:],reverse=True) - print(*ans) - break - if ans: - break - -if not ans: - print(-1) +import sys +input = sys.stdin.readline + +N = int(input()) +pers = list(map(int,input().split())) +ans = [] + +for i in range(N-1,0,-1): + if pers[i] < pers[i-1]: + for j in range(N-1,i-1,-1): + if pers[i-1] >pers[j]: + pers[i-1],pers[j] = pers[j],pers[i-1] + ans = pers[:i] + sorted(pers[i:],reverse=True) + print(*ans) + break + if ans: + break + +if not ans: + print(-1) diff --git "a/10974\353\252\250\353\223\240\354\210\234\354\227\264.py" "b/10974\353\252\250\353\223\240\354\210\234\354\227\264.py" index 3b5ce70..c21434c 100644 --- "a/10974\353\252\250\353\223\240\354\210\234\354\227\264.py" +++ "b/10974\353\252\250\353\223\240\354\210\234\354\227\264.py" @@ -1,7 +1,7 @@ -from itertools import permutations - -N = int(input()) - -permutation_s = permutations(range(1,N+1)) -for x in permutation_s: +from itertools import permutations + +N = int(input()) + +permutation_s = permutations(range(1,N+1)) +for x in permutation_s: print(*x) \ No newline at end of file diff --git "a/10974\353\252\250\353\223\240\354\210\234\354\227\264_dfs.py" "b/10974\353\252\250\353\223\240\354\210\234\354\227\264_dfs.py" index 09d2c22..8532fd3 100644 --- "a/10974\353\252\250\353\223\240\354\210\234\354\227\264_dfs.py" +++ "b/10974\353\252\250\353\223\240\354\210\234\354\227\264_dfs.py" @@ -1,24 +1,21 @@ -from sys import stdin - - -def dfs(depth): - global answer - - if depth == n: - answer.append([num for num in check]) - else: - for i in range(n): - if i + 1 in check: - continue - check[depth] = i + 1 - dfs(depth + 1) - check[depth] = 0 - -if __name__ == '__main__': - answer = [] - n = int(stdin.readline()) - check = [0] * n - dfs(0) - - for case in answer: - print(*case) \ No newline at end of file +from sys import stdin + + +def dfs(depth): + if depth == n: + answer.append([num for num in permutation_deep]) + else: + for i in range(n): + if i + 1 in permutation_deep: + continue + permutation_deep[depth] = i + 1 + dfs(depth + 1) + permutation_deep[depth] = 0 + +answer = [] +n = int(stdin.readline()) +permutation_deep = [0] * n +dfs(0) + +for case in answer: + print(*case) \ No newline at end of file diff --git "a/10988\355\214\260\353\246\260\353\223\234\353\241\254\354\235\270\354\247\200 \355\231\225\354\235\270\355\225\230\352\270\260.py" "b/10988\355\214\260\353\246\260\353\223\234\353\241\254\354\235\270\354\247\200 \355\231\225\354\235\270\355\225\230\352\270\260.py" index 77a77c8..77b99af 100644 --- "a/10988\355\214\260\353\246\260\353\223\234\353\241\254\354\235\270\354\247\200 \355\231\225\354\235\270\355\225\230\352\270\260.py" +++ "b/10988\355\214\260\353\246\260\353\223\234\353\241\254\354\235\270\354\247\200 \355\231\225\354\235\270\355\225\230\352\270\260.py" @@ -1,13 +1,13 @@ -import sys -input = sys.stdin.readline - -S = tuple(input().rstrip()) - -S_copy = S -S_copy = list(S_copy) -reverse_S = [] -for _ in range(len(S)): - reverse_S.append(S_copy.pop()) -S = list(S) - +import sys +input = sys.stdin.readline + +S = tuple(input().rstrip()) + +S_copy = S +S_copy = list(S_copy) +reverse_S = [] +for _ in range(len(S)): + reverse_S.append(S_copy.pop()) +S = list(S) + print(1 if S==reverse_S else 0) \ No newline at end of file diff --git "a/10994 \353\263\204\354\260\215\352\270\26014.py" "b/10994 \353\263\204\354\260\215\352\270\26014.py" deleted file mode 100644 index a976593..0000000 --- "a/10994 \353\263\204\354\260\215\352\270\26014.py" +++ /dev/null @@ -1,46 +0,0 @@ -import sys -input = sys.stdin.readline - -def draw(n,idx): - if n==1: - stars[idx][idx] = '*' - return ; - l = 4*n-3 - - for i in range(idx,l+idx): - stars[idx][i]='*' - stars[idx+l-1][i]='*' - - stars[i][idx]='*' - stars[i][idx+l-1]='*' - - return draw(n-1,idx+2) - -n = int(input()) # n을 입력받는다. -lens = 4*n -3 - -stars = [[' ']*lens for _ in range(lens) ] - -draw(n,0) - -for i in range(lens): - for j in range(lens): - print(stars[i][j],end="") - print() - - -# 풀이 2 -num = int(input()) -print('*'*(1+(num-1)*4)) -for i in range(1, 2*num-1): - if i % 2: - print('* '*((i+1)//2) + ' '*(1+(num-1)*4-(i+1)//2*4) + ' *'*((i+1)//2)) - else: - print('* '*((i+1)//2) + '*'*(1+(num-1)*4-(i+1)//2*4) + ' *'*((i+1)//2)) -for i in range(2*num-3, 0, -1): - if i % 2: - print('* '*((i+1)//2) + ' '*(1+(num-1)*4-(i+1)//2*4) + ' *'*((i+1)//2)) - else: - print('* '*((i+1)//2) + '*'*(1+(num-1)*4-(i+1)//2*4) + ' *'*((i+1)//2)) -if num != 1: - print('*'*(1+(num-1)*4)) \ No newline at end of file diff --git "a/10999\352\265\254\352\260\204\355\225\251\352\265\254\355\225\230\352\270\2602.py" "b/10999\352\265\254\352\260\204\355\225\251\352\265\254\355\225\230\352\270\2602.py" deleted file mode 100644 index fdb85a8..0000000 --- "a/10999\352\265\254\352\260\204\355\225\251\352\265\254\355\225\230\352\270\2602.py" +++ /dev/null @@ -1,64 +0,0 @@ -import sys -import math -from collections import deque -import copy -input=sys.stdin.readline -INF=sys.maxsize - -def init(arr,tree,start,end,node): - if start==end: - tree[node]=arr[start] - else: - mid = (start+end)//2 - init(arr,tree,start,mid,node*2) - init(arr,tree,mid+1,end,node*2+1) - tree[node]=tree[node*2]+tree[node*2+1] - -def update_lazy(tree,lazy,node,start,end): - if lazy[node] !=0: - tree[node] += (end-start+1)*lazy[node] - if start!=end: - lazy[node*2]+=lazy[node] - lazy[node*2+1]+=lazy[node] - lazy[node]=0 - -def update_range(tree,lazy,start,end,node,idx_start,idx_end,dif): - update_lazy(tree,lazy,node,start,end) - if idx_start>end or start>idx_end: return - - if start>=idx_start and idx_end>=end: - tree[node]+=(end-start+1)*dif - if start!=end: - lazy[node*2]+=dif - lazy[node*2+1]+=dif - return - - mid = (start+end)//2 - update_range(tree,lazy,start,mid,node*2,idx_start,idx_end,dif) - update_range(tree,lazy,mid+1,end,node*2+1,idx_start,idx_end,dif) - tree[node]=tree[node*2]+tree[node*2+1] - -def sum(tree,lazy,start,end,node,left,right): - update_lazy(tree,lazy,node,start,end) - if left>end or start>right:return 0 - if start>=left and right>=end: return tree[node] - - mid=(start+end)//2 - return sum(tree,lazy,start,mid,node*2,left,right)+sum(tree,lazy,mid+1,end,node*2+1,left,right) - -if __name__ == "__main__": - n,m,k=map(int,input().split()) - arr=[int(input()) for _ in range(n)] - val=[list(map(int,input().split())) for _ in range(m+k)] - #tree_list=[0]*(pow(2,math.ceil(math.log(n,2))+1)-1) - tree_list=[0]*(n*4) - lazy=[0]*(n*4) - init(arr,tree_list,0,n-1,1) - - for v in val: - b,c=v[1],v[2] - if v[0]==1: #b~c까지 d를 더함 - d=v[3] - update_range(tree_list,lazy,0,n-1,1,b-1,c-1,d) - else: - print(sum(tree_list,lazy,0,n-1,1,b-1,c-1)) \ No newline at end of file diff --git "a/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225.py" "b/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225.py" index 87d10cf..376b47b 100644 --- "a/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225.py" +++ "b/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225.py" @@ -1,23 +1,19 @@ -import heapq -import sys - -N = int(input()) - -timeTable = [list(map(int,sys.stdin.readline().split())) for _ in range(N)] -timeTable.sort(key=lambda x: x[0]) - -queue = [] -heapq.heappush(queue,timeTable[0][1]) - -for i in range(1,N): - # last_time이 들어오는 시작시간보다 크면?(queue[0]은 가장 작은 last_time) - # 방하나 늘어남 - if queue[0] > timeTable[i][0]: - heapq.heappush(queue,timeTable[i][1]) - # 가장 작은 last_time보다 시작시간이 크면 작은거 pop하고 새로운거 넣는다. - # 방 고대로(pop하고 넣고 반복.) - else: - heapq.heappop(queue) - heapq.heappush(queue,timeTable[i][1]) - -print(len(queue)) +import heapq +import sys + +N = int(input()) + +timeTable = [list(map(int,sys.stdin.readline().split())) for _ in range(N)] +timeTable.sort(key=lambda x: x[0]) + +queue = [] +heapq.heappush(queue,timeTable[0][1]) + +for i in range(1,N): + if queue[0] > timeTable[i][0]: + heapq.heappush(queue,timeTable[i][1]) + else: + heapq.heappop(queue) + heapq.heappush(queue,timeTable[i][1]) + +print(len(queue)) diff --git "a/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225_1\354\260\250.py" "b/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225_1\354\260\250.py" index 4526403..80415f5 100644 --- "a/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225_1\354\260\250.py" +++ "b/11000\352\260\225\354\235\230\354\213\244\353\260\260\354\240\225_1\354\260\250.py" @@ -1,20 +1,22 @@ -import sys -input = sys.stdin.readline -from collections import deque - -N= int(input()) -times = [] -for _ in range(N): - times.append(list(map(int,input().split()))) - -class_room = 1 -overlap = 0 -last_time = deque() -for i in range(N): - if last_time[0] > times[i][0]: - overlap+=1 - if last_time < times[i][1]: - last_time = times[i][1] - if overlap > class_room: - class_room+=1 - +N = int(input()) +Si = [] +Ti = [] +check = [False] * N + +for _ in range(N): + i,j = map(int,input().split()) + Si.append(i) + Ti.append(j) + + +cnt = 0 + +while sum(check) != N: + finish = 0 + for i in range(N): + if Si[i] >= finish and check[i] == False: + finish = Ti[i] + check[i] = True + cnt+=1 + +print(cnt) \ No newline at end of file diff --git "a/11005\354\247\204\353\262\225\353\263\200\355\231\230.py" "b/11005\354\247\204\353\262\225\353\263\200\355\231\230.py" deleted file mode 100644 index 1e27e83..0000000 --- "a/11005\354\247\204\353\262\225\353\263\200\355\231\230.py" +++ /dev/null @@ -1,11 +0,0 @@ -system = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" #10진법이면 9 까지, 36진법이면 Z까지 표현된다 -N, B = map(int, input().split()) -answer = '' - -while N != 0: - # N을 B로 나눈 나머지를 마지막칸에 채움(1의자리)(36진법이면 나머지 = 36진법중 2번째 숫자) - answer += str(system[N % B]) #위치로 진법 변환 - # N을 B로 나눈 몫이 N이 된다. - N //= B - -print(answer[::-1]) \ No newline at end of file diff --git "a/11005\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" "b/11005\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" index f0ebe8b..50cf004 100644 --- "a/11005\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" +++ "b/11005\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" @@ -1,12 +1,11 @@ -system = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" #10진법이면 9 까지, 36진법이면 Z까지 표현된다 -N, B = map(int, input().split()) -answer = '' - -while N != 0: - # N을 B로 나눈 나머지를 마지막칸에 채움(1의자리)(36진법이면 나머지 = 36진법중 2번째 숫자) - answer += str(system[N % B]) #위치로 진법 변환 - # N을 B로 나눈 몫이 N이 된다. - N //= B - - +system = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" #10진법이면 9 까지, 36진법이면 Z까지 표현된다 +N, B = map(int, input().split()) +answer = '' + +while N != 0: + # N을 B로 나눈 나머지를 마지막칸에 채움(1의자리)(36진법이면 나머지 = 36진법중 2번째 숫자) + answer += str(system[N % B]) #위치로 진법 변환 + # N을 B로 나눈 몫이 N이 된다. + N //= B + print(answer[::-1]) \ No newline at end of file diff --git "a/1100\353\213\244\353\246\254\353\206\223\352\270\260.py" "b/1100\353\213\244\353\246\254\353\206\223\352\270\260.py" deleted file mode 100644 index f733008..0000000 --- "a/1100\353\213\244\353\246\254\353\206\223\352\270\260.py" +++ /dev/null @@ -1,8 +0,0 @@ -from math import factorial - -T = int(input()) -for test in range(T): - N,M = map(int,input().split()) - - answer = factorial(M)//(factorial(N)*factorial(M-N)) - print(answer) \ No newline at end of file diff --git "a/1102\353\260\234\354\240\204\354\206\214.py" "b/1102\353\260\234\354\240\204\354\206\214.py" deleted file mode 100644 index 1694f03..0000000 --- "a/1102\353\260\234\354\240\204\354\206\214.py" +++ /dev/null @@ -1,51 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def make_electic(start,cur_cnt): - queue = deque() - dp[start] = 0 - answer=float('inf') - if target_cnt==0 or cur_cnt>=target_cnt: - return 0 - elif cur_cnt==0: - return -1 - else: - queue.append([start,0]) - while target_cnt > cur_cnt: - # 한 순회에 하나씩 킬꺼임. - circle_SIZE = len(queue) - for _ in range(circle_SIZE): - now,cost = queue.popleft() - # 어떤 발전소 킬지 순회 - for i in range(N): - if not now & (1< cost + min_cost: - dp[now|(1< P: - print(0) - -while P != cnt: - for i in range(N): - if electric[i] == "Y": - for j in range(N): - if i != j and dp[j][0] == cnt : - dp[j] = [cnt+1, dp[j][1] + cost[i][j]] - print(dp) - - - # 일단 Y인것들 dp에 다 초기화. - # 0이 아닌 것들 중에서 똑같이 진행. - # cnt이용 P만큼 켜졌을때 종료. 가장 작은 dp로 채택. - - for i in range(N): - if dp[i][1] != 0: - electric[i] = "Y" - - cnt+=1 - -ans_list = [] -for i in range(N): - if dp[i][0] == P: - ans_list.append(dp[i][1]) - -if not ans_list: - print(-1) -else: - print(min(ans_list)) +import sys +input = sys.stdin.readline + +N = int(input()) +cost = [list(map(int,input().split())) for _ in range(N)] +electric = list(input()) +P = int(input()) - electric.count("Y") +dp=[[0,0]] * N +cnt = 0 + +if electric.count("Y") == 0: + print(-1) +elif electric.count("Y") > P: + print(0) + +while P != cnt: + for i in range(N): + if electric[i] == "Y": + for j in range(N): + if i != j and dp[j][0] == cnt : + dp[j] = [cnt+1, dp[j][1] + cost[i][j]] + print(dp) + + + # 일단 Y인것들 dp에 다 초기화. + # 0이 아닌 것들 중에서 똑같이 진행. + # cnt이용 P만큼 켜졌을때 종료. 가장 작은 dp로 채택. + + for i in range(N): + if dp[i][1] != 0: + electric[i] = "Y" + + cnt+=1 + +ans_list = [] +for i in range(N): + if dp[i][0] == P: + ans_list.append(dp[i][1]) + +if not ans_list: + print(-1) +else: + print(min(ans_list)) diff --git "a/11046\355\214\260\353\246\260\353\223\234\353\241\254.py" "b/11046\355\214\260\353\246\260\353\223\234\353\241\254.py" deleted file mode 100644 index a139b52..0000000 --- "a/11046\355\214\260\353\246\260\353\223\234\353\241\254.py" +++ /dev/null @@ -1,60 +0,0 @@ -import itertools as I,sys -def F(s): - n=len(s) - *a,r,p=[0]*(n+2) - for i in range(n): - if i<=r:a[i]=min(a[2*p-i],r-i) - else:a[i]=0 - while i-a[i]-1>=0 and i+a[i]+1=l)) - - - -# def manacher(s): -# A = [] -# R = -1; p = -1 -# for i in range(len(s)): -# if i <= R: A.append(min(A[2*p-i], R-i)) -# else: A.append(0) -# while i-A[i]-1 >= 0 and i+A[i]+1 < len(s) and s[i-A[i]-1] == s[i+A[i]+1]: A[i]+= 1 -# if i+A[i] > R: R = i+A[i]; p = i -# return A - -# def maxpalin(M, i): -# if i%2 == 0: return M[i]//2*2+1 -# return (M[i]+1)//2*2 - -# from sys import stdin -# input = stdin.readline -# n = int(input()) -# L = [0]*(2*n-1) -# for i, c in zip(range(n), map(int,input().split())): L[2*i] = c -# M = manacher(L) -# for TEST in range(int(input())): -# a, b = map(int,input().split()) -# print(int(maxpalin(M, a+b-2) >= b-a+1)) \ No newline at end of file diff --git "a/11048\354\235\264\353\217\231\355\225\230\352\270\260.py" "b/11048\354\235\264\353\217\231\355\225\230\352\270\260.py" deleted file mode 100644 index 0c590d4..0000000 --- "a/11048\354\235\264\353\217\231\355\225\230\352\270\260.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def BFS(i,j): - candy_max = 0 - queue = deque() - queue.append([i,j]) - visited_candy = [[-1 for _ in range(M)] for _ in range(N)] - visited_candy[i][j] = maze[i][j] - while queue: - x,y = queue.popleft() - if x==N-1 and y==M-1: - if visited_candy[x][y] > candy_max: - candy_max = visited_candy[x][y] - for nx,ny in [(x+1,y),(x,y+1),(x+1,y+1)]: - if 0<=nx visited_candy[nx][ny]: - visited_candy[nx][ny] = visited_candy[x][y] + maze[nx][ny] - queue.append([nx,ny]) - else: - return candy_max - -N,M = map(int,input().split()) -maze = [list(map(int,input().split())) for _ in range(N)] - -print(BFS(0,0)) diff --git "a/11049\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.py" "b/11049\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.py" deleted file mode 100644 index db7130a..0000000 --- "a/11049\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - - -N = int(input()) -matrix = [list(map(int, input().split())) for i in range(N)] -# dp[i][j]는 i번재 행렬에서 j번째 행렬까지 곱한 -dp = [[0] * N for _ in range(N)] -for i in range(1, N): #몇 번째 대각선? 0번째 대각선은 자기자신이므로 0유지. - for j in range(0, N-i): #대각선에서 몇 번째 열?(N*N에서 반만 채우므로 대각선 번호가 끝으로 갈수록 계산해야되는 칸도 하나씩 줄어감) - x = i+j # 차이가0인 본인대각선 모든값 0 -> 첫 대각선 계산수 N-1 -> 두번째 대각선 계산수 N-2 .... N번째 대각선 1회. - if i == 1: # x는 i번째 대각선의 j번째 열. 대각선은 한칸마다 1,1씩 증가해야하므로 j가 양쪽에 들어가 1씩 증가시켜준다.i는 표준편차의 크기. - dp[j][x] = matrix[j][0] * matrix[j][1] * matrix[x][1] # 계산 횟수는 가운데 낀 숫자는 1번 맨앞, 맨뒤숫자 1번씩 곱. - continue - - dp[j][x] = 2**32 #최댓값을 미리 넣어줌(min연산을 위해 inf값 할당해주듯) - #k는 A~E중 어디를 자르는가의 문제. ex ABC라면 AB,C / A,BC - #즉 k에따라 콤마위치가 변하고 dp[j][k]는 j부터 k행렬까지의 최소값, dp[k+1][x]는 K+1에서 x까지의 최솟값 - #뒤에 곱하는 dp는 앞행렬과 뒷행렬을 곱하는 횟수(A의 행수*자르는index인 k의 열수*마지막인자인 x의 열수) - for k in range(j, x): - dp[j][x] = min(dp[j][x], dp[j][k] + dp[k+1][x] + matrix[j][0] * matrix[k][1] * matrix[x][1]) - - -print(dp[0][N-1]) #맨 오른쪽 위 \ No newline at end of file diff --git "a/11051\354\235\264\355\225\255\352\263\204\354\210\2302.py" "b/11051\354\235\264\355\225\255\352\263\204\354\210\2302.py" deleted file mode 100644 index 0a2f4e8..0000000 --- "a/11051\354\235\264\355\225\255\352\263\204\354\210\2302.py" +++ /dev/null @@ -1,7 +0,0 @@ -import sys -input = sys.stdin.readline -from math import factorial - -N,K = map(int,input().split()) - -print((factorial(N)//(factorial(K)*factorial(N-K)))%10007) \ No newline at end of file diff --git a/11052.py b/11052.py index a066546..d55ce16 100644 --- a/11052.py +++ b/11052.py @@ -1,13 +1,12 @@ -N = int(input()) -P = [0] + list(map(int,input().split())) -dp = [0]*(N+1) - -dp[1] = P[1] - - -# dp[i]랑 dp k 전에꺼 + k개 들어있는 팩의 값 -for i in range(2,N+1): - for k in range(1,i+1): - dp[i] = max(dp[i],dp[i-k]+P[k]) - +N = int(input()) +P = [0] + list(map(int,input().split())) +dp = [0]*(N+1) + +dp[1] = P[1] + +# dp[i]랑 dp k 전에꺼 + k개 들어있는 팩의 값 +for i in range(2,N+1): + for k in range(1,i+1): + dp[i] = max(dp[i],dp[i-k]+P[k]) + print(dp[N]) \ No newline at end of file diff --git "a/11054\353\260\224\354\235\264\355\206\240\353\213\211\353\266\200\353\266\204\354\210\230\354\227\264.py" "b/11054\353\260\224\354\235\264\355\206\240\353\213\211\353\266\200\353\266\204\354\210\230\354\227\264.py" index c4c33b0..efeaf9e 100644 --- "a/11054\353\260\224\354\235\264\355\206\240\353\213\211\353\266\200\353\266\204\354\210\230\354\227\264.py" +++ "b/11054\353\260\224\354\235\264\355\206\240\353\213\211\353\266\200\353\266\204\354\210\230\354\227\264.py" @@ -1,19 +1,19 @@ -N = int(input()) -A = [0] + list(map(int, input().split())) -LDS = [1]*(N+1) -LIS = [1]*(N+1) -Bi = [] - - - -for i in range(1,N+1): - for j in range(1,i): - if A[i]>A[j] and LIS[i]<=LIS[j]: - LIS[i] = LIS[j] + 1 - if A[-i]>A[-j] and LDS[-i]<=LDS[-j]: - LDS[-i] = LDS[-j] + 1 - -for i in range(1,N+1): - Bi.append(LIS[i]+LDS[i]-1) - -print(max(Bi)) +N = int(input()) +A = [0] + list(map(int, input().split())) +LDS = [1]*(N+1) +LIS = [1]*(N+1) +Bi = [] + + + +for i in range(1,N+1): + for j in range(1,i): + if A[i]>A[j] and LIS[i]<=LIS[j]: + LIS[i] = LIS[j] + 1 + if A[-i]>A[-j] and LDS[-i]<=LDS[-j]: + LDS[-i] = LDS[-j] + 1 + +for i in range(1,N+1): + Bi.append(LIS[i]+LDS[i]-1) + +print(max(Bi)) diff --git a/11055LIS.py b/11055LIS.py index 76d5d43..0fc28bd 100644 --- a/11055LIS.py +++ b/11055LIS.py @@ -1,13 +1,13 @@ -N = int(input()) -A = [0] + list(map(int, input().split())) -dp = [0]*(N+1) - - -for i in range(1,N+1): - s = [0] - for j in range(1,i): - if A[i]>A[j]: - s.append(dp[j]) - dp[i] = max(s)+A[i] - -print(max(dp)) +N = int(input()) +A = [0] + list(map(int, input().split())) +dp = [0]*(N+1) + + +for i in range(1,N+1): + s = [0] + for j in range(1,i): + if A[i]>A[j]: + s.append(dp[j]) + dp[i] = max(s)+A[i] + +print(max(dp)) diff --git "a/11057\354\230\244\353\245\264\353\247\211\354\210\230.py" "b/11057\354\230\244\353\245\264\353\247\211\354\210\230.py" index ae085e1..848ac44 100644 --- "a/11057\354\230\244\353\245\264\353\247\211\354\210\230.py" +++ "b/11057\354\230\244\353\245\264\353\247\211\354\210\230.py" @@ -1,17 +1,15 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -matrix=[[0]*10 for _ in range(n)] -matrix[0]=[1 for i in range(10)] - -for i in range(1,n): - sum=0 - for j in range(10): - for k in range(j+1): - matrix[i][j] += matrix[i-1][k] - sum += matrix[i-1][k] -if n==1: - print(10) -else: +n = int(input()) + +matrix=[[1]*10 for _ in range(n)] + +for i in range(1,n): + sum=0 + for j in range(10): + for k in range(j+1): + matrix[i][j] += matrix[i-1][k] + sum += matrix[i-1][k] + +if n==1: + print(10) +else: print(sum%10007) \ No newline at end of file diff --git "a/11060\354\240\220\355\224\204\354\240\220\355\224\204.py" "b/11060\354\240\220\355\224\204\354\240\220\355\224\204.py" index d7bf957..a0f5721 100644 --- "a/11060\354\240\220\355\224\204\354\240\220\355\224\204.py" +++ "b/11060\354\240\220\355\224\204\354\240\220\355\224\204.py" @@ -1,26 +1,24 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -A = list(map(int,input().split())) -check = [False] * 1000 -ans = [] - -def DFS(v,cnt): - if v>=N-1: - ans.append(cnt) - return - if A[v]==0: - return - for i in range(1,A[v]+1): - if not check[v+i]: - check[v+i] = True - DFS(v+i,cnt+1) - check[v+i] = False - -check[0]=True -DFS(0,0) -if ans: - print(min(ans)) -else: - print(-1) \ No newline at end of file +import sys +input = sys.stdin.readline + +N = int(input()) +A = list(map(int,input().split())) +check = [False] * 1200 +ans = [] +v = 0 +cnt = 0 +def DFS(v,cnt): + if v>=N-1: + ans.append(cnt) + return + if A[v]==0: + return + for i in range(1,A[v]+1): + if not check[v+i] and not v+i>N-1: + check[v+i] = True + DFS(v+i,cnt+1) + check[v+i] = False + +check[0]=True +DFS(0,0) +print(min(ans) if ans else -1) \ No newline at end of file diff --git "a/11060\354\240\220\355\224\204\354\240\220\355\224\204_bfs.py" "b/11060\354\240\220\355\224\204\354\240\220\355\224\204_bfs.py" index 1650d2d..d4ea35d 100644 --- "a/11060\354\240\220\355\224\204\354\240\220\355\224\204_bfs.py" +++ "b/11060\354\240\220\355\224\204\354\240\220\355\224\204_bfs.py" @@ -1,19 +1,19 @@ -n = int(input()) -lst = list(map(int, input().split())) - -dp = [-1] * n - -def bfs(start): - q = [] - q.append(start) - dp[start] = 0 - while q: - v = q.pop(0) - jump = lst[v] - for i in range(jump, 0, -1): - if v + i < n and dp[v + i] == -1: - dp[v + i] = dp[v] + 1 - q.append(v + i) - -bfs(0) +n = int(input()) +lst = list(map(int, input().split())) + +dp = [-1] * n + +def bfs(start): + q = [] + q.append(start) + dp[start] = 0 + while q: + v = q.pop(0) + jump = lst[v] + for i in range(jump, 0, -1): + if v + i < n and dp[v + i] == -1: + dp[v + i] = dp[v] + 1 + q.append(v + i) + +bfs(0) print(dp[-1]) \ No newline at end of file diff --git "a/11060\354\240\220\355\224\204\354\240\220\355\224\204_dp.py" "b/11060\354\240\220\355\224\204\354\240\220\355\224\204_dp.py" index b1a2918..19a90b2 100644 --- "a/11060\354\240\220\355\224\204\354\240\220\355\224\204_dp.py" +++ "b/11060\354\240\220\355\224\204\354\240\220\355\224\204_dp.py" @@ -1,10 +1,10 @@ -N = int(input()) -li = list(map(int, input().split())) -dp = [N+1]*N -dp[0] = 0 -for i in range(N): - for j in range(1, li[i]+1): - if i+j >= N: - break - dp[i+j] = min(dp[i+j], dp[i]+1) +N = int(input()) +li = list(map(int, input().split())) +dp = [N+1]*N +dp[0] = 0 +for i in range(N): + for j in range(1, li[i]+1): + if i+j >= N: + break + dp[i+j] = min(dp[i+j], dp[i]+1) print(dp[N-1] if dp[N-1] != N+1 else -1) \ No newline at end of file diff --git "a/11066\355\214\214\354\235\274\355\225\251\354\271\230\352\270\260.py" "b/11066\355\214\214\354\235\274\355\225\251\354\271\230\352\270\260.py" deleted file mode 100644 index f87288b..0000000 --- "a/11066\355\214\214\354\235\274\355\225\251\354\271\230\352\270\260.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -def solve(): - N, A = int(input()), [0] + list(map(int, input().split())) - # S[i]는 1번부터 i번까지의 누적합 - S = [0 for _ in range(N+1)] - for i in range(1, N+1): - S[i] = S[i-1] + A[i] - DP = [[0 for _ in range(N+1)] for _ in range(N+1)] - - for i in range(2, N+1): # 부분 파일의 길이(몇개 합쳤냐? 두개합친거에서 3개를 구하고 4개를 구하고.(결국 앞에더할까 뒤에더할까)) - for j in range(1, N+2-i): # 시작점 - # 원래 행별 계산이면 j가 앞쪽 인자로만 들어가나 대각선이기때문에 행, 열 모두에 들어가 1씩 증가시켜준다. - # DP[1][3] -> min(DP[1][2]+DP[3][3],DP[1][1] + DP[2][3]) + S[3]-S[1](이게 범위 합에 누적합을 더하는 방식.) - # 플로이드 워셜처럼 k를 끼고 최솟값이 있냐 없냐? 어느경로로 가는게 좋냐 최솟값 택해서 누적합 더해주기. - # k는 결국 길이 범위인 i보다 작은 범위 즉 길이가 i면 부분 길이 k는 0부터 i-1까지. - DP[j][j+i-1] = min([DP[j][j+k] + DP[j+k+1][j+i-1] for k in range(i-1)]) + (S[j+i-1] - S[j-1]) - - print(DP[1][N]) - -for _ in range(int(input())): - solve() diff --git "a/1107\353\246\254\353\252\250\354\273\250.py" "b/1107\353\246\254\353\252\250\354\273\250.py" deleted file mode 100644 index 6ac4d49..0000000 --- "a/1107\353\246\254\353\252\250\354\273\250.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -def can_push_num(num): - num = list(str(num)) - for i in num: - if i in broken: - return False - return True - -target = int(input()) -m = int(input()) -broken = list(input().split()) -min_push = abs(target - 100) -for i in range(1000001): - if can_push_num(i): - min_push = min(min_push, len(str(i)) + abs(i - target)) -print(min_push) \ No newline at end of file diff --git "a/1107\353\246\254\353\252\250\354\273\250_re.py" "b/1107\353\246\254\353\252\250\354\273\250_re.py" deleted file mode 100644 index 990c031..0000000 --- "a/1107\353\246\254\353\252\250\354\273\250_re.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - - -N = int(input()) -M = int(input()) -broken = list(input().split()) -init_cnt = abs(N - 100) -for check in range(1000000): - num = list(str(check)) - for digit in num: - if digit in broken: - break - else: - init_cnt = min(init_cnt, len(str(check)) + abs(check - N)) -print(init_cnt) \ No newline at end of file diff --git "a/1108 \352\262\200\354\203\211\354\227\224\354\247\204.py" "b/1108 \352\262\200\354\203\211\354\227\224\354\247\204.py" deleted file mode 100644 index deaef34..0000000 --- "a/1108 \352\262\200\354\203\211\354\227\224\354\247\204.py" +++ /dev/null @@ -1,69 +0,0 @@ -import sys -sys.setrecursionlimit(10 ** 9) - - -def dfs1(n): - visited[n] = True - for v in forward[n]: - if not visited[v]: - dfs1(v) - stack.append(n) - - -def dfs2(n): - visited[n] = idx - for i in range(len(backward[n]) - 1, -1, -1): - v = backward[n][i] - if visited[v] == -1: - forward[v].remove(n) - dfs2(v) - elif visited[v] == idx: - forward[v].remove(n) - tmp.append(n) - - -def dfs(n): - for v in forward[n]: - if dp[v] == 1: - dp[n] += dfs(v) - else: - dp[n] += dp[v] - return dp[n] - - -N = int(sys.stdin.readline()) -forward = [[] for _ in range(N)] -backward = [[] for _ in range(N)] -data = [sys.stdin.readline().split() for _ in range(N)] -alpha = dict() -idx = N -for i in range(N): - alpha[data[i][0]] = i -for i in range(N): - for j in range(2, len(data[i])): - if data[i][j] not in alpha: - alpha[data[i][j]] = idx - idx += 1 - forward.append([]) - backward.append([]) - forward[i].append(alpha[data[i][j]]) - backward[alpha[data[i][j]]].append(i) -N = idx -visited = [False] * N -stack = [] -for i in range(N): - if not visited[i]: - dfs1(i) -visited = [-1] * N -idx = 0 -ans = [] -target = alpha[sys.stdin.readline().rstrip()] -while stack: - cur = stack.pop() - if visited[cur] == -1: - tmp = [] - dfs2(cur) - ans.append(tmp) - idx += 1 -dp = [1] * N -print(dfs(target)) \ No newline at end of file diff --git a/1110.py b/1110.py deleted file mode 100644 index 2c2fb57..0000000 --- a/1110.py +++ /dev/null @@ -1,30 +0,0 @@ - -N = int(input()) -stack = [] - -for test in range(N): - order= list(input().split()) - - if order[0]=='push': - stack.append(order[1]) - if order[0] == 'pop': - if stack: - print(stack.pop()) - else: - print(-1) - if order[0] == 'size': - print(len(stack)) - if order[0] == 'empty': - if stack: - print(0) - else: - print(1) - if order[0] == 'top': - if stack: - print(stack[-1]) - else: - print(-1) - - - - \ No newline at end of file diff --git "a/11123\354\226\221\355\225\234\353\247\210\353\246\254.py" "b/11123\354\226\221\355\225\234\353\247\210\353\246\254.py" deleted file mode 100644 index f0fe05c..0000000 --- "a/11123\354\226\221\355\225\234\353\247\210\353\246\254.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -dx = [0,0,1,-1] -dy = [1,-1,0,0] - -def BFS(i,j): - queue = deque() - queue.append([i,j]) - while queue: - x,y = queue.popleft() - for i in range(4): - nx=x+dx[i] - ny=y+dy[i] - if 0<=nx temp[j + blocks[i]] : # 쌓은 블럭이 그 전 높이차이 최대 탑 높이보다 클 경우 - temp[j + blocks[i]] = dp[j] + blocks[i] - - if j > blocks[i] : - if dp[j] > temp[j - blocks[i]] : - temp[j - blocks[i]] = dp[j] - - elif j < blocks[i] : - if blocks[i] + dp[j] - j > temp[blocks[i] - j]: - temp[blocks[i] - j] = blocks[i] + dp[j] - j - - else : - if temp[0] < dp[j] : - temp[0] = dp[j] - if ans < dp[j] : ans = dp[j] - dp = temp[:] - -print(ans) - - -import sys -input = sys.stdin.readline - -n = int(input()) -block = list(map(int, input().split())) - -if n == 1: - print(-1) - quit() -height_sum = sum(block) -dp = [[-1] * height_sum for _ in range(len(block))] -dp[0][0] = 0 -dp[0][block[0]] = block[0] -for i in range(len(block) - 1): - for j in range(height_sum//2 + 1): - # i+1번째 블록을 사용하지 않는 경우 - if dp[i][j] != -1: - dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]) - # 더 높은 탑에 쌓는 경우 - if j + block[i + 1] < height_sum: - dp[i + 1][j + block[i + 1]] = max(dp[i + 1][j + block[i + 1]], dp[i][j] + block[i + 1]) - # 더 낮은 탑에 쌓는 경우 case1. block_i <= j case2. block_i > j - if block[i + 1] <= j: - dp[i + 1][j - block[i + 1]] = max(dp[i + 1][j - block[i + 1]], dp[i][j]) - else: - dp[i + 1][block[i + 1] - j] = max(dp[i + 1][block[i + 1] - j], dp[i][j] + block[i + 1] - j) -if dp[-1][0] == 0: - print(-1) -else: - print(dp[-1][0]) - - diff --git "a/11265 \353\201\235\353\202\230\354\247\200\354\225\212\353\212\224 \355\214\214\355\213\260.py" "b/11265 \353\201\235\353\202\230\354\247\200\354\225\212\353\212\224 \355\214\214\355\213\260.py" deleted file mode 100644 index cce6f83..0000000 --- "a/11265 \353\201\235\353\202\230\354\247\200\354\225\212\353\212\224 \355\214\214\355\213\260.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int,input().split()) -parties = [list(map(int,input().split())) for _ in range(N)] -for k in range(N): - for i in range(N): - for j in range(N): - if parties[i][j] > parties[i][k] + parties[k][j]: - parties[i][j] = parties[i][k] + parties[k][j] -for _ in range(M): - A, B, C = map(int,input().split()) - if parties[A-1][B-1] <= C: - print('Enjoy other party') - else: - print('Stay here') diff --git "a/11279\354\265\234\353\214\200\355\236\231.py" "b/11279\354\265\234\353\214\200\355\236\231.py" deleted file mode 100644 index 0b13ca9..0000000 --- "a/11279\354\265\234\353\214\200\355\236\231.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -from heapq import heappush,heappop - -queue = [] -for _ in range(int(input())): - x = int(input()) - if not x: - try: - print(heappop(queue)[1]) - except: - print(0) - else: - heappush(queue,(-x,x)) \ No newline at end of file diff --git a/11281 2-sat-4.py b/11281 2-sat-4.py deleted file mode 100644 index 415cb9f..0000000 --- a/11281 2-sat-4.py +++ /dev/null @@ -1,267 +0,0 @@ -# 타잔 -import sys -sys.setrecursionlimit(10 ** 5) - -N, M = map(int, sys.stdin.readline().split()) -graph = [[] for _ in range(2 * N + 1)] - -for _ in range(M): - a, b = map(int, sys.stdin.readline().split()) - graph[-a].append(b) - graph[-b].append(a) - -scc_num = 1 -idx = 1 -stack = [] -scc_idx = [0] * (2 * N + 1) -check = [0] * (2 * N + 1) -visit = [0] * (2 * N + 1) - -def SCC(node): - global idx, scc_num - visit[node] = idx - root = idx - idx += 1 - stack.append(node) - - for nxt in graph[node]: - if not visit[nxt]: - root = min(root, SCC(nxt)) - elif not check[nxt]: - root = min(root, visit[nxt]) - - if root == visit[node]: - while stack: - top = stack.pop() - check[top] = 1 - scc_idx[top] = scc_num - if node == top: - break - - scc_num += 1 - - return root - -for i in range(1, 2 * N + 1): - if not visit[i]: - SCC(i) - -result = [0] * N -for i in range(1, N + 1): - if scc_idx[i] == scc_idx[-i]: - print(0) - break - if scc_idx[i] < scc_idx[-i]: - result[i - 1] = 1 -else: - print(1) - print(*result) - - -# 2 -import sys - - -input = sys.stdin.readline - -stack: list[int] = [] -edge_list: list[list[int]] - - -def initialize(length: int) -> None: - global _id, scc_id, finished, id_list, sccid_list, edge_list - _id = 0 - scc_id = 1 - finished = [False for _ in range(length)] - id_list = [-1 for _ in range(length)] - sccid_list = [-1 for _ in range(length)] - edge_list = [[] for _ in range(length)] - - -def dfs(x: int) -> int: - global _id, scc_id - _id += 1 - id_list[x] = _id - stack.append(x) - - parent: int = id_list[x] - for nx in edge_list[x]: - if id_list[nx] == -1: - parent = min(parent, dfs(nx)) - elif not finished[nx]: - parent = min(parent, id_list[nx]) - - if parent == id_list[x]: - while True: - top = stack.pop() - sccid_list[top] = scc_id - finished[top] = True - if top == x: - break - scc_id += 1 - - return parent - - -def check(n: int) -> bool: - for x in range(1, n + 1): - if sccid_list[x] == sccid_list[-x]: - return False - return True - - -def print_answer(n: int) -> None: - can_true = check(n) - print(int(can_true)) - if can_true: - for x in range(1, n + 1): - print(int(sccid_list[x] < sccid_list[-x]), end=" ") - - -def main() -> None: - n, m = map(int, input().split()) - - initialize(2 * n + 1) - - for _ in range(m): - x, y = map(int, input().split()) - edge_list[-x].append(y) - edge_list[-y].append(x) - - for x in range(1, 2 * n + 1): - if id_list[x] == -1: - dfs(x) - - print_answer(n) - - -if __name__ == "__main__": - sys.setrecursionlimit(20000) - main() - - -# 3 -from sys import stdin, setrecursionlimit as SRL -input = stdin.readline; SRL(123123) -MIS = lambda: map(int,input().split()) - -def SCC(adj): - def dfs(count, v): - pre[v] = count; count+= 1 - S.append(v); P.append(v) - for w in adj[v]: - if pre[w] == -1: count = dfs(count, w) - elif not scced[w]: - while P and pre[P[-1]] > pre[w]: P.pop() - if not P or P[-1] != v: return count - comp = [] - while S: - w = S.pop(); scced[w] = True; comp.append(w) - if w == v: break - P.pop(); sccs.append(comp) - return count - n, count = len(adj), 0 - pre, scced = [-1]*n, [False]*n; S, P, sccs = [], [], [] - for v in range(n//2): - if pre[v+1] == -1: count = dfs(count, v+1) - if pre[-v-1] == -1: count = dfs(count, -v-1) - scx = [-1]*n - for i in range(len(sccs)): - for x in sccs[i]: scx[x] = i+1 - return scx, sccs - -def TwoSAT(n, cnf): - adj = [[] for i in range(2*n+1)] - for a, b in cnf: adj[-a].append(b); adj[-b].append(a) - scx, res = SCC(adj) - for i in range(1, n+1): - if scx[i] == scx[-i]: return False - assign = [-1]*(n+1) - for i in range(len(res)-1,-1,-1): - for var in res[i]: - if assign[abs(var)] == -1: assign[abs(var)] = var<0 - return assign - -n, m = MIS() -cnf = [] -for i in range(m): cnf.append(tuple(MIS())) -asg = TwoSAT(n, cnf) -if asg == False: print(0) -else: - print(1) - print(*map(int, asg[1:])) - - -# 4 -import sys -rd, wt = sys.stdin.readline, sys.stdout.write -sys.setrecursionlimit(10**6) - -def scan() : return map(int, rd().split()) - -def F(node) : return 2 * node if node > 0 else 1 - 2 * node - -N, M = scan() - -adj = [[] for _ in range(2 * N + 2)] -disc = [-1 for _ in range(2 * N + 2)] -scc = [-1 for _ in range(2 * N + 2)] -ans = [-1 for _ in range(N + 1)] -info, st, num, grp = [], [], 0, 0 - -def DFS(pre) : - - global num, grp - - disc[pre] = ret = num - num += 1 - - st.append(pre) - - for seq in adj[pre] : - if disc[seq] < 0 : ret = min(ret, DFS(seq)) - elif scc[seq] < 0 : ret = min(ret, disc[seq]) - - if ret == disc[pre] : - - tmp = [] - - while True : - - node = st.pop() - - scc[node] = grp - tmp.append(node) - - if node == pre : break - - info.append(tmp) - grp += 1 - - return ret - -for _ in range(M) : - A, B = scan() - adj[F(-A)].append(F(B)) - adj[F(-B)].append(F(A)) - -for i in range(2, 2 * N + 2) : - if disc[i] < 0 : DFS(i) - -for i in range(1, N + 1) : - if scc[2 * i + 1] == scc[2 * i] : - wt('0') - sys.exit() - -while info : - - arr = info.pop() - - while arr : - - num = arr.pop() - - if ans[num // 2] < 0 : ans[num // 2] = num % 2 - -wt('1\n') -for i in range(N) : wt('%d ' %ans[i + 1]) \ No newline at end of file diff --git "a/11286 \354\240\210\353\214\223\352\260\222 \355\236\231.py" "b/11286 \354\240\210\353\214\223\352\260\222 \355\236\231.py" deleted file mode 100644 index a5d1e44..0000000 --- "a/11286 \354\240\210\353\214\223\352\260\222 \355\236\231.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -N = int(input()) -arr = [] -for _ in range(N): - x = int(input()) - if x: - heappush(arr,(abs(x),x)) - continue - try: - print(heappop(arr)[1]) - except: - print(0) diff --git "a/11375\354\227\264\355\230\210\352\260\225\355\230\270_\354\235\264\353\266\204\353\247\244\354\271\255.py" "b/11375\354\227\264\355\230\210\352\260\225\355\230\270_\354\235\264\353\266\204\353\247\244\354\271\255.py" deleted file mode 100644 index 0457330..0000000 --- "a/11375\354\227\264\355\230\210\352\260\225\355\230\270_\354\235\264\353\266\204\353\247\244\354\271\255.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input=sys.stdin.readline -N,M=map(int,input().split()) -flow=[''] -for i in range(N): - flow.append(list(map(int,input().split()))[1:]) - -rev=[0]*1005 -def dfs(n): - if visited[n]: return 0 - visited[n]=1 - for i in flow[n]: - if not rev[i] or dfs(rev[i]): - rev[i]=n - return 1 - -ret=0 -for i in range(N): - visited=[0]*1005 - if dfs(1+i):ret+=1 -print(ret) \ No newline at end of file diff --git "a/11376\354\227\264\355\230\210\352\260\225\355\230\2702.py" "b/11376\354\227\264\355\230\210\352\260\225\355\230\2702.py" deleted file mode 100644 index 9a04310..0000000 --- "a/11376\354\227\264\355\230\210\352\260\225\355\230\2702.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline -n, m = map(int, input().split()) -s = [[] for i in range(n + 1)] -d = [0 for i in range(m + 1)] -cnt = 0 -def dfs(start): - if visit[start] == 1: - return 0 - visit[start] = 1 - for i in s[start]: - if d[i] == 0 or dfs(d[i]): - d[i] = start - return 1 - return 0 -for i in range(1, n + 1): - a = list(map(int, input().split())) - for j in a[1:]: - s[i].append(j) -for j in range(2): - for i in range(1, n + 1): - visit = [0 for _ in range(n + 1)] - if dfs(i): - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/11377\354\227\264\355\230\210\352\260\225\355\230\2703.py" "b/11377\354\227\264\355\230\210\352\260\225\355\230\2703.py" deleted file mode 100644 index 7cab3cb..0000000 --- "a/11377\354\227\264\355\230\210\352\260\225\355\230\2703.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline -n, m, k = map(int, input().split()) -s = [[] for i in range(n + 1)] -d = [0 for i in range(m + 1)] -cnt = 0 -def dfs(start): - if visit[start] == 1: - return 0 - visit[start] = 1 - for i in s[start]: - if d[i] == 0 or dfs(d[i]): - d[i] = start - return 1 - return 0 -for i in range(1, n + 1): - a = list(map(int, input().split())) - for j in a[1:]: - s[i].append(j) -for i in range(1, n + 1): - visit = [0 for i in range(n + 1)] - if dfs(i): - cnt += 1 -for i in range(1, n + 1): - visit = [0 for i in range(n + 1)] - if dfs(i): - cnt += 1 - k -= 1 - if k == 0: - break -print(cnt) \ No newline at end of file diff --git "a/11401\355\216\230\353\245\264\353\247\210\354\235\230\354\206\214\354\240\225\353\246\254.py" "b/11401\355\216\230\353\245\264\353\247\210\354\235\230\354\206\214\354\240\225\353\246\254.py" deleted file mode 100644 index ab2a4fd..0000000 --- "a/11401\355\216\230\353\245\264\353\247\210\354\235\230\354\206\214\354\240\225\353\246\254.py" +++ /dev/null @@ -1,19 +0,0 @@ -def pow(n, k, m): - if k == 1: - return n - pow_half = pow(n, k//2, m) - if k % 2 == 0: - return (pow_half ** 2) % m - else: - return (pow_half ** 2 * n) % m - -n, k = map(int, input().split()) - -factorial = [1] * (n+1) -for idx in range(2, n+1): - factorial[idx] = (factorial[idx-1] * idx) % 1000000007 - -def inverse(n): - return pow(factorial[n], 1000000005, 1000000007) - -print(factorial[n] * inverse(n-k) * inverse(k) % 1000000007) \ No newline at end of file diff --git "a/11403 \352\262\275\353\241\234\354\260\276\352\270\260.py" "b/11403 \352\262\275\353\241\234\354\260\276\352\270\260.py" deleted file mode 100644 index 7c66d11..0000000 --- "a/11403 \352\262\275\353\241\234\354\260\276\352\270\260.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -def dfs(v): - for i in range(n): - if visited[i] == 0 and matrix[v][i] == 1: - visited[i] = 1 - dfs(i) - -n = int(input()) -matrix = [list(map(int, input().split())) for _ in range(n)] -for i in range(n): - visited = [0 for _ in range(n)] - dfs(i) - for j in range(n): - print(1 if visited[j] == 1 else 0, end=' ') - print() - \ No newline at end of file diff --git a/11404floid.py b/11404floid.py deleted file mode 100644 index 813d546..0000000 --- a/11404floid.py +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -m = int(input()) -maps = [[float('inf') for _ in range(n)] for _ in range(n)] -for _ in range(m): - a,b,c = map(int,input().split()) - maps[a-1][b-1]=min(maps[a-1][b-1],c) - -for i in range(n): - maps[i][i]=0 - -for k in range(n): - for i in range(n): - for j in range(n): - if maps[i][j] > maps[i][k]+maps[k][j]: - maps[i][j] = maps[i][k]+maps[k][j] - -for i in range(n): - for j in range(n): - if maps[i][j]==float('inf'): - maps[i][j]=0 - -for map in maps: - print(*map) \ No newline at end of file diff --git "a/11404\355\224\214\353\241\234\354\235\264\353\223\234.py" "b/11404\355\224\214\353\241\234\354\235\264\353\223\234.py" deleted file mode 100644 index 518eaef..0000000 --- "a/11404\355\224\214\353\241\234\354\235\264\353\223\234.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def floid_washal(): - dp_dists = [[float('inf') for _ in range(n+1)] for _ in range(n+1)] - for cur_node in graph: - for next_node,dist in graph[cur_node]: - if dp_dists[cur_node][next_node] > dist: - dp_dists[cur_node][next_node] = dist - dp_dists[cur_node][cur_node] = 0 - - for k in range(1,n+1): - for i in range(1,n+1): - for j in range(1,n+1): - dp_dists[i][j] = min(dp_dists[i][j],dp_dists[i][k]+dp_dists[k][j]) - - for i in range(1,n+1): - for j in range(1,n+1): - if dp_dists[i][j] == float('inf'): - print(0, end=' ') - else: - print(dp_dists[i][j], end=' ') - print() - -n = int(input()) -m = int(input()) -graph = {i:[] for i in range(1,n+1)} -for _ in range(m): - a,b,c = map(int,input().split()) - graph[a].append([b,c]) - -floid_washal() \ No newline at end of file diff --git "a/11408 \354\227\264\355\230\210\352\260\225\355\230\2705.py" "b/11408 \354\227\264\355\230\210\352\260\225\355\230\2705.py" deleted file mode 100644 index a24109d..0000000 --- "a/11408 \354\227\264\355\230\210\352\260\225\355\230\2705.py" +++ /dev/null @@ -1,270 +0,0 @@ -import sys -from collections import deque - -n, m = map(int, sys.stdin.readline().split()) -board = [[0] * (m + 1) for _ in range(n + 1)] -graph = [[] for _ in range(n + m + 2)] - -for i in range(1, n + 1): - data = list(map(int, sys.stdin.readline().split())) - for j in range(data[0]): - board[i][data[2 * j + 1]] = data[2 * j + 2] - graph[i].append(data[2 * j + 1] + n) - -for i in range(1, n + 1): - graph[0].append(i) - -for j in range(n + 1, n + m + 1): - graph[j].append(n + m + 1) - -ans = 0 -weight = 0 -while True: - res = [float('inf')] * (n + m + 2) - res[0] = 0 - - prev = [-1] * (n + m + 2) - visit = [0] * (n + m + 2) - queue = deque([0]) - - while queue: - cur = queue.popleft() - visit[cur] = 0 - - for nxt in graph[cur]: - if 0 < cur < nxt < n + m + 1: - cost = board[cur][nxt - n] - elif 0 < nxt < cur < n + m + 1: - cost = -board[nxt][cur - n] - else: - cost = 0 - - if res[nxt] > res[cur] + cost: - res[nxt] = res[cur] + cost - prev[nxt] = cur - - if not visit[nxt]: - queue.append(nxt) - visit[nxt] = 1 - - if res[-1] == float('inf'): - break - - ans += 1 - nxt = n + m + 1 - while nxt: - cur = prev[nxt] - - if 0 < cur < nxt < n + m + 1: - weight += board[cur][nxt - n] - elif 0 < nxt < cur < n + m + 1: - weight -= board[nxt][cur - n] - - graph[cur].remove(nxt) - graph[nxt].append(cur) - nxt = cur - -print(ans) -print(weight) - -# 2 -import sys -input = sys.stdin.readline -INF = 9876543210 - -def MCMF(source, sink): - answer = [0, 0] # 최소 비용, 최대 유량 - while True: - path, dist = [-1]*v, [INF]*v - inQueue, queue = [0]*v, [source] # 다음에 방문할 정점들 - dist[source], inQueue[source] = 0, 1 - while queue: - present = queue[0] # 현재 정점 - del queue[0] - inQueue[present] = False - for _next in adj[present]: - # 최소 비용이고, 최대 유량일 경우 - if dist[_next] > dist[present] + cost[present][_next] and capacity[present][_next] - flow[present][_next] > 0: - dist[_next], path[_next] = dist[present] + cost[present][_next], present - if not inQueue[_next]: - queue.append(_next) - inQueue[_next] = 1 - if path[sink] == -1: # 가능한 모든 경로를 찾았을 경우 - break - # 현재 경로에서의 최소 유량 찾음 - flowRate = INF - present = sink - while present != source: - previous = path[present] - flowRate = min(flowRate, capacity[previous][present] - flow[previous][present]) - present = path[present] - # 유량 흘림 - present = sink - while present != source: - previous = path[present] - answer[0] += flowRate*cost[previous][present] # 총 비용이 각 간선 비용만큼 증가 - flow[previous][present] += flowRate - flow[present][previous] -= flowRate # 음의 유량 - present = path[present] - answer[1] += flowRate - return answer - -MAX_N, MAX_M = 400, 400 # 최대 직원의 수, 최대 일의 수 -n, m = map(int, input().split()) # 직원의 수, 일의 수 -v = MAX_N + MAX_M + 2 # 정점의 수 (최대 직원 수 + 최대 일의 수 + source + sink) -capacity = [[0]*v for _ in range(v)] # 용량 -flow = [[0]*v for _ in range(v)] # 유량 -cost = [[0]*v for _ in range(v)] # 비용 -adj = [[] for _ in range(v)] # 연결된 정점 (source + 직원 + 일 + sink) -for _n in range(1, n+1): # 직원과 일 매칭 - info = list(map(int, input().split())) - for i in range(1, len(info), 2): - _m = MAX_N+info[i] - adj[_n].append(_m) - adj[_m].append(_n) - capacity[_n][_m] = 1 - cost[_n][_m] = info[i+1] # 순방향 간선의 비용 - cost[_m][_n] = -info[i+1] # 역방향 간선의 비용 -for _n in range(1, n+1): # source와 직원 매칭 - adj[0].append(_n) - adj[_n].append(0) - capacity[0][_n] = 1 -for _m in range(MAX_N+1, MAX_N+m+1): # 일과 sink 매칭 - adj[_m].append(v-1) - adj[v-1].append(_m) - capacity[_m][v-1] = 1 -min_cost, max_flow = MCMF(0, v-1) -print(max_flow) -print(min_cost) - -# 3 -# 1 아니면 0 임으로 따로 허용량 표시 안해도 되긴 할 듯 -> 속도 향상 될수도 - -import sys -input = sys.stdin.readline - -n,m = list(map(int,input().strip().split())) -# 0 n n+m n+m+1 -start = 0 -destination = n+m+1 -graph = dict([(i,{}) for i in range(n+m+2)]) - -for i in range(n): - read = list(map(int,input().strip().split()))[1:] - for j in range(len(read)//2): - index = j*2 - graph[i+1][read[index]+n] = read[index+1] - -for i in range(1,n+1): - graph[0][i] = 0 - -for i in range(n+1,destination): - graph[i][destination] = 0 - -def search(): - queue = {} - new_queue = {start:start} - distance[start] = 0 - while len(new_queue): - queue = new_queue - new_queue = {} - for k in list(queue.keys()): - node = queue.pop(k) - use_graph = graph[node] - for g in use_graph: - new_d = distance[node] + use_graph[g] - if distance[g] > new_d: - distance[g] = new_d - parent[g] = node - new_queue[g] = g - - -sum_v = 0 -while True: - parent = [None for _ in range(m+n+2)] - distance = [99999 for _ in range(m+n+2)] - search() - end = destination - if parent[destination] == None: - break - while True: - pa = parent[end] - if pa == None: - break - w = graph[pa][end] - sum_v+=w - del graph[pa][end] - graph[end][pa] = -w - end = pa - - -print(len(graph[destination])) -print(sum_v) - - -# 5 비효율 -import sys -from collections import deque -input = sys.stdin.readline -INF = 1e9 -n, m = map(int, input().split()) -maxv = n+m+2 -S = maxv-2 -E = maxv-1 -c = [[0 for _ in range(maxv)] for _ in range(maxv)] -d = [[0 for _ in range(maxv)] for _ in range(maxv)] -f = [[0 for _ in range(maxv)] for _ in range(maxv)] -adj = [[] for _ in range(maxv)] -for i in range(m): - c[i+n][E] = 1 - adj[i+n].append(E) - adj[E].append(i+n) -for i in range(n): - c[S][i] = 1 - adj[S].append(i) - adj[i].append(S) - tmp = list(map(int, input().split())) - idx = 1 - while idx < tmp[0]*2: - j, val = tmp[idx], tmp[idx+1] - d[i][n+j-1], d[n+j-1][i] = val, -val - c[i][n+j-1] = 1 - adj[i].append(n+j-1) - adj[n+j-1].append(i) - idx += 2 -res = 0 -cnt = 0 -while True: - prev = [-1 for _ in range(maxv)] - dist = [INF for _ in range(maxv)] - atQ = [False for _ in range(maxv)] - q = deque() - dist[S] = 0 - atQ[S] = True - q.append(S) - while q: - cur = q.popleft() - atQ[cur] = False - for nxt in adj[cur]: - if c[cur][nxt] - f[cur][nxt] > 0 and dist[nxt] > dist[cur] + d[cur][nxt]: - dist[nxt] = dist[cur]+d[cur][nxt] - prev[nxt] = cur - if not atQ[nxt]: - q.append(nxt) - atQ[nxt] = True - if prev[E] == -1: - break - flow = INF - i = E - while i != S: - flow = min(flow, c[prev[i]][i]-f[prev[i]][i]) - i = prev[i] - i = E - while i != S: - res += flow*d[prev[i]][i] - f[prev[i]][i] += flow - f[i][prev[i]] -= flow - i = prev[i] - cnt += 1 -print(cnt) -print(res) diff --git "a/1142\355\224\274\354\236\220.py" "b/1142\355\224\274\354\236\220.py" deleted file mode 100644 index 5a5259f..0000000 --- "a/1142\355\224\274\354\236\220.py" +++ /dev/null @@ -1,26 +0,0 @@ - - -N = int(input()) -maps = [] -for _ in range(N): - maps.append(list(map(int,input().split()))) - - - - -cnt=0 -for i in range(N-1): - for j in range(i+1,N): - x1,y1 = maps[i] - x2,y2 = maps[j] - try: - k = y1 - ((y2-y1)/(x2-x1))*x1 - except: - if x1==0 and x2==0: - cnt+=1 - continue - else: - if k==0: - cnt+=1 - -print(cnt) \ No newline at end of file diff --git a/11437LCA.py b/11437LCA.py index 2c815c4..2047cb6 100644 --- a/11437LCA.py +++ b/11437LCA.py @@ -1,57 +1,57 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(100000) - - -def dfs(v, d): - depth[v] = d - visited[v] = True - - for child in tree[v]: - if not visited[child]: - parent[child][0] = v - dfs(child, d+1) - -def find_parent(): - for i in range(1, 21): - for j in range(1, V+1): - parent[j][i] = parent[parent[j][i-1]][i-1] - -def lca(a, b): - if depth[a] > depth[b]: - a, b = b, a - for i in range(20, -1, -1): - if depth[b] - depth[a] >= (1< depth[b]: + a, b = b, a + for i in range(20, -1, -1): + if depth[b] - depth[a] >= (1< depth[b]: - a,b = b,a - # 더 깊은 b에 대해 동일해질때까지 올린다. - for i in range(LOG-1,-1,-1): - if depth[b] - depth[a] >= (1< LIS[-1]: - LIS.append(card) - else: - LIS[bisect_left(LIS,card)] = card -print(len(LIS)-1) \ No newline at end of file diff --git a/1157.py b/1157.py deleted file mode 100644 index 9c0c90d..0000000 --- a/1157.py +++ /dev/null @@ -1,6 +0,0 @@ -sentence = list(input().strip()) - -if len(sentence)==0: - print(0) -else: - print(sentence.count(" ")+1) \ No newline at end of file diff --git a/11576_baseconversion.py b/11576_baseconversion.py index d1566c1..7f05561 100644 --- a/11576_baseconversion.py +++ b/11576_baseconversion.py @@ -1,13 +1,13 @@ -x, y = map(int, input().split()) -z = int(input()) -a = list(map(int, input().split())) -ten = 0 -answer =[] -for i in range(z): - ten += a[-1] * (x**i) - a.pop(-1) -while ten !=0: - answer.append(str(ten % y)) - ten = ten // y - +x, y = map(int, input().split()) +z = int(input()) +a = list(map(int, input().split())) +ten = 0 +answer =[] +for i in range(z): + ten += a[-1] * (x**i) + a.pop(-1) +while ten !=0: + answer.append(str(ten % y)) + ten = ten // y + print(' '.join(answer[::-1])) \ No newline at end of file diff --git "a/1158.\354\232\224\354\204\270\355\221\270\354\212\244\353\254\270\354\240\234.py" "b/1158.\354\232\224\354\204\270\355\221\270\354\212\244\353\254\270\354\240\234.py" deleted file mode 100644 index a7ffd33..0000000 --- "a/1158.\354\232\224\354\204\270\355\221\270\354\212\244\353\254\270\354\240\234.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) -nums = [i for i in range(1, N + 1)] - -result = [] -idx = 0 -for _ in range(N): - idx += K-1 - if len(nums) <= idx: - idx %= len(nums) - result.append(nums[idx]) - nums = nums[:idx]+nums[idx+1:] - -ended=[] -ended.append(result.pop()) -ended.append(">") -if N==1: - print("<1>") -else: - print("<", end='') - print(*result,sep=', ',end = ', ') - print(*ended,sep='') diff --git "a/11653\354\206\214\354\235\270\354\210\230\353\266\204\355\225\264.py" "b/11653\354\206\214\354\235\270\354\210\230\353\266\204\355\225\264.py" index 9d25a7b..d616631 100644 --- "a/11653\354\206\214\354\235\270\354\210\230\353\266\204\355\225\264.py" +++ "b/11653\354\206\214\354\235\270\354\210\230\353\266\204\355\225\264.py" @@ -1,8 +1,8 @@ -N = int(input()) - -while N>1: - for i in range(2,N+1): - if N%i==0: - print(i) - N = int(N/i) - break +N = int(input()) + +while N>1: + for i in range(2,N+1): + if N%i==0: + print(i) + N = int(N/i) + break diff --git "a/11656\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" "b/11656\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" index a3575fb..ad157fd 100644 --- "a/11656\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" +++ "b/11656\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" @@ -1,9 +1,9 @@ -S = str(input()) -S_list = [] - -for _ in S: - S_list.append(S) - S = S[1:] - -for i in sorted(S_list): +S = str(input()) +S_list = [] + +for _ in S: + S_list.append(S) + S = S[1:] + +for i in sorted(S_list): print(i) \ No newline at end of file diff --git "a/11657\355\203\200\354\236\204\353\250\270\354\213\240.py" "b/11657\355\203\200\354\236\204\353\250\270\354\213\240.py" deleted file mode 100644 index ff5c5da..0000000 --- "a/11657\355\203\200\354\236\204\353\250\270\354\213\240.py" +++ /dev/null @@ -1,43 +0,0 @@ -import sys -input = sys.stdin.readline - -def bellman_ford(start): - dp_dists[start] = 0 - -# 모든 정점 수만큼 검사 - for i in range(N): - # 매 정점마다 모든 간선 검사(그 점에서 타 점까지) - for cur_node in graph: - for next_node, dist in graph[cur_node]: - # 방문 안했거나 다음점보다 지금 가는 경로가 더 짧으면 갱신 - if dp_dists[cur_node] !=float('inf') and dp_dists[next_node] > dp_dists[cur_node]+dist: - dp_dists[next_node] = dp_dists[cur_node]+dist - # N-1번째 순회일때 최단거리 갱신이 된다면 음의 사이클 존재. - if i==N-1: - return True - - return False - - - - -N,M = map(int,input().split()) -graph = {i:[] for i in range(1,N+1)} -dp_dists = [float('inf') for _ in range(N+1)] - -for _ in range(M): - a,b,c = map(int,input().split()) - graph[a].append([b,c]) - - -negative_cycle = bellman_ford(1) - -if negative_cycle: - print(-1) -else: - # 1번말고 다른 노드들로 가는dp값 출력. - for i in range(2,N+1): - if dp_dists[i] == float('inf'): - print(-1) - else: - print(dp_dists[i]) diff --git "a/11659 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 4.py" "b/11659 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 4.py" deleted file mode 100644 index dc9a8f3..0000000 --- "a/11659 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 4.py" +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -arr = list(map(int, input().split())) -dp = [0] -for i in range(N): - dp.append(dp[i]+arr[i]) -for _ in range(M): - i, j = map(int, input().split()) - print(dp[j] - dp[i-1]) diff --git "a/1165RCT\354\225\224\355\230\270\355\231\224.py" "b/1165RCT\354\225\224\355\230\270\355\231\224.py" index 253ee7e..1b33f87 100644 --- "a/1165RCT\354\225\224\355\230\270\355\231\224.py" +++ "b/1165RCT\354\225\224\355\230\270\355\231\224.py" @@ -1,6 +1,6 @@ -num = list(input().split()) - -A = int(num[0] + num[1]) -B = int(num[2] + num[3]) - -print(A+B) +num = list(input().split()) + +A = int(num[0] + num[1]) +B = int(num[2] + num[3]) + +print(A+B) diff --git "a/11660\352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\2605.py" "b/11660\352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\2605.py" deleted file mode 100644 index 7993815..0000000 --- "a/11660\352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\2605.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M = map(int,input().split()) - -matrix = [list(map(int,input().split())) for _ in range(N)] -dp = [[0]*N for _ in range(N)] - - - - -for i in range(N): - for j in range(N): - dp[0][0] = matrix[0][0] - if i==0 and j>0: - dp[i][j] = dp[i][j-1]+matrix[i][j] - elif j==0 and i>0: - dp[i][j] = dp[i-1][j]+matrix[i][j] - else: - dp[i][j] = dp[i-1][j]+dp[i][j-1] + matrix[i][j] - dp[i-1][j-1] - - -for _ in range(M): - x1,y1,x2,y2 = map(int,input().split()) - if x1==1 and y1 !=1: - answer = dp[x2-1][y2-1] - dp[x2-1][y1-2] - elif y1==1 and x1 !=1: - answer = dp[x2-1][y2-1] - dp[x1-2][y2-1] - elif x1==1 and x1==1: - answer = dp[x2-1][y2-1] - else: - answer = dp[x2-1][y2-1] - dp[x2-1][y1-2] - dp[x1-2][y2-1] + dp[x1-2][y1-2] - print(answer) \ No newline at end of file diff --git "a/1167\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" "b/1167\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" index df7962a..ca4397d 100644 --- "a/1167\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" +++ "b/1167\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" @@ -1,37 +1,37 @@ -import sys -from collections import deque,defaultdict - -input = sys.stdin.readline -V = int(input()) -graph = defaultdict(list) - -for _ in range(V): - c = list(map(int, input().split())) - for e in range(1, len(c) - 2, 2): - graph[c[0]].append(c[e:e + 2]) - - -def bfs(v): - visited = [-1] * (V + 1) - queue = deque() - queue.append(v) - visited[v] = 0 - max_node = [0, 0] - - while queue: - t = queue.popleft() - for e, w in graph[t]: - if visited[e] == -1: - visited[e] = visited[t] + w - queue.append(e) - if max_node[0] < visited[e]: - max_node = visited[e], e - - return max_node - - -dist, node = bfs(1) -dist, node = bfs(node) -print(dist) - +import sys +from collections import deque,defaultdict + +input = sys.stdin.readline +V = int(input()) +graph = defaultdict(list) + +for _ in range(V): + c = list(map(int, input().split())) + for e in range(1, len(c) - 2, 2): + graph[c[0]].append(c[e:e + 2]) + + +def bfs(v): + visited = [-1] * (V + 1) + queue = deque() + queue.append(v) + visited[v] = 0 + max_node = [0, 0] + + while queue: + t = queue.popleft() + for e, w in graph[t]: + if visited[e] == -1: + visited[e] = visited[t] + w + queue.append(e) + if max_node[0] < visited[e]: + max_node = visited[e], e + + return max_node + + +dist, node = bfs(1) +dist, node = bfs(node) +print(dist) + # 트리의 지름(그래프 간 가장 먼 노드 사이의 거리) = 아무 노드에서 최장 노드, 그 노드에서 다시한번 최장노드 = 지름 \ No newline at end of file diff --git a/11689GCD(n,k)=1.py b/11689GCD(n,k)=1.py deleted file mode 100644 index db3b66a..0000000 --- a/11689GCD(n,k)=1.py +++ /dev/null @@ -1,16 +0,0 @@ -# n의 소인수를 p1,p2..라 할때 -# 서로소의 갯수는 = n*(1-1/p1)*(1-1/p2)*...*(1-1/pk) - -n = int(input()) -result = n -# n 으로 소인수 분해 하기. -for i in range(2, round(n ** 0.5) + 1): - if n % i == 0: - while n % i == 0: - n //= i - # 소인수 하나당 공식 곱해주기 - result *= 1 - (1 / i) -# 남은게 1이상이면 그 수만큼 곱해주기 -if n > 1: - result *= 1 - (1 / n) -print(round(result)) \ No newline at end of file diff --git a/11720.py b/11720.py deleted file mode 100644 index 738e011..0000000 --- a/11720.py +++ /dev/null @@ -1,15 +0,0 @@ -word = list(input()) -alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] -print_list = [-1]*26 -cnt = 0 - -for i in range(len(word)): - for j in range(26): - if word[i] ==alphabet[j]: - if print_list[j] != -1: - cnt+=1 - else: - print_list[j] = cnt - cnt +=1 - -print(*print_list) \ No newline at end of file diff --git a/11722LDS.py b/11722LDS.py index 46f4fea..891d8f5 100644 --- a/11722LDS.py +++ b/11722LDS.py @@ -1,12 +1,12 @@ -N = int(input()) -A = [0] + list(map(int, input().split())) -dp = [1]*(N+1) - - -for i in range(1,N+1): - for j in range(1,i): - if A[i]= level[b]: - parent[b] = a - if level[a]==level[b]: - level[a] += 1 - else: - parent[a] = b - -N, M = map(int, input().split()) -parent = {i: i for i in range(1,N+1)} -level = {i:0 for i in range(1,N+1)} -for _ in range(M): - a, b = map(int, input().split()) - if find(a) != find(b): - union(a,b) -cnt = set() -for i in range(1,N+1): - pa = find(i) - if pa not in cnt: - cnt.add(pa) -print(len(cnt)) \ No newline at end of file diff --git "a/11725\355\212\270\353\246\254\354\235\230\353\266\200\353\252\250\354\260\276\352\270\260.py" "b/11725\355\212\270\353\246\254\354\235\230\353\266\200\353\252\250\354\260\276\352\270\260.py" deleted file mode 100644 index 09ce942..0000000 --- "a/11725\355\212\270\353\246\254\354\235\230\353\266\200\353\252\250\354\260\276\352\270\260.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict,deque - -N = int(input()) -graph = defaultdict(list) - -for _ in range(N-1): - a,b = map(int,input().split()) - graph[a].append(b) - graph[b].append(a) - -queue = deque([1]) -ans = {} -check = [False for _ in range(N+1)] - -while queue: - parent = queue.popleft() - for i in graph[parent]: - if not check[i]: - ans[i] = parent - queue.append(i) - check[i] = True - -for i in range(2,N+1): - print(ans[i]) \ No newline at end of file diff --git "a/11725\355\212\270\353\246\254\354\235\230\353\266\200\353\252\250\354\260\276\352\270\260_\353\263\265\354\212\265.py" "b/11725\355\212\270\353\246\254\354\235\230\353\266\200\353\252\250\354\260\276\352\270\260_\353\263\265\354\212\265.py" deleted file mode 100644 index d313798..0000000 --- "a/11725\355\212\270\353\246\254\354\235\230\353\266\200\353\252\250\354\260\276\352\270\260_\353\263\265\354\212\265.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -# BFS로 루트부터 전위순회.로 -# 루트 아래있는 노드들에 루트노드를 부모로 부여, 내려가며 반복해준다. -def BFS(start): - queue = deque() - visited = [False]*(N+1) - visited[start] = True - queue.append(start) - while queue: - cur_node = queue.popleft() - for next_node in graph[cur_node]: - if not visited[next_node]: - visited[next_node] = True - super_node[next_node] = cur_node - queue.append(next_node) - -N = int(input()) -graph = {i:[] for i in range(1,N+1)} -super_node = {i:0 for i in range(1,N+1)} -for _ in range(N-1): - a,b = map(int,input().split()) - graph[a].append(b) - graph[b].append(a) - -BFS(1) - -for i in range(2,N+1): - print(super_node[i]) \ No newline at end of file diff --git "a/11728 \353\260\260\354\227\264\355\225\251\354\271\230\352\270\260.py" "b/11728 \353\260\260\354\227\264\355\225\251\354\271\230\352\270\260.py" deleted file mode 100644 index ad7649b..0000000 --- "a/11728 \353\260\260\354\227\264\355\225\251\354\271\230\352\270\260.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -arr_a = list(map(int, input().split())) -arr_b = list(map(int, input().split())) -ai = 0 -bi = 0 -answer = [] -while 1: - if arr_a[ai] <= arr_b[bi]: - answer.append(arr_a[ai]) - ai += 1 - else: - answer.append(arr_b[bi]) - bi += 1 - if ai == N or bi == M: - answer += arr_a[ai:] + arr_b[bi:] - break -print(*answer) \ No newline at end of file diff --git a/11758CCW.py b/11758CCW.py deleted file mode 100644 index e51cca6..0000000 --- a/11758CCW.py +++ /dev/null @@ -1,18 +0,0 @@ -dot = [] -for i in range(3): - dot.append(list(map(int, input().split()))) - -# 외적. 양수면 반시계 음수면 시계 일직선이면 0 -def ccw(p1, p2, p3): - x1, y1 = p1 - x2, y2 = p2 - x3, y3 = p3 - return (x1 * y2 + x2 * y3 + x3 * y1) - (x2 * y1 + x3 * y2 + x1 * y3) - -result = ccw(dot[0], dot[1], dot[2]) -if result > 0: - print(1) -elif result < 0: - print(-1) -else: - print(0) \ No newline at end of file diff --git "a/11780\355\224\214\353\241\234\354\235\264\353\223\2342.py" "b/11780\355\224\214\353\241\234\354\235\264\353\223\2342.py" deleted file mode 100644 index 5286469..0000000 --- "a/11780\355\224\214\353\241\234\354\235\264\353\223\2342.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - -n=int(input()) -m=int(input()) -cities = [[float('inf') for _ in range(n+1)] for _ in range(n+1)] -pre_node = [[0 for _ in range(n+1)] for _ in range(n+1)] -for i in range(1,n+1): - cities[i][i] = 0 - -for _ in range(m): - a,b,c = map(int,input().split()) - cities[a][b] = min(cities[a][b],c) - # 이전노드 저장. - pre_node[a][b] = a - -for k in range(1,n+1): - for i in range(1,n+1): - for j in range(1,n+1): - if cities[i][j] > cities[i][k] + cities[k][j]: - cities[i][j] = cities[i][k] + cities[k][j] - pre_node[i][j] = pre_node[k][j] - -for i in range(1,n+1): - for j in range(1,n+1): - print(cities[i][j] if not cities[i][j]==float('inf') else 0,end=" ") - print() -# i 에서 j로 가는 최소비용에 포함되어 잇는 도시의 개수 k출력 -# i에서 j로 가는 경로를 공배으로 구분해 출력. -for i in range(1,n+1): - for j in range(1,n+1): - if cities[i][j]==float('inf') or cities[i][j]==0: - print(0) - else: - # i에서 경로를 따라 최단거리를 추적하는 노드들. - path = [j] - end_point = j - while end_point != i: - path.append(pre_node[i][end_point]) - end_point = pre_node[i][end_point] - print(len(path), end=" ") - print(*path[::-1]) diff --git "a/1181\353\213\250\354\226\264\354\240\225\353\240\254.py" "b/1181\353\213\250\354\226\264\354\240\225\353\240\254.py" deleted file mode 100644 index 3f4f912..0000000 --- "a/1181\353\213\250\354\226\264\354\240\225\353\240\254.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = [] - -for _ in range(N): - a = input().rstrip() - arr.append((len(a),a)) -arr = list(set(arr)) -arr.sort(key=lambda arr: (arr[0],arr[1])) - -for i in range(len(arr)): - print(arr[i][1]) \ No newline at end of file diff --git "a/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_comb.py" "b/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_comb.py" index b3c48d9..2f184f3 100644 --- "a/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_comb.py" +++ "b/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_comb.py" @@ -1,20 +1,20 @@ -import sys -input = sys.stdin.readline -from itertools import combinations - - -N,S = map(int,input().split()) -super_set = list(map(int,input().split())) -cnt = 0 - -# 1개뽑는조합~n개뽑는조합까지 모든 부분집합에 대해 조사 가능. -# 부분집합의 요소들의 합이s가 되는지만 조사하고 버림. -for i in range(1,N+1) : - sub_set = list(combinations(super_set,i)) - for c in sub_set : - if sum(c) == S : - cnt +=1 - -print(cnt) - - +import sys +input = sys.stdin.readline +from itertools import combinations + + +N,S = map(int,input().split()) +super_set = list(map(int,input().split())) +cnt = 0 + +# 1개뽑는조합~n개뽑는조합까지 모든 부분집합에 대해 조사 가능. +# 부분집합의 요소들의 합이s가 되는지만 조사하고 버림. +for i in range(1,N+1) : + sub_set = list(combinations(super_set,i)) + for c in sub_set : + if sum(c) == S : + cnt +=1 + +print(cnt) + + diff --git "a/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_dfs.py" "b/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_dfs.py" index 2f0bcfb..459b019 100644 --- "a/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_dfs.py" +++ "b/1182\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_dfs.py" @@ -1,21 +1,21 @@ -import sys -input = sys.stdin.readline - -# 처음 첫요소,합0으로 들어가서 sum요소에 자기value더해주고 자기를포함하는 재귀와 포함하지 않는 재귀로 나눠서 다음 idx진행. -# 부분집합은 결국 요소를 포함하느냐 안하느냐 0과1인데서 착안한 탐색. -def dfs(idx, sum): - global cnt - if idx >= n: - return - sum += s_[idx] - if sum == s: - cnt += 1 - dfs(idx + 1, sum - s_[idx]) - dfs(idx + 1, sum) - - -n, s = map(int, input().split()) -s_ = list(map(int, input().split())) -cnt = 0 -dfs(0, 0) +import sys +input = sys.stdin.readline + +# 처음 첫요소,합0으로 들어가서 sum요소에 자기value더해주고 자기를포함하는 재귀와 포함하지 않는 재귀로 나눠서 다음 idx진행. +# 부분집합은 결국 요소를 포함하느냐 안하느냐 0과1인데서 착안한 탐색. +def dfs(idx, sum): + global cnt + if idx >= n: + return + sum += s_[idx] + if sum == s: + cnt += 1 + dfs(idx + 1, sum - s_[idx]) + dfs(idx + 1, sum) + + +n, s = map(int, input().split()) +s_ = list(map(int, input().split())) +cnt = 0 +dfs(0, 0) print(cnt) \ No newline at end of file diff --git "a/1194\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244\352\260\200\354\236\220.py" "b/1194\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244\352\260\200\354\236\220.py" deleted file mode 100644 index bfbc123..0000000 --- "a/1194\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244\352\260\200\354\236\220.py" +++ /dev/null @@ -1,39 +0,0 @@ -from collections import deque -import sys -input = sys.stdin.readline -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] -def bfs(): - while q: - x, y, key, cnt = q.popleft() - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0 <= nx < n and 0 <= ny < m and s[nx][ny] != "#" and not visit[nx][ny][key]: - if s[nx][ny] == ".": - visit[nx][ny][key] = 1 - q.append([nx, ny, key, cnt + 1]) - elif s[nx][ny] == "1": - return cnt + 1 - else: - if s[nx][ny].isupper(): - if key & 1 << (ord(s[nx][ny]) - 65): - visit[nx][ny][key] = 1 - q.append([nx, ny, key, cnt + 1]) - elif s[nx][ny].islower(): - nc = key | (1 << ord(s[nx][ny]) - 97) - if visit[nx][ny][nc] == 0: - visit[nx][ny][nc] = 1 - q.append([nx, ny, nc, cnt + 1]) - return -1 -n, m = map(int, input().split()) -q = deque() -visit = [[[0] * 64 for i in range(m)] for i in range(n)] -s = list(list(input().rstrip()) for _ in range(n)) -for i in range(n): - for j in range(m): - if s[i][j] == "0": - q.append([i, j, 0, 0]) - s[i][j] = "." - visit[i][j][0] = 1 -print(bfs()) \ No newline at end of file diff --git "a/1197\354\265\234\354\206\214\354\212\244\355\214\250\353\213\235\355\212\270\353\246\254.py" "b/1197\354\265\234\354\206\214\354\212\244\355\214\250\353\213\235\355\212\270\353\246\254.py" index 7a61cb2..ca3bbda 100644 --- "a/1197\354\265\234\354\206\214\354\212\244\355\214\250\353\213\235\355\212\270\353\246\254.py" +++ "b/1197\354\265\234\354\206\214\354\212\244\355\214\250\353\213\235\355\212\270\353\246\254.py" @@ -1,41 +1,41 @@ -import sys - -input = sys.stdin.readline -V, S = map(int, input().split()) - -# s크루스칼 알고리즘은 sort를 써야하므로 간선 list안에 튜플을 담아준다. -edge = [] -for _ in range(S): - a, b, w = map(int, input().split()) - edge.append((w, a, b)) -# 간선을 에 따라 오름차순 정렬 -edge.sort(key=lambda x: x[0]) - -# 부모노드를 각 노드idx에 맞춰 생성, 매칭해준다. -parent = list(range(V + 1)) - -# union 알고리즘 구현 각 노드가 속한 집합의 대푯값(루트노드)을 구하고 합쳐준다. -def union(a, b): - a = find(a) - b = find(b) - - if b < a: - parent[a] = b - else: - parent[b] = a - -# 루트노드를 찾기위해 재귀로 찾아준다. -def find(a): - if a == parent[a]: - return a - parent[a] = find(parent[a]) # 경로 압축 - return parent[a] - -# 간선을 가중치 낮은것부터 하나씩 꺼내 둘이 다른 집합이라면 MST집합에 이어주고 가중치 값을 더해준다. -sum = 0 -for w, s, e in edge: - if find(s) != find(e): - union(s, e) - sum += w - +import sys + +input = sys.stdin.readline +V, S = map(int, input().split()) + +# s크루스칼 알고리즘은 sort를 써야하므로 간선 list안에 튜플을 담아준다. +edge = [] +for _ in range(S): + a, b, w = map(int, input().split()) + edge.append((w, a, b)) +# 간선을 에 따라 오름차순 정렬 +edge.sort(key=lambda x: x[0]) + +# 부모노드를 각 노드idx에 맞춰 생성, 매칭해준다. +parent = list(range(V + 1)) + +# union 알고리즘 구현 각 노드가 속한 집합의 대푯값(루트노드)을 구하고 합쳐준다. +def union(a, b): + a = find(a) + b = find(b) + + if b < a: + parent[a] = b + else: + parent[b] = a + +# 루트노드를 찾기위해 재귀로 찾아준다. +def find(a): + if a == parent[a]: + return a + parent[a] = find(parent[a]) # 경로 압축 + return parent[a] + +# 간선을 가중치 낮은것부터 하나씩 꺼내 둘이 다른 집합이라면 MST집합에 이어주고 가중치 값을 더해준다. +sum = 0 +for w, s, e in edge: + if find(s) != find(e): + union(s, e) + sum += w + print(sum) \ No newline at end of file diff --git a/1201 NMK.py b/1201 NMK.py deleted file mode 100644 index b3d63ce..0000000 --- a/1201 NMK.py +++ /dev/null @@ -1,60 +0,0 @@ -import sys -n,m,k = map(int, sys.stdin.readline().split()) -# n이 범위를 만족하는지 (자세한 것은 비둘기의 정리 참조) -if m + k - 1 <= n and n <= m * k: - # 첫번째 조건 반영 (1 ~ n)까지의 수 - num = [i + 1 for i in range(n)] - g = [] - # k를 담는다 (= 첫 그룹의 끝나는 점) - g.append(0) - g.append(k) - # 이미 k를 넣었으니 전체에서 k개는 빼고 봐도 되니까 n에서 k를 빼준다 - n -= k - # 그룹도 한개를 만들었으니 m에서 1을 빼준다 - m -= 1 - # 남은 n - k에서 균일하게 그룹 수(m - 1)로 나누어주면 각각의 그룹의 갯수가 나온다 - gs = 1 if m == 0 else n // m - # 나누어 떨어지지 않는다면 나머지를 변수에 할당해준다 - r = 0 if m == 0 else n % m - for i in range(m): - # 항상 g의 마지막 원소는 그 그룹이 끝나는 지점이므로 거기서 부터 갱신해줘야 한다 - # 각 그룹의 원소의 갯수 만큼 더해주고 나머지의 원소들을 하나하나 씩 다음 그룹에 더해준다 - g.append(g[-1] + gs + (1 if r > 0 else 0)) - if r > 0: - # 나머지에서 각 그룹한테 한개씩 줬으니까 빼준다 - r -= 1 - # 각 그룹을 뒤집어주는 작업 - for i in range(len(g) - 1): - begin = g[i] - end = g[i + 1] - 1 - while begin < end: - temp = num[begin] - num[begin] = num[end] - num[end] = temp - begin += 1 - end -= 1 - for i in num: - print(i, end=' ') -# 애초에 n이 범위를 벗어나면 불가능하므로 -1 출력 -else: - print(-1) - - - -################ -N,M,K=map(int,input().split()) -if M+K-1<=N<=M*K: - Ln=list(range(N+1)) - Cn=[1]*M - N-=M - i=0 - while N>0: - Cn[i]+=min(K-1,N) - N-=min(K-1,N) - i+=1 - i=0 - for j in Cn: - print(' '.join(map(str,Ln[i+j:i:-1])),end=" ") - i+=j -else: - print(-1) \ No newline at end of file diff --git a/12015LIS2.py b/12015LIS2.py deleted file mode 100644 index 5ad20fc..0000000 --- a/12015LIS2.py +++ /dev/null @@ -1,13 +0,0 @@ -from bisect import bisect_left #이진탐색 코드, 같은 수일 경우 왼쪽 index를 돌려준다 - -input() -A = list(map(int, input().split())) -dp = [] - -for i in A: - k = bisect_left(dp, i) #자신이 들어갈 위치 k - if len(dp) <= k: #i가 가장 큰 숫자라면 - dp.append(i) - else: - dp[k] = i #자신보다 큰 수 중 최솟값과 대체 -print(len(dp)) \ No newline at end of file diff --git "a/12026BOJ\352\261\260\353\246\254.py" "b/12026BOJ\352\261\260\353\246\254.py" deleted file mode 100644 index 1c01843..0000000 --- "a/12026BOJ\352\261\260\353\246\254.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -BOJ_avenue = input().rstrip() -# 스타트 i i+1부터N번까지 점프 가능 K만큼 점프하는 에너지 k*k -# 가장 가까운 BOJ를 순서대로 밟기. -# 누적 -> dp(전 상태에 따라 변화값이 존재하는 조건.) -dp = [float('inf')]*N -dp[0] = 0 -for i in range(1,N): - for j in range(i): - if BOJ_avenue[j]=='B' and BOJ_avenue[i]=='O': - dp[i] = min(dp[i],dp[j]+ pow(i-j,2)) - elif BOJ_avenue[j]=='O' and BOJ_avenue[i]=="J": - dp[i] = min(dp[i],dp[j]+ pow(i-j,2)) - elif BOJ_avenue[j]=='J' and BOJ_avenue[i]=='B': - dp[i] = min(dp[i],dp[j]+ pow(i-j,2)) - -if dp[N-1] != float('inf'): - print(dp[N-1]) -else: - print(-1) \ No newline at end of file diff --git "a/1208\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\2512.py" "b/1208\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\2512.py" deleted file mode 100644 index f89bd0b..0000000 --- "a/1208\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\2512.py" +++ /dev/null @@ -1,31 +0,0 @@ -from sys import stdin -from collections import defaultdict - - -def dfs(idx, end_idx, subtotal, direction): - global answer - - # 종료 index에 왓을때 오른쪽에 진행되던 분기는 left 딕셔너리에 s-자기의 총합만큼의 left값이 있나 체크 후 그 숫자만큼 답에 더해주고 - # 왼쪽은 총합만큼 딕셔너리에 기록해준다.(왼쪽과 오른쪽의 합이 s가 되는 만큼 answer에 더해진다.) - if idx == end_idx: - if direction == "right": - answer += left[s - subtotal] - else: - left[subtotal] += 1 - return - # 결국 부분수열의 합은 각 원소에 대해 0또는 1로 가져갈것이냐 안가져갈 것이냐 - # 인덱스를 진행해가며 분기를 나눠 계산한다. - dfs(idx + 1, end_idx, subtotal, direction) - dfs(idx + 1, end_idx, subtotal + nums[idx], direction) - - -if __name__ == "__main__": - answer = 0 - n, s = map(int, stdin.readline().split()) - nums = list(map(int, stdin.readline().split())) - left = defaultdict(int) - - dfs(0, n//2, 0, "left") - dfs(n//2, n, 0, "right") - - print(answer if s != 0 else answer - 1) \ No newline at end of file diff --git "a/1208\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_\353\271\204\355\212\270\353\247\210\354\212\244\355\202\271.py" "b/1208\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_\353\271\204\355\212\270\353\247\210\354\212\244\355\202\271.py" deleted file mode 100644 index b12c97e..0000000 --- "a/1208\353\266\200\353\266\204\354\210\230\354\227\264\354\235\230\355\225\251_\353\271\204\355\212\270\353\247\210\354\212\244\355\202\271.py" +++ /dev/null @@ -1,54 +0,0 @@ -import sys -# 입력부 -n,s = map(int, sys.stdin.readline().split()) -a = list(map(int, sys.stdin.readline().split())) -# 이분 분할 -m = n//2 -n = n - m -# first : 왼쪽 Subset -# 왼쪽의 경우의 수. -first = [0] * (1< 0: - first[i] += a[k] -# second : 오른쪽 Subset -# 오른쪽도 동일하게 진행. -second = [0]*(1< 0: - second[i] += a[k+n] -# first 오름차순 정렬, second 내림차순 정렬 -first.sort() -second.sort(reverse = True) -# n, m = first의 길이, second의 길이 -n,m,i,j,ans = (1< n: - return - if n == sum_num: - cnt += 1 - if cnt == k: - print(answer[:-1]) - exit() - for i in (1, 2, 3): - DFS(sum_num + i, answer+str(i)+'+') - -cnt = 0 -n, k = map(int, input().split()) -DFS(0, '') -print(-1) \ No newline at end of file diff --git "a/1213\355\216\240\353\246\260\353\223\234\353\241\254 \353\247\214\353\223\244\352\270\260.py" "b/1213\355\216\240\353\246\260\353\223\234\353\241\254 \353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 6aa7038..0000000 --- "a/1213\355\216\240\353\246\260\353\223\234\353\241\254 \353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -name = input().rstrip() -count = defaultdict(int) -for char in name: - count[char] += 1 -char_set = [] -flag = 0 -mid = '' -for char in count: - if count[char] % 2: - if flag: - print("I'm Sorry Hansoo") - exit() - else: - mid = char - flag = 1 - for _ in range(count[char] // 2): - char_set.append(char) - else: - for _ in range(count[char] // 2): - char_set.append(char) -char_set.sort() -answer = ''.join(char_set) -print(answer + mid + answer[::-1]) \ No newline at end of file diff --git "a/1238\355\214\214\355\213\260.py" "b/1238\355\214\214\355\213\260.py" index 263bfdb..5067754 100644 --- "a/1238\355\214\214\355\213\260.py" +++ "b/1238\355\214\214\355\213\260.py" @@ -1,42 +1,42 @@ -import sys -from heapq import heappush, heappop -input = sys.stdin.readline - - -n, m, x = map(int, input().split()) -inf = 100000000 -s = [[] for i in range(n + 1)] -dp = [inf] * (n + 1) -s_r = [[] for i in range(n + 1)] -dp_r = [inf] * (n + 1) - - -def dijkstra(start, dp, s): - heap = [] - dp[start] = 0 - heappush(heap, [0, start]) - while heap: - w, n = heappop(heap) - if dp[n] < w: - continue - for n_n, wei in s[n]: - n_w = wei + w - if n_w < dp[n_n]: - dp[n_n] = n_w - heappush(heap, [n_w, n_n]) - - -for i in range(m): - a, b, t = map(int, input().split()) - s[a].append([b, t]) - s_r[b].append([a, t]) - - -dijkstra(x, dp, s) -dijkstra(x, dp_r, s_r) - - -max_ = 0 -for i in range(1, n + 1): - max_ = max(max_, dp[i] + dp_r[i]) +import sys +from heapq import heappush, heappop +input = sys.stdin.readline + + +n, m, x = map(int, input().split()) +inf = 100000000 +s = [[] for i in range(n + 1)] +dp = [inf] * (n + 1) +s_r = [[] for i in range(n + 1)] +dp_r = [inf] * (n + 1) + + +def dijkstra(start, dp, s): + heap = [] + dp[start] = 0 + heappush(heap, [0, start]) + while heap: + w, n = heappop(heap) + if dp[n] < w: + continue + for n_n, wei in s[n]: + n_w = wei + w + if n_w < dp[n_n]: + dp[n_n] = n_w + heappush(heap, [n_w, n_n]) + + +for i in range(m): + a, b, t = map(int, input().split()) + s[a].append([b, t]) + s_r[b].append([a, t]) + + +dijkstra(x, dp, s) +dijkstra(x, dp_r, s_r) + + +max_ = 0 +for i in range(1, n + 1): + max_ = max(max_, dp[i] + dp_r[i]) print(max_) \ No newline at end of file diff --git "a/1238\355\214\214\355\213\260_re.py" "b/1238\355\214\214\355\213\260_re.py" deleted file mode 100644 index 7fbc381..0000000 --- "a/1238\355\214\214\355\213\260_re.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop, heappush - -def dijkstra(start): - heap = [] - visited = {i: float('inf') for i in range(1, N + 1)} - visited[start] = 0 - heappush(heap, (0, start)) - while heap: - time, cur_node = heappop(heap) - if visited[cur_node] < time: - continue - for next_node, next_time in graph[cur_node]: - if visited[next_node] > time + next_time: - visited[next_node] = time + next_time - heappush(heap, (visited[next_node], next_node)) - return visited -N, M, X = map(int, input().split()) -graph = {i: [] for i in range(1, N + 1)} -for __ in range(M): - s, e, t = map(int, input().split()) - graph[s].append((e, t)) - -max_dist = 0 -dist_X = dijkstra(X) -for i in range(1, N + 1): - if i == X: continue - each = dijkstra(i) - max_dist = max(max_dist, dist_X[i] + each[X]) -print(max_dist) \ No newline at end of file diff --git a/123game.py b/123game.py index b63c6f5..5f55c3c 100644 --- a/123game.py +++ b/123game.py @@ -1,10 +1,10 @@ -n = int(input()) - -def solution(n): - if n <= 3: - return '124'[n-1] - else: - q,r = divmod(n-1, 3) - return solution(q) + '124'[r] - +n = int(input()) + +def solution(n): + if n <= 3: + return '124'[n-1] + else: + q,r = divmod(n-1, 3) + return solution(q) + '124'[r] + print(solution(n)) \ No newline at end of file diff --git "a/1240\353\205\270\353\223\234\354\202\254\354\235\264\354\235\230\352\261\260\353\246\254.py" "b/1240\353\205\270\353\223\234\354\202\254\354\235\264\354\235\230\352\261\260\353\246\254.py" index 9df45be..69d235e 100644 --- "a/1240\353\205\270\353\223\234\354\202\254\354\235\264\354\235\230\352\261\260\353\246\254.py" +++ "b/1240\353\205\270\353\223\234\354\202\254\354\235\264\354\235\230\352\261\260\353\246\254.py" @@ -1,36 +1,34 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict,deque - -def Distance(a,b): - queue = deque() - queue.append(a) - visited = [False]*(N+1) - visited[a] = True - target_dist = [0]*(N+1) - while queue: - v = queue.popleft() - if v==b: - print(target_dist[v]) - return - for next,dist in graph[v]: - if not visited[next]: - queue.append(next) - visited[next] = True - target_dist[next] += target_dist[v] +dist - print(queue) - - - -N,M = map(int,input().split()) -graph = defaultdict(list) - - -for _ in range(N-1): - a,b,dist = map(int,input().split()) - graph[a].append((b,dist)) - graph[b].append((a,dist)) - -for _ in range(M): - a,b = map(int,input().split()) +import sys +input = sys.stdin.readline +from collections import defaultdict,deque + +def Distance(a,b): + queue = deque() + queue.append(a) + visited = [False]*(N+1) + visited[a] = True + target_dist = [0]*(N+1) + while queue: + v = queue.popleft() + if v==b: + print(target_dist[v]) + return + for next,dist in graph[v]: + if not visited[next]: + queue.append(next) + visited[next] = True + target_dist[next] += target_dist[v] +dist + + +N,M = map(int,input().split()) +graph = defaultdict(list) + + +for _ in range(N-1): + a,b,dist = map(int,input().split()) + graph[a].append((b,dist)) + graph[b].append((a,dist)) + +for _ in range(M): + a,b = map(int,input().split()) Distance(a,b) \ No newline at end of file diff --git "a/1244\354\212\244\354\234\204\354\271\230 \354\274\234\352\263\240 \353\201\204\352\270\260.py" "b/1244\354\212\244\354\234\204\354\271\230 \354\274\234\352\263\240 \353\201\204\352\270\260.py" deleted file mode 100644 index 70a386f..0000000 --- "a/1244\354\212\244\354\234\204\354\271\230 \354\274\234\352\263\240 \353\201\204\352\270\260.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - - -N = int(input()) -switches = list(map(int, input().split())) -M = int(input()) -for _ in range(M): - a, b = map(int, input().split()) - # 남학생이면 스위치 번호가 받은 수의 배수이면 그 스위치의 상태를 바꾼다. XOR(3을 받으면 3,6끔) - # 여학생은 자기가 받은 스위치 번호를 중심으로 좌우가 대칭이면서 가장 많은 스위치를 포함하는 구간을 찾아 상태를 모두 바꾼다. XOR - if a==1: - for i in range(N): - if not (i+1)%b: - switches[i] ^= 1 - else: - size=1 - while b-1-size>=0 and b-1+size= 0: - return False - elif hap > 0 and S[i][idx] <= 0: - return False - return True - -def solve(idx): - # 인덱스가 N에 도달할때까지 모든 idx check가 true인 상태면 모든 선택지에 대해 true를 반환하고 그 당시의 result배열을 반환. - if idx == N: - return True - # 0일때는 0기록하고 다음순서로 넘어간다.(0일때는 result도 무조건 0) - if S[idx][idx] == 0: - result[idx] = 0 - return solve(idx+1) - # 수를 1부터 10까지만 쓸 수있다. 모든경우의 수를 S값 즉 양 음에 따라 곱해서 기록한다. - for i in range(1, 11): - result[idx] = S[idx][idx] * i - # 인덱스까지의 모든 합이 부호와 일치하면 true.그리고 뒤의 모든 idx도 다 일치하면 true - if ck(idx) and solve(idx+1): - return True - # 1~10 돌았는데 부호일치안하면 잘못된 선택지이므로 False반환. - return False - -#s는 array의 부호에 따라 result에 저장할 숫자들의 계수(음수,양수여부를 저장하는 배열) -N = int(input()) -arr = list(input()) -S = [[0]*N for _ in range(N)] -for i in range(N): - for j in range(i, N): - temp = arr.pop(0) - if temp == '+': - S[i][j] = 1 - elif temp == '-': - S[i][j] = -1 - -# result배열에 각 부호에 맞는 숫자를 경우의수에 따라. 저장해주면서 백트래킹한다. -result = [0] * N -solve(0) -# checking이끝난 배열에 대해 출력한다. -print(' '.join(map(str, result))) \ No newline at end of file diff --git "a/1251\353\213\250\354\226\264\353\202\230\353\210\204\352\270\260.py" "b/1251\353\213\250\354\226\264\353\202\230\353\210\204\352\270\260.py" deleted file mode 100644 index 21ad1f7..0000000 --- "a/1251\353\213\250\354\226\264\353\202\230\353\210\204\352\270\260.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -# 브루트포스. -# ord()로 가장 낮은 idx찾으려 했는데 맨앞이랑 맨끝때매 경우의수 너무 갈림. -s = input().rstrip() -l = len(s) -answer = [] -for i in range(l-2): - for j in range(i+1, l-1): - for k in range(j+1, l): - new_s = s[:j][::-1] + s[j:k][::-1] + s[k:][::-1] - answer.append(new_s) - -answer.sort() -print(answer[0]) \ No newline at end of file diff --git "a/1256\354\202\254\354\240\204.py" "b/1256\354\202\254\354\240\204.py" deleted file mode 100644 index 2038a4d..0000000 --- "a/1256\354\202\254\354\240\204.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M,K = map(int,input().split()) -arr = [[1]*(M+1) for _ in range(N+1)] - -for i in range(1,N+1): - for j in range(1,M+1): - # a를 하나 뺀 단어와 z를 하나 뺀 단어의 갯수의 합. - arr[i][j] = arr[i-1][j] + arr[i][j-1] - # a와z의 갯수에 따라 단어의 갯수를 저장하는 배열 arr. - -if arr[N][M] < K: - print(-1) -else: - result="" - while True: - if not N or not M: - result += "z"*M - result += "a"*N - break -# arr[N-1][M]은 a를 하나 앞으로 빼뒀을때 뒤에 배열 할 수 있는 가짓수.즉 K가 이거보다 작으면 앞이 a고 크면 z임. -# 이걸 기준으로 하나씩 앞자릿수를 확정시켜주며 z가 앞으로 가면 flag만큼 K를 줄여줌(그래야 다시 앞자리를 a로 유지시키면서 반복가능.) - flag = arr[N-1][M] - if K <= flag: - result += "a" - N -= 1 - else: - result += "z" - M -= 1 - K -= flag - print(result) \ No newline at end of file diff --git a/1260DFSBFS.py b/1260DFSBFS.py index d5a76a4..0af14b0 100644 --- a/1260DFSBFS.py +++ b/1260DFSBFS.py @@ -1,44 +1,44 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -N,M,V = list(map(int,input().split())) -graph = defaultdict(list) -check = [True] +[False]*(N) -stack = [] - -for _ in range(M): - a,b = map(int,input().split()) - graph[a] +=[b] - graph[b] +=[a] - -for i in range(1,N+1): - graph[i].sort() - -def DFS(v): - stack.append(v) - check[v] = True - for i in graph[v]: - if check[i]==False: - DFS(i) - return stack - -def BFS(v): - queue = [v] - stack.append(v) - check[v] = True - while queue: - v = queue.pop(0) - for i in graph[v]: - if check[i] ==False: - queue.append(i) - stack.append(i) - check[i] = True - return stack - -ans_DFS = DFS(V) -print(*ans_DFS) -check = [True] +[False]*(N) -stack = [] -ans_BFS = BFS(V) +import sys +input = sys.stdin.readline +from collections import defaultdict + +N,M,V = list(map(int,input().split())) +graph = defaultdict(list) +check = [True] +[False]*(N) +stack = [] + +for _ in range(M): + a,b = map(int,input().split()) + graph[a] +=[b] + graph[b] +=[a] + +for i in range(1,N+1): + graph[i].sort() + +def DFS(v): + stack.append(v) + check[v] = True + for i in graph[v]: + if check[i]==False: + DFS(i) + return stack + +def BFS(v): + queue = [v] + stack.append(v) + check[v] = True + while queue: + v = queue.pop(0) + for i in graph[v]: + if check[i] ==False: + queue.append(i) + stack.append(i) + check[i] = True + return stack + +ans_DFS = DFS(V) +print(*ans_DFS) +check = [True] +[False]*(N) +stack = [] +ans_BFS = BFS(V) print(*ans_BFS) \ No newline at end of file diff --git "a/BOJ/bfs/1261 \354\225\214\352\263\240\354\212\244\355\214\237/1261\354\225\214\352\263\240\354\212\244\355\214\237_deque.py" "b/1261\354\225\214\352\263\240\354\212\244\355\214\237_deque.py" similarity index 96% rename from "BOJ/bfs/1261 \354\225\214\352\263\240\354\212\244\355\214\237/1261\354\225\214\352\263\240\354\212\244\355\214\237_deque.py" rename to "1261\354\225\214\352\263\240\354\212\244\355\214\237_deque.py" index 623a874..270dc52 100644 --- "a/BOJ/bfs/1261 \354\225\214\352\263\240\354\212\244\355\214\237/1261\354\225\214\352\263\240\354\212\244\355\214\237_deque.py" +++ "b/1261\354\225\214\352\263\240\354\212\244\355\214\237_deque.py" @@ -1,27 +1,27 @@ -from collections import deque -dx = [-1,1,0,0] -dy = [0,0,-1,1] - -m,n = map(int, input().split()) -arr = [ list(map(int, input())) for _ in range(n)] -dist = [[-1] * m for _ in range(n)] # 가중치 - -q = deque() -q.append((0,0)) -dist[0][0] = 0 -while q: - x,y = q.popleft() - for k in range(4): - nx = x + dx[k] - ny = y + dy[k] - if 0 <= nx < n and 0 <= ny < m: - if dist[nx][ny] == -1: - if arr[nx][ny] == 0: - dist[nx][ny] = dist[x][y] - q.appendleft((nx, ny)) - else: - dist[nx][ny] = dist[x][y] + 1 - q.append((nx, ny)) -print(dist[n-1][m-1]) - +from collections import deque +dx = [-1,1,0,0] +dy = [0,0,-1,1] + +m,n = map(int, input().split()) +arr = [ list(map(int, input())) for _ in range(n)] +dist = [[-1] * m for _ in range(n)] # 가중치 + +q = deque() +q.append((0,0)) +dist[0][0] = 0 +while q: + x,y = q.popleft() + for k in range(4): + nx = x + dx[k] + ny = y + dy[k] + if 0 <= nx < n and 0 <= ny < m: + if dist[nx][ny] == -1: + if arr[nx][ny] == 0: + dist[nx][ny] = dist[x][y] + q.appendleft((nx, ny)) + else: + dist[nx][ny] = dist[x][y] + 1 + q.append((nx, ny)) +print(dist[n-1][m-1]) + # 핵심은 0은 appendleft, 1은 appendrignt를 통해 0부터 queue에 넣어 우선순위를 부여. \ No newline at end of file diff --git "a/1261\354\225\214\352\263\240\354\212\244\355\214\237_heap.py" "b/1261\354\225\214\352\263\240\354\212\244\355\214\237_heap.py" index 61f066d..f07eee8 100644 --- "a/1261\354\225\214\352\263\240\354\212\244\355\214\237_heap.py" +++ "b/1261\354\225\214\352\263\240\354\212\244\355\214\237_heap.py" @@ -1,25 +1,27 @@ -from heapq import heappush, heappop - -m, n = map(int, input().split()) -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] -s = [] -visit = [[0] * m for i in range(n)] -for i in range(n): - s.append(list(map(int, input()))) -def bfs(): - heap = [] - heappush(heap, [0, 0, 0]) - visit[0][0] = 1 - while heap: - c, a, b = heappop(heap) - if a == n - 1 and b == m - 1: - print(c) - return - for i in range(4): - x = a + dx[i] - y = b + dy[i] - if 0 <= x < n and 0 <= y < m and visit[x][y] == 0: - heappush(heap, [c + 1 if s[x][y] == 1 else c, x, y]) - visit[x][y] = 1 +from heapq import heappush, heappop + +m, n = map(int, input().split()) +dx = [1, -1, 0, 0] +dy = [0, 0, -1, 1] +s = [] +visit = [[0] * m for i in range(n)] + +for i in range(n): + s.append(list(map(int, input()))) + +def bfs(): + heap = [] + heappush(heap, [0, 0, 0]) + visit[0][0] = 1 + while heap: + c, a, b = heappop(heap) + if a == n - 1 and b == m - 1: + print(c) + return + for i in range(4): + x = a + dx[i] + y = b + dy[i] + if 0 <= x < n and 0 <= y < m and visit[x][y] == 0: + heappush(heap, [c + 1 if s[x][y] == 1 else c, x, y]) + visit[x][y] = 1 bfs() \ No newline at end of file diff --git a/12738LIS3.py b/12738LIS3.py deleted file mode 100644 index 5ad20fc..0000000 --- a/12738LIS3.py +++ /dev/null @@ -1,13 +0,0 @@ -from bisect import bisect_left #이진탐색 코드, 같은 수일 경우 왼쪽 index를 돌려준다 - -input() -A = list(map(int, input().split())) -dp = [] - -for i in A: - k = bisect_left(dp, i) #자신이 들어갈 위치 k - if len(dp) <= k: #i가 가장 큰 숫자라면 - dp.append(i) - else: - dp[k] = i #자신보다 큰 수 중 최솟값과 대체 -print(len(dp)) \ No newline at end of file diff --git "a/12782 \353\271\204\355\212\270 \354\232\260\354\240\225\354\247\200\354\210\230.py" "b/12782 \353\271\204\355\212\270 \354\232\260\354\240\225\354\247\200\354\210\230.py" deleted file mode 100644 index df92c08..0000000 --- "a/12782 \353\271\204\355\212\270 \354\232\260\354\240\225\354\247\200\354\210\230.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - N, M = map(lambda x: int(x,2), input().split()) - xor = N^M - n = len(bin(xor)[2:]) - one = 0 - zero = 0 - answer = 0 - for i in range(n): - if xor & 1< one: - one, zero = zero, one - answer += zero - answer += one - zero - print(answer) \ No newline at end of file diff --git "a/12813\354\235\264\354\247\204\354\210\230 \352\263\204\354\202\260.py" "b/12813\354\235\264\354\247\204\354\210\230 \352\263\204\354\202\260.py" deleted file mode 100644 index d2d39bf..0000000 --- "a/12813\354\235\264\354\247\204\354\210\230 \352\263\204\354\202\260.py" +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline - -A = int(input(), 2) -B = int(input(), 2) -print(bin(A & B)[2:].zfill(100000)) -print(bin(A | B)[2:].zfill(100000)) -print(bin(A ^ B)[2:].zfill(100000)) -print(bin(A ^ (1<<100000)-1)[2:].zfill(100000)) -print(bin(B ^ (1<<100000)-1)[2:].zfill(100000)) - diff --git "a/12851\354\210\250\353\260\224\352\274\255\354\247\2102.py" "b/12851\354\210\250\353\260\224\352\274\255\354\247\2102.py" index 549ef29..68d869a 100644 --- "a/12851\354\210\250\353\260\224\352\274\255\354\247\2102.py" +++ "b/12851\354\210\250\353\260\224\352\274\255\354\247\2102.py" @@ -1,44 +1,41 @@ -import sys -from collections import deque -input = sys.stdin.readline - -n, k = list(map(int, input().split())) - -def bfs(n): - # visited[next] : next 까지 오는데 얼마의 최소 time을 저장. - # ways[next] : next 까지 최소 time으로 오는 방법의 수 저장. - queue = deque([n]) - visited = [float('inf')]*100001 - ways = [0]*100001 - time = 0 - success = False - ways[n] = 1 - visited[n] = 0 - -# 한 size씩 측정해 그 사이즈까지만 돌리고 성공했으면 빠져나옴. - while queue and not success: - size = len(queue) - - for _ in range(size): - v = queue.popleft() - - for next in [v-1, v+1, v*2]: - if 0<= next <= 100000 and time + 1 <= visited[next]: - ways[next] += 1 - visited[next] = time + 1 - - if next == k: - success = True - - if not success: - queue.append(next) - time += 1 - - return visited[k], ways[k] -if n >= k: - print(n-k) - print(1) -else: - time, count = bfs(n) - print(time) +import sys +from collections import deque +input = sys.stdin.readline + +n, k = list(map(int, input().split())) + +def bfs(n): + # visited[next] : next 까지 오는데 얼마의 최소 time을 저장. + # ways[next] : next 까지 최소 time으로 오는 방법의 수 저장. + q, visited, ways = deque([n]), [float('inf')]*100001, [0]*100001 + time, success = 0, False + ways[n] = 1 + visited[n] = 0 + +# 한 size씩 측정해 그 사이즈까지만 돌리고 성공했으면 빠져나옴. + while q and not success: + size = len(q) + + for _ in range(size): + v = q.popleft() + + for next in [v-1, v+1, v*2]: + if 0<= next <= 100000 and time + 1 <= visited[next]: + ways[next] += 1 + visited[next] = time + 1 + + if next == k: + success = True + + if not success: + q.append(next) + time += 1 + + return visited[k], ways[k] +if n >= k: + print(n-k) + print(1) +else: + time, count = bfs(n) + print(time) print(count) \ No newline at end of file diff --git "a/12852 1\353\241\234\353\247\214\353\223\244\352\270\2602.py" "b/12852 1\353\241\234\353\247\214\353\223\244\352\270\2602.py" deleted file mode 100644 index a73edef..0000000 --- "a/12852 1\353\241\234\353\247\214\353\223\244\352\270\2602.py" +++ /dev/null @@ -1,20 +0,0 @@ -N = int(input()) - -dp = [[0,[]] for _ in range(N+1)] - - -dp[1][0] = 0 -dp[1][1] = [1] -if N>1: - for i in range(2,N+1): - dp[i][0] = dp[i-1][0]+1 - dp[i][1] = dp[i-1][1] + [i] - - if not i%3 and dp[i//3][0]+1 < dp[i][0]: - dp[i][0] = dp[i//3][0]+1 - dp[i][1] = dp[i//3][1]+[i] - if not i%2 and dp[i//2][0]+1 < dp[i][0]: - dp[i][0] = dp[i//2][0]+1 - dp[i][1] = dp[i//2][1]+[i] -print(dp[N][0]) -print(*dp[N][1][::-1]) \ No newline at end of file diff --git "a/12865\355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.py" "b/12865\355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.py" deleted file mode 100644 index 9423f99..0000000 --- "a/12865\355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) -wei_cost = [[0,0]] -dp = [[0 for _ in range(K + 1)] for _ in range(N + 1)] - -for _ in range(N): - wei_cost.append(list(map(int, input().split()))) - - -for i in range(1, N + 1): - for j in range(1, K + 1): - weight = wei_cost[i][0] - cost = wei_cost[i][1] - if j < weight: - dp[i][j] = dp[i - 1][j] - else: - dp[i][j] = max(cost + dp[i - 1][j - weight], dp[i - 1][j]) - -print(dp[N][K]) diff --git "a/12871 \353\254\264\355\225\234\353\254\270\354\236\220\354\227\264.py" "b/12871 \353\254\264\355\225\234\353\254\270\354\236\220\354\227\264.py" deleted file mode 100644 index 4fdea0d..0000000 --- "a/12871 \353\254\264\355\225\234\353\254\270\354\236\220\354\227\264.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline -from math import gcd - -s = input().rstrip() -t = input().rstrip() -n = len(s) -m = len(t) -a = gcd(n,m) -if s*(m//a) == t*(n//a): - print(1) -else: - print(0) \ No newline at end of file diff --git "a/12896 \354\212\244\355\201\254\353\243\250\354\247\200 \353\257\274\355\230\270_\353\257\274\352\265\254\353\213\230 \355\222\200\354\235\264.py" "b/12896 \354\212\244\355\201\254\353\243\250\354\247\200 \353\257\274\355\230\270_\353\257\274\352\265\254\353\213\230 \355\222\200\354\235\264.py" deleted file mode 100644 index a89b599..0000000 --- "a/12896 \354\212\244\355\201\254\353\243\250\354\247\200 \353\257\274\355\230\270_\353\257\274\352\265\254\353\213\230 \355\222\200\354\235\264.py" +++ /dev/null @@ -1,42 +0,0 @@ -''' -첫번째 접근 : 각 정점마다 가장 먼 거리 하나씩 뽑아서 그거 min 하면 시간 맞으려나 -N = 10만 > 네 시간 초과 -두번째 접근 : 간선 거리가 1이면 트리의 지름 구한거 /2하면 끝아님? -''' - -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(start): - visited = [0] * (N+1) - distance = [0] * (N+1) - q = deque() - q.append(start) - visited[start] = 1 - - # 노드, 거리 기록 - far_max = [0,0] - - while q: - x = q.popleft() - for next in graph[x]: - if not visited[next]: - distance[next] = distance[x] + 1 - visited[next] = 1 - q.append(next) - if far_max[1] < distance[next]: - far_max[1] = distance[next] - far_max[0] = next - return far_max - -N = int(input()) -graph = [[] for _ in range(N+1)] - -for _ in range(N-1): - a, b = map(int,input().split()) - graph[a].append(b) - graph[b].append(a) - -print((bfs(bfs(1)[0])[1] + 1)//2) - diff --git "a/1289\355\212\270\353\246\254\354\235\230 \352\260\200\354\244\221\354\271\230.py" "b/1289\355\212\270\353\246\254\354\235\230 \352\260\200\354\244\221\354\271\230.py" deleted file mode 100644 index b507f1e..0000000 --- "a/1289\355\212\270\353\246\254\354\235\230 \352\260\200\354\244\221\354\271\230.py" +++ /dev/null @@ -1,84 +0,0 @@ -import sys -input =sys.stdin.readline -sys.setrecursionlimit(10**6) - -# dp[u]는 노드 u가 루트인 subtree에서 u부터 다른 모든 노드 까지 가는 모든 경로들의 곱의 합. -# 즉 (dp[v] * c) 들의 합. 그 값을 리스트 p에 저장해뒀다가 모든 값들에 대해 (dp[u] - dp[v]*c)*(c*dp[v])들의 합을 구해준다. -# 그 후 중복을 제거하기 위해 나누기 2를 해줘야 하나 MOD의 반인 500000004를 곱하고 MOD로 나눔으로써 2로 나누는 것과 같은 효과를 얻을 수 있다. -def dfs(u): - global ans - visited[u] = True - p = [] - for i in range(len(edges[u])): - v = edges[u][i] - c = costs[u][i] - if visited[v]: - continue - - dfs(v) - dp[u] += (dp[v] * c) % MOD - dp[u] %= MOD - - p.append((dp[v] * c) % MOD) - ans += dp[u] - ans %= MOD - - sum_v = 0 - # (ab+ac+ad+bc+bd+cd) = ((a+b+c+d)^2-(a^2+b^2+c^2+d^2))/2 를 사용해 시간복잡도를 O(n^2)에서 O(n)으로 바꿈. - for v in p: - sum_v += ((dp[u] - v + MOD) % MOD * v) % MOD - sum_v %= MOD - - sum_v *= 500000004 - sum_v %= MOD - - ans += sum_v - ans %= MOD - - dp[u] += 1 - dp[u] %= MOD - - -MOD = 1000000007 -N = int(input()) -ans = 0 -visited = {i: False for i in range(1,N+1)} -dp = [0 for _ in range(N+1)] -edges = {i: [] for i in range(1,N+1)} -costs = {i: [] for i in range(1,N+1)} -for _ in range(N-1): - a, b, c = map(int, input().split()) - edges[a].append(b) - edges[b].append(a) - costs[a].append(c) - costs[b].append(c) - -dfs(1) -print(ans) - - -# 다른사람 코드 -import sys -sys.setrecursionlimit(100000) -n = int(sys.stdin.readline()) -mod = 1000000007 -adj = [[] for _ in range(n + 1)] -for i in range(n - 1): - a, b, c = map(int, sys.stdin.readline().split()) - adj[a].append((b, c)) - adj[b].append((a, c)) -ans = 0 -def go(now, past): - global ans - pow = 1 - for i in adj[now]: - next = i[0] - next_cost = i[1] - if next != past: - extra_cost = (go(next, now) * next_cost) % mod - ans = (ans + extra_cost * pow) % mod - pow = (pow + extra_cost) % mod - return pow - -go(1,-1) -print(ans) \ No newline at end of file diff --git a/128_A.py b/128_A.py deleted file mode 100644 index c236910..0000000 --- a/128_A.py +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - l1, r1, l2, r2 = map(int, input().split()) - candi = set() - for num in range(l1, r1 + 1): - candi.add(num) - for num in range(l2, r2 + 1): - if num in candi: - print(num) - break - else: - print(l1 + l2) diff --git a/128_B.py b/128_B.py deleted file mode 100644 index 85e068d..0000000 --- a/128_B.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - - -def isCheck(): - for i in range(n): - for j in range(m): - if matrix[i][j] == "R": - for i2 in range(i + 1, n): - for j2 in range(j): - if matrix[i2][j2] == "R": - return False - return True - return False - - -for _ in range(int(input())): - n, m = map(int, input().split()) - matrix = [input().rstrip() for _ in range(n)] - print("YES" if isCheck() else "NO") - diff --git a/128_C.py b/128_C.py deleted file mode 100644 index cd85e33..0000000 --- a/128_C.py +++ /dev/null @@ -1,12 +0,0 @@ -for _ in range(int(input())): - s = input().strip().strip('0') - z = s.count('0') - a = list(map(len, s.split('1')))[1:-1] - best, r, sm, n = z, 0, 0, len(a) - for l in range(len(a)): - while r < n and sm + a[r] <= n - r + l: - sm += a[r] - r += 1 - best = min(best, max(sm, n - r + l)) - sm -= a[l] - print(best) \ No newline at end of file diff --git a/128_D.py b/128_D.py deleted file mode 100644 index 6b388ef..0000000 --- a/128_D.py +++ /dev/null @@ -1,23 +0,0 @@ -n, k = map(int, input().split()) -n += 1 -a = list(map(int, input().split())) -a.insert(0, 0) -p, q = [0]*n, [0]*n - -for i in range(1, n): - p[i], q[i] = p[i-1] + (a[i] == 0), q[i-1] + a[i] - -s, r = q[n-1], -1 -for t in range(2): - for i in range(n): - for j in range(i+1, n): - c = p[j]-p[i] - x = p[n-1]-c - v = 0 - if t == 0: - v = max(-c*k, min(c*k, x*k-s)) - else: - v = min(c*k, max(-c*k, -s-x*k)) - if s-x*k+v <= 0 and 0 <= s+x*k+v: - r = max(r, 1 + abs(q[j] - q[i] + v)) -print(r) \ No newline at end of file diff --git a/128_D2.py b/128_D2.py deleted file mode 100644 index d71496a..0000000 --- a/128_D2.py +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - - -def ProGamerMove(): - n, k = map(int, input().split()) - a = list(map(int, input().split())) - zeros = a.count(0) - sm = sum(a) - s1, s2 = 0, 0 - c1, c2 = 0, 0 - res = -2 - - def intersect(m1, b1, m2, b2): - l1, r1 = m1 - b1 * k, m1 + b1 * k - l2, r2 = m2 - b2 * k, m2 + b2 * k - return not (r1 < l2 or r2 < l1) - - for l in range(0, n + 1): - s2, c2 = 0, 0 - for r in range(0, n + 1): - if l <= r: - b1, b2, b3 = c1, c2 - c1, zeros - c2 - m1, m2, m3 = s1, s2 - s1, sm - s2 - # b1 + b3 == -b2 - # min b1, b3 - if not intersect(m1 + m3, b1 + b3, -m2, b2): continue - r1 = max(m1 + m3 - (b1 + b3) * k, -m2 - b2 * k) - r2 = min(m1 + m3 + (b1 + b3) * k, -m2 + b2 * k) - res = max(res, abs(r1), abs(r2)) - if r < n: - s2 += a[r] - c2 += a[r] == 0 - if l < n: - s1 += a[l] - c1 += a[l] == 0 - print(res + 1) - - -n = 1 -# n = int(input()) -for _ in range(0, n): ProGamerMove() \ No newline at end of file diff --git "a/1300K\353\262\210\354\247\270\354\210\230.py" "b/1300K\353\262\210\354\247\270\354\210\230.py" deleted file mode 100644 index 0dfb7b0..0000000 --- "a/1300K\353\262\210\354\247\270\354\210\230.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -k = int(input()) - -start = 1 -end = k -# k번째의 '값'을 찾기위한 탐색. start와 end가 만나는 지점에 mid값이 k번째로 정렬된 수 이다. -while start <= end: - mid = (start+end)//2 - - cnt = 0 - # 우리가 찾으려는 값 mid를 i로 나눴을 때 i번째 행에서 나보다 작은 갯수가 나온다. - # 여기서 N*N이므로 행의 최대갯수인N은 넘을 수 없다. - # 계산 끝나면 mid가 N*N에서 몇번째로 큰 숫자인지 알 수 있다. - for i in range(1,N+1): - cnt += min(mid//i,N) - # cnt가 k이상이라면 cnt값을 줄이기위해 앞쪽 라인을 검사하러 간다. - # cnt값을 k에 수렴시키다보면 mid는 결국 앞에서 k번째 값에 수렴하게 된다. - if cnt >= k: - answer = mid - end = mid-1 - else: - start = mid+1 - -print(answer) \ No newline at end of file diff --git a/13023ABCDE.py b/13023ABCDE.py index e36b6e2..af6b61a 100644 --- a/13023ABCDE.py +++ b/13023ABCDE.py @@ -1,30 +1,36 @@ -import sys -from collections import defaultdict -input = sys.stdin.readline - -N,M = map(int, input().split()) -check = [False]*N -graph = defaultdict(list) -cnt = 0 - -for _ in range(M): - a,b = map(int,input().split()) - graph[a] += [b] - graph[b] += [a] - -def DFS(v,h): - if h==4: - print(1) - exit() - for i in graph[v]: - if check[i]==False: - check[i] = True - DFS(i, h+1) - check[i]=False - -for i in range(N): - check[i] = True - DFS(i,0) - check[i]= False - +import sys +from collections import defaultdict +input = sys.stdin.readline + +N,M = map(int, input().split()) +check = [False]*N +graph = defaultdict(list) +cnt = 0 + +for _ in range(M): + a,b = map(int,input().split()) + graph[a] += [b] + graph[b] += [a] + +# 방문, graph[v]안의 노드들 돌아가면서 검사 노드하나들어가서 +# False면 True방문하고 DFS로 파고들고 h하나 늘리고. +# 끝까지 갔는데 못찾으면 check하나씩 False로 되돌리면서 나오기 +# 이런식으로 모든 경로 깊이 탐색. + +def DFS(v,h): + if h==4: + print(1) + exit() + for i in graph[v]: + if check[i]==False: + check[i] = True + DFS(i, h+1) + check[i]=False + +# 최초 몇번노드로 들어갈 것인지?0~N-1 +for i in range(N): + check[i] = True + DFS(i,0) + check[i]= False + print(0) \ No newline at end of file diff --git "a/1302\353\262\240\354\212\244\355\212\270\354\205\200\353\237\254.py" "b/1302\353\262\240\354\212\244\355\212\270\354\205\200\353\237\254.py" deleted file mode 100644 index 615a055..0000000 --- "a/1302\353\262\240\354\212\244\355\212\270\354\205\200\353\237\254.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -N = int(input()) -sell = defaultdict(int) -for __ in range(N): - book = input().rstrip() - sell[book] += 1 - -arr_for_sort = [] -for book in sell: - arr_for_sort.append((sell[book], str(book))) - -arr_for_sort.sort(key=lambda x: (-x[0], x[1])) -print(arr_for_sort[0][1]) \ No newline at end of file diff --git "a/1305\352\264\221\352\263\240.py" "b/1305\352\264\221\352\263\240.py" deleted file mode 100644 index b8f4df2..0000000 --- "a/1305\352\264\221\352\263\240.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -L = int(input()) # 광고판 길이 -string = input().rstrip() # 광고판 문자열 -string_length = len(string) - -# 실패함수 ( KMP 패턴 부분 일치 테이블 만들기) -pattern_table = [0 for _ in range(string_length)] -count = 0 -for idx in range(1, string_length): - while count > 0 and string[idx]!=string[count]: - count = pattern_table[count-1] - if string[idx]==string[count]: - count+=1 - pattern_table[idx] = count - -pattern_length = string_length - pattern_table[string_length-1] # 가장짧은 광고길이 -print(pattern_length) \ No newline at end of file diff --git "a/1306\353\213\254\353\240\244\353\235\274\355\231\215\354\244\200_\354\204\270\352\267\270\355\212\270\353\246\254.py" "b/1306\353\213\254\353\240\244\353\235\274\355\231\215\354\244\200_\354\204\270\352\267\270\355\212\270\353\246\254.py" deleted file mode 100644 index 227042a..0000000 --- "a/1306\353\213\254\353\240\244\353\235\274\355\231\215\354\244\200_\354\204\270\352\267\270\355\212\270\353\246\254.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline - -seg = [0 for _ in range(4040404)] - -# 최댓값 세그트리 만들기. -def init(n,s,e): - if s == e: - seg[n] = a[s-1] - return seg[n] - mid = (s+e)//2 - seg[n] = max( init(n*2,s,mid), init(n*2+1,mid+1,e) ) - return seg[n] - - -def getMax(n,l,r,s,e): - if e < l or r < s: return 0 - if l <= s and e <= r: return seg[n] - mid = (s+e)//2 - return max( getMax(n*2,l,r,s,mid), getMax(n*2+1,l,r,mid+1,e) ) - -n, m = map(int, input().split()) -p = m*2-1 # 시야범위 -a = list(map(int, input().split())) -ans = [] - -init(1,1,n) - -for i in range(n-p+1): - ans.append(getMax(1,1+i,i+p,1,n)) -print(*ans) \ No newline at end of file diff --git "a/1309\353\217\231\353\254\274\354\233\220.py" "b/1309\353\217\231\353\254\274\354\233\220.py" deleted file mode 100644 index 407b6e6..0000000 --- "a/1309\353\217\231\353\254\274\354\233\220.py" +++ /dev/null @@ -1,10 +0,0 @@ -N = int(input()) -dp = [0] * 100001 - -dp[1] = 3 -dp[2] = 7 -for i in range(3, N+1): - dp[i] = (dp[i-1]*2 + dp[i-2])%9901 - -print(dp[N]) - diff --git "a/1316\352\267\270\353\243\271\353\213\250\354\226\264\354\262\264\354\273\244.py" "b/1316\352\267\270\353\243\271\353\213\250\354\226\264\354\262\264\354\273\244.py" deleted file mode 100644 index abbae76..0000000 --- "a/1316\352\267\270\353\243\271\353\213\250\354\226\264\354\262\264\354\273\244.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline -N = int(input()) -cnt=0 -for _ in range(N): - chr_set = {i:0 for i in range(97,123)} - word = input().rstrip() - for i in range(len(word)): - if chr_set[ord(word[i])]==1: - break - if i 틀린풀이. -# import sys -# from collections import deque -# input = sys.stdin.readline - -# N, M = map(int, input().split()) -# parents = {i: [] for i in range(1,N+1)} -# childs = {i: 1 for i in range(1,N+1)} -# level = {i: 0 for i in range(1,N+1)} -# for _ in range(M): -# a, b = map(int, input().split()) -# parents[a] += [b] -# level[b] += 1 -# queue = deque() -# for i in range(1,N+1): -# if not level[i]: -# queue.append(i) - -# while queue: -# cur_node = queue.popleft() -# for next_node in parents[cur_node]: -# level[next_node] -= 1 -# childs[next_node] += childs[cur_node] -# if not level[next_node]: -# queue.append(next_node) - -# max_num = 0 -# ans = [] -# for node in childs: -# if childs[node] > max_num: -# max_num = childs[node] -# ans.clear() -# ans.append(node) -# elif childs[node] == max_num: -# ans.append(node) -# print(*ans) - - -from collections import deque -import sys -input = sys.stdin.readline -def bfs(start): - q = deque() - q.append(start) - visit = [0 for _ in range(n + 1)] - visit[start] = 1 - cnt = 1 - while q: - st = q.popleft() - for i in s[st]: - if visit[i] == 0: - visit[i] = 1 - cnt += 1 - q.append(i) - return cnt -n, m = map(int, input().split()) -s = [[] for i in range(n + 1)] -for i in range(m): - a, b = map(int, input().split()) - s[b].append(a) -result = [] -max_cnt = 0 -for i in range(1, n + 1): - tmp = bfs(i) - if max_cnt == tmp: - result.append(i) - if max_cnt < tmp: - max_cnt = tmp - result = [] - result.append(i) -print(*result) \ No newline at end of file diff --git "a/13275\352\260\200\354\236\245 \352\270\264 \355\214\260\353\246\260\353\223\234\353\241\254 \353\266\200\353\266\204 \353\254\270\354\236\220\354\227\264.py.py" "b/13275\352\260\200\354\236\245 \352\270\264 \355\214\260\353\246\260\353\223\234\353\241\254 \353\266\200\353\266\204 \353\254\270\354\236\220\354\227\264.py.py" deleted file mode 100644 index 5e49ac5..0000000 --- "a/13275\352\260\200\354\236\245 \352\270\264 \355\214\260\353\246\260\353\223\234\353\241\254 \353\266\200\353\266\204 \353\254\270\354\236\220\354\227\264.py.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - - -def manacher(string): - n = len(string) - a = [0] * n # i번째 문자를 중심으로 하는 가장 긴 팰린드롬 반지름 크기. - c = 0 # 중심점(center) 초기화 - r = 0 # 시작점에서 가장 먼 반경(펠린드롬 끝나는 인덱스중 가장 큰 값.) - - for now in range(n): - # i번째 문자가 now 아래쪽에 있는 문자를 중심으로 하는 팰린드롬 범위 밖의 문자라는 뜻. - # 때문에 now 이전에 얻은 정보를 재활용하지 못하고 i를 기준으로 초기화시켜 재계산함. - if r < now: - a[now] = 0 - # i번째 문자가 i미만의 문자를 중심으로 하는 팰린드롬에 속한다면? - # 1. i를 중심으로 하는 가장 긴 팰린드롬이 기존 최장 팰린드롬인 c를 중심으로 하는 가장 긴 팰린드롬에 완전히 속하는 경우 -> i의 c점에 대한 대칭점 now'을 기준으로 하는 펠린드롬은 i를 기준으로 하는 팰린드롬과 완전한 대칭. a[now]=a[now']인데 p[now']은 이전에 구해놓았기 때문에 연산 안해도됨. - # 2. i를 중심으로 하는 가장 긴 팰린드롬이 c를 중심으로 한느 가장 긴 팰린드롬에 일부만 포함된느 경우 -> 초기 반지름 a[now] = ((c+a[c])-now)가 보장이됨(가장 긴 펠린드롬의 오른쪽 한계로부터 i만큼 왼쪽으로 줄인 반지름에서 (c+a[c])-now+1부터 비교 시작) - # 3. i를 중심으로 한느 가장 긴 팰린드롬이 c < i인 c를 중심으로 하는 가장 긴 팰린드롬과 겹치는 경우. (c의 날개와 i의 날개가 동일지점인 경우) - # 역시 case 2처럼 a[now] = ((c+a[c])-now)만큼의 반지름이 보장이 됨. 그 이후로 부터 비교하면 됨. now'은 (2*c)-i이므로 now'의 날개와 r-i값중 더 작은 곳을 보장받고 움직이면 됨. - else: - a[now] = min(a[(2*c) - now], r - now) - - # i번째 인덱스 기준 가장 긴 펠린드롬 반지름을 펼쳤을 시 0~len(s)의 범위 안에 존재해야하며 - # i기준 a[now](반지름)만큼 펼친 그 양옆문자도 같으면?(-1.+1인덱스가 같으면) - # a[now]+1(반지름 확장) - while(now-a[now]-1>=0 and now+a[now]+1 < n and string[now-a[now]-1] == string[now+a[now]+1]): - a[now] = a[now] + 1 - # 시작점에서 가장 먼 반경인 now + a[now]가 기존 최장 반지름 길이 r보다 크므로 - # r초기화, 중심점 c는 현재 최장 펠린드롬의 중심점인 i로 초기화. - # 결국 r,c는 현 시점에서 가장 먼 팰린드롬의 날개값(가장 멀리갈때 초기화됨.) - # a[now]가 0이어도 r보다 i가 커지면 갱신됨. - if (r < now + a[now]): - r = now + a[now] - c = now - return max(a) - -s = input().rstrip() -print(manacher('#' + '#'.join(s)+'#')) \ No newline at end of file diff --git "a/13300\353\260\251\353\260\260\354\240\225.py" "b/13300\353\260\251\353\260\260\354\240\225.py" deleted file mode 100644 index 55e2f5c..0000000 --- "a/13300\353\260\251\353\260\260\354\240\225.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) -students = [[0,0] for _ in range(6)] -for _ in range(N): - S, Y = map(int, input().split()) - students[Y-1][S] += 1 -answer = 0 -for grade in students: - for sex in grade: - answer += sex//K - if sex%K: - answer += 1 -print(answer) \ No newline at end of file diff --git "a/13334\354\262\240\353\241\234.py" "b/13334\354\262\240\353\241\234.py" deleted file mode 100644 index 54f0980..0000000 --- "a/13334\354\262\240\353\241\234.py" +++ /dev/null @@ -1,56 +0,0 @@ -import sys -input = sys.stdin.readline -import heapq - -n = int(input()) -road_info = [] -for _ in range(n): - road = list(map(int, input().split())) - road_info.append(road) - -d = int(input()) -roads = [] -for road in road_info: - house, office = road - if abs(house - office) <= d: - road = sorted(road) - roads.append(road) -roads.sort(key=lambda x:x[1]) - -answer = 0 -heap = [] -for road in roads: - if not heap: - heapq.heappush(heap, road) - else: - while heap[0][0] < road[1] - d: - heapq.heappop(heap) - if not heap: - break - heapq.heappush(heap, road) - answer = max(answer, len(heap)) - -print(answer) - -# 다른풀이 -import sys -input = sys.stdin.readline -from heapq import heappush, heappop - -def solution(n): - lst = [sorted(list(map(int, input().split()))) for i in range(n)] - lst.sort(key=lambda x: x[1]) - d = int(input()) - result = -1 - heap = [] - for s, e in lst: - lim = e - d - if s >= lim: - heappush(heap, s) - while heap and heap[0] < lim: - heappop(heap) - result = max(result, len(heap)) - print(result) - -if __name__ == '__main__': - solution(int(input())) \ No newline at end of file diff --git "a/13398\354\227\260\354\206\215\355\225\251.py" "b/13398\354\227\260\354\206\215\355\225\251.py" index 0e449c4..2b3cd0e 100644 --- "a/13398\354\227\260\354\206\215\355\225\251.py" +++ "b/13398\354\227\260\354\206\215\355\225\251.py" @@ -1,21 +1,21 @@ -n = int(input()) -lst = list(map(int, input().split())) - -# 원소 제외 없는 결과, 원소 하나 제외한 결과 -dp = [[0, 0] for _ in range(n)] -# 초깃값 : 나자신 or 나를 제외한 경우. -dp[0] = [lst[0], -999999999] - -for i in range(1, n): - # 끊고 출발하거나 이전에꺼에 덧붙히거나. - dp[i][0] = max(dp[i - 1][0] + lst[i], lst[i]) - # 이전까지의 합에 나를 제외한 경우.(+0이 생략된 값을 이어붙힘), 이전까지의 합에 나를 붙힌경우(생략x) - # => 앞에서 -가 생략이 됐고 그게 최적이라면 dp[i-1][1]+lst[i]가 더 커야하고 아니라면 - # 앞의 생략이 최적이 아니므로 dp[i-1][0]의 생략 안된 값을 가져와 나를 생략하고 저장하게 됨. - # 즉 생략 안된 list로 부터 나를 제외 한 값과 아닌 값을 유지해 나가며 비교하면 최적값을 구할 수 있음. - dp[i][1] = max(dp[i - 1][0], dp[i - 1][1] + lst[i]) - -ans = -999999999 -for i in range(n): - ans = max(ans, dp[i][0], dp[i][1]) -print(ans) +n = int(input()) +lst = list(map(int, input().split())) + +# 원소 제외 없는 결과, 원소 하나 제외한 결과 +dp = [[0, 0] for _ in range(n)] +# 초깃값 : 나자신 or 나를 제외한 경우. +dp[0] = [lst[0], -999999999] + +for i in range(1, n): + # 끊고 출발하거나 이전에꺼에 덧붙히거나. + dp[i][0] = max(dp[i - 1][0] + lst[i], lst[i]) + # 이전까지의 합에 나를 제외한 경우.(+0이 생략된 값을 이어붙힘), 이전까지의 합에 나를 붙힌경우(생략x) + # => 앞에서 -가 생략이 됐고 그게 최적이라면 dp[i-1][1]+lst[i]가 더 커야하고 아니라면 + # 앞의 생략이 최적이 아니므로 dp[i-1][0]의 생략 안된 값을 가져와 나를 생략하고 저장하게 됨. + # 즉 생략 안된 list로 부터 나를 제외 한 값과 아닌 값을 유지해 나가며 비교하면 최적값을 구할 수 있음. + dp[i][1] = max(dp[i - 1][0], dp[i - 1][1] + lst[i]) + +ans = -999999999 +for i in range(n): + ans = max(ans, dp[i][0], dp[i][1]) +print(ans) diff --git "a/13418 \355\225\231\352\265\220\355\203\220\353\260\251\355\225\230\352\270\260.py" "b/13418 \355\225\231\352\265\220\355\203\220\353\260\251\355\225\230\352\270\260.py" deleted file mode 100644 index 4a04d8d..0000000 --- "a/13418 \355\225\231\352\265\220\355\203\220\353\260\251\355\225\230\352\270\260.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline -def find(x): - if parent[x] == x: - return x - parent[x] = find(parent[x]) - return parent[x] - -def union(a,b): - a = find(a) - b = find(b) - - if level[a] >= level[b]: - parent[b] = a - if level[a]==level[b]: - level[a] +=1 - else: - parent[a] = b - -N, M = map(int, input().split()) -parent = {i:i for i in range(N+1)} -level = {i:0 for i in range(N+1)} -edges = [] -for _ in range(M+1): - a, b, c = map(int, input().split()) - edges.append([c,a,b]) -edges.sort() -ascend = 0 -for i in range(M+1): - cost, a, b = edges[i] - if find(a) != find(b): - union(a,b) - ascend += cost -parent = {i:i for i in range(N+1)} -level = {i:0 for i in range(N+1)} -decend = 0 -for i in range(M,-1,-1): - cost, a, b = edges[i] - if find(a) != find(b): - union(a,b) - decend += cost -print((N-ascend)**2 - (N-decend)**2) \ No newline at end of file diff --git "a/13424\353\271\204\353\260\200\353\252\250\354\236\204.py" "b/13424\353\271\204\353\260\200\353\252\250\354\236\204.py" index a9c6cdf..3a5a08f 100644 --- "a/13424\353\271\204\353\260\200\353\252\250\354\236\204.py" +++ "b/13424\353\271\204\353\260\200\353\252\250\354\236\204.py" @@ -1,54 +1,54 @@ -import sys -input = sys.stdin.readline -from heapq import heappop, heappush -from collections import defaultdict - - - - -# 각 친구들 위치에서 모든 방에 대해 최소거리 배열 출력. -def dijkstra(start): - global dp_dists - dp_dists = [float('inf')] * (N + 1) - heap = [] - dp_dists[start] = 0 - heappush(heap, [dp_dists[start], start]) - while heap: - cur_dist, cur_node = heappop(heap) - if dp_dists[cur_node] < cur_dist: - continue - for next_node, next_dist in graph[cur_node]: - dist = next_dist + cur_dist - if dist < dp_dists[next_node]: - dp_dists[next_node] = dist - heappush(heap, [dist, next_node]) - return dp_dists - - -# N개의 방(1~N번) -# M개의 통로(양방향), 가중치 -# 친구 K명 -for test in range(int(input())): - N,M = map(int,input().split()) - graph = defaultdict(list) - - for _ in range(M): - a,b,dist = map(int,input().split()) - graph[a].append((b,dist)) - graph[b].append((a,dist)) - - - # 모든 친구들은 최단 경로를 이용해서 방으로 모일것임. - K = int(input()) - friends_start = list(map(int,input().split())) - sum_dists = [0]*(N+1) - for start in friends_start: - dijkstra(start) - for i in range(len(dp_dists)): - sum_dists[i] += dp_dists[i] - -# 모임장소는 모든 친구들의 이동경로 합이 최소가 되는 방. - for i in range(1,N+1): - if sum_dists[i] ==min(sum_dists): - print(i) +import sys +input = sys.stdin.readline +from heapq import heappop, heappush +from collections import defaultdict + + + +# 각 친구들 위치에서 모든 방에 대해 최소거리 배열 출력. +# 최소 거리 찾는 것이므로 나중에 min쓸꺼 대비해 누적거리는 inf부터 시작함. +def dijkstra(start): + global dp_dists + dp_dists = [float('inf')] * (N + 1) + heap = [] + dp_dists[start] = 0 + heappush(heap, [dp_dists[start], start]) + while heap: + cur_dist, cur_node = heappop(heap) + if dp_dists[cur_node] < cur_dist: + continue + for next_node, next_dist in graph[cur_node]: + dist = next_dist + cur_dist + if dist < dp_dists[next_node]: + dp_dists[next_node] = dist + heappush(heap, [dist, next_node]) + return dp_dists + + +# N개의 방(1~N번) +# M개의 통로(양방향), 가중치 +# 친구 K명 +for test in range(int(input())): + N,M = map(int,input().split()) + graph = defaultdict(list) + + for _ in range(M): + a,b,dist = map(int,input().split()) + graph[a].append((b,dist)) + graph[b].append((a,dist)) + + + # 모든 친구들은 최단 경로를 이용해서 방으로 모일것임. + K = int(input()) + friends_start = list(map(int,input().split())) + sum_dists = [0]*(N+1) + for start in friends_start: + dijkstra(start) + for i in range(len(dp_dists)): + sum_dists[i] += dp_dists[i] + + # 모임장소는 모든 친구들의 이동경로 합이 최소가 되는 방. + for i in range(1,N+1): + if sum_dists[i] ==min(sum_dists): + print(i) break \ No newline at end of file diff --git "a/1342\355\226\211\354\232\264\354\235\230\353\254\270\354\236\220\354\227\264.py" "b/1342\355\226\211\354\232\264\354\235\230\353\254\270\354\236\220\354\227\264.py" index 242e643..749758e 100644 --- "a/1342\355\226\211\354\232\264\354\235\230\353\254\270\354\236\220\354\227\264.py" +++ "b/1342\355\226\211\354\232\264\354\235\230\353\254\270\354\236\220\354\227\264.py" @@ -1,41 +1,41 @@ -from sys import stdin -input = stdin.readline - -def dfs(depth, string): - global N, ret, charSet, cntMap - - if depth == N: - # print(string) - ret += 1 - return - - for char in charSet: - idx = ord(char) - ord('a') - # 알파뱃 카운트가 0이면 그 알파뱃으로 돌지 않는다. - if cntMap[idx] == 0: - continue - # 중요한게 string''면 -1인덱스 오류날텐데 string존재여부를 앞에 두어 없으면 앞에서 False나서 돌아가게 설계.! 기억할것. - # 문자열이 존재하고 문자열 -1값이 알파뱃이랑 같으면 돌지 않는다. - if string and string[-1] == char: - continue - # 문자열이 비었거나 알파뱃카운트가 있고 전이랑 지금알파뱃이 다를때. - # 알파뱃 카운트 컨트롤, depth늘려주며 길이 체크, string에 문자추가. - cntMap[idx] -= 1 - dfs(depth + 1, string + char) - cntMap[idx] += 1 - - -raw = input().strip() -cntMap = [0] * 26 -N = len(raw) -ret = 0 -charSet = set() - -for char in raw: - idx = ord(char) - ord('a') - cntMap[idx] = cntMap[idx] + 1 - charSet.add(char) -# print(charSet, cntMap, cntSum) - -dfs(0, '') +from sys import stdin +input = stdin.readline + +def dfs(depth, string): + global N, ret, charSet, cntMap + + if depth == N: + # print(string) + ret += 1 + return + + for char in charSet: + idx = ord(char) - ord('a') + # 알파뱃 카운트가 0이면 그 알파뱃으로 돌지 않는다. + if cntMap[idx] == 0: + continue + # 중요한게 string''면 -1인덱스 오류날텐데 string존재여부를 앞에 두어 없으면 앞에서 False나서 돌아가게 설계.! 기억할것. + # 문자열이 존재하고 문자열 -1값이 알파뱃이랑 같으면 돌지 않는다. + if string and string[-1] == char: + continue + # 문자열이 비었거나 알파뱃카운트가 있고 전이랑 지금알파뱃이 다를때. + # 알파뱃 카운트 컨트롤, depth늘려주며 길이 체크, string에 문자추가. + cntMap[idx] -= 1 + dfs(depth + 1, string + char) + cntMap[idx] += 1 + + +raw = input().strip() +cntMap = [0] * 26 +N = len(raw) +ret = 0 +charSet = set() + +for char in raw: + idx = ord(char) - ord('a') + cntMap[idx] = cntMap[idx] + 1 + charSet.add(char) +# print(charSet, cntMap, cntSum) + +dfs(0, '') print(ret) \ No newline at end of file diff --git "a/1343\355\217\264\353\246\254\354\230\244\353\257\270\353\205\270.py" "b/1343\355\217\264\353\246\254\354\230\244\353\257\270\353\205\270.py" deleted file mode 100644 index 25fa353..0000000 --- "a/1343\355\217\264\353\246\254\354\230\244\353\257\270\353\205\270.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -s = input().rstrip() + '.' -answer='' -cnt=0 -for chr in s: - if chr=='X': - cnt+=1 - if cnt==4: - answer+='AAAA' - cnt=0 - else: - if cnt==2: - answer+='BB.' - cnt=0 - elif cnt==0: - answer+='.' - else: - print(-1) - exit() -print(answer[:-1]) \ No newline at end of file diff --git "a/13458\354\213\234\355\227\230\352\260\220\353\217\205.py" "b/13458\354\213\234\355\227\230\352\260\220\353\217\205.py" deleted file mode 100644 index bf4edc8..0000000 --- "a/13458\354\213\234\355\227\230\352\260\220\353\217\205.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline -from math import ceil - -N = int(input()) -A = list(map(int,input().split())) -B,C = map(int,input().split()) -cnt=0 -for i in range(N): - if A[i]-B>0: - cnt+=ceil((A[i]-B)/C) - cnt+=1 - -print(cnt) \ No newline at end of file diff --git "a/13459\352\265\254\354\212\254 \355\203\210\354\266\234.py" "b/13459\352\265\254\354\212\254 \355\203\210\354\266\234.py" deleted file mode 100644 index 27d02df..0000000 --- "a/13459\352\265\254\354\212\254 \355\203\210\354\266\234.py" +++ /dev/null @@ -1,64 +0,0 @@ -from collections import deque - - -# 벽이나 구멍이 나올때까지 굴린다. -# 굴린 거리만큼 c에 저장. -def move(i, j, dx, dy): - c = 0 - while s[i + dx][j + dy] != "#" and s[i][j] != "O": - i += dx - j += dy - c += 1 - return i, j, c - - -def bfs(): - - while q: - ri, rj, bi, bj, d = q.popleft() - # 10번 넘게 돌리면 종료. - if d > 10: - break - # 구슬 두개를 같이 돌린다. 매 분기마다 4방향을 모두 검사한다. - for i in range(4): - nri, nrj, rc = move(ri, rj, dx[i], dy[i]) - nbi, nbj, bc = move(bi, bj, dx[i], dy[i]) - # 파란구슬이 O가 아니면서 빨간구슬이 O면 종료. - if s[nbi][nbj] != "O": - if s[nri][nrj] == "O": - print(1) - return - # 아니면서 두 구슬의 위치가 겹칠때 이동한 거리가 긴놈을 -1칸 뒤로 위치시킴. - if nri == nbi and nrj == nbj: - if rc > bc: - nri -= dx[i] - nrj -= dy[i] - else: - nbi -= dx[i] - nbj -= dy[i] - # 똑같은 배치가 한번도 안나왔다면 분기로 진입. - if not visit[nri][nrj][nbi][nbj]: - visit[nri][nrj][nbi][nbj] = True - q.append([nri, nrj, nbi, nbj, d + 1]) - print(0) - - -n, m = map(int, input().split()) -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] -visit = [[[[False] * m for i in range(n)] for i in range(m)] for i in range(n)] -s = [] -# 구슬 최초위치 저장. -for i in range(n): - a = list(input()) - s.append(a) - for j in range(m): - if a[j] == "R": - ri, rj = i, j - if a[j] == "B": - bi, bj = i, j -q = deque() -# 탐색. -q.append([ri, rj, bi, bj, 1]) -visit[ri][rj][bi][bj] = True -bfs() \ No newline at end of file diff --git "a/13537 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2541.py" "b/13537 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2541.py" deleted file mode 100644 index 9e62f8b..0000000 --- "a/13537 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2541.py" +++ /dev/null @@ -1,486 +0,0 @@ -#!/usr/bin/env python -import os -import sys -from io import BytesIO, IOBase -from operator import add - -class SegmentTree: - def __init__(self, data, default=0, func=max): - """initialize the segment tree with data""" - self._default = default - self._func = func - self._len = len(data) - self._size = _size = 1 << (self._len - 1).bit_length() - - self.data = [default] * (2 * _size) - self.data[_size:_size + self._len] = data - for i in reversed(range(_size)): - self.data[i] = func(self.data[i + i], self.data[i + i + 1]) - - def __delitem__(self, idx): - self[idx] = self._default - - def __getitem__(self, idx): - return self.data[idx + self._size] - - def __setitem__(self, idx, value): - idx += self._size - self.data[idx] = value - idx >>= 1 - while idx: - self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) - idx >>= 1 - - def __len__(self): - return self._len - - def query(self, start, stop): - """func of data[start, stop)""" - start += self._size - stop += self._size - - res_left = res_right = self._default - while start < stop: - if start & 1: - res_left = self._func(res_left, self.data[start]) - start += 1 - if stop & 1: - stop -= 1 - res_right = self._func(self.data[stop], res_right) - start >>= 1 - stop >>= 1 - - return self._func(res_left, res_right) - - def __repr__(self): - return "SegmentTree({0})".format(self.data) - -def main(): - N = int(input()) - A = list(map(int,input().split())) - M = int(input()) - AA = SegmentTree([0] * N, func = add) - q1 = [] - for i in range(N): - q1.append((A[i], i)) - q2 = [] - ans = [0] * M - for i in range(M): - a,b,c = map(int,input().split()) - q2.append((c, a - 1, b, i)) - q1.sort() - q2.sort() - while q2: - while q1 and q1[-1][0] > q2[-1][0]: - AA[q1[-1][1]] = 1 - q1.pop() - ans[q2[-1][3]] = AA.query(q2[-1][1], q2[-1][2]) - q2.pop() - for elem in ans: - print(elem) - -# region fastio - -BUFSIZE = 8192 - - -class FastIO(IOBase): - newlines = 0 - - def __init__(self, file): - self._fd = file.fileno() - self.buffer = BytesIO() - self.writable = "x" in file.mode or "r" not in file.mode - self.write = self.buffer.write if self.writable else None - - def read(self): - while True: - b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) - if not b: - break - ptr = self.buffer.tell() - self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) - self.newlines = 0 - return self.buffer.read() - - def readline(self): - while self.newlines == 0: - b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) - self.newlines = b.count(b"\n") + (not b) - ptr = self.buffer.tell() - self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) - self.newlines -= 1 - return self.buffer.readline() - - def flush(self): - if self.writable: - os.write(self._fd, self.buffer.getvalue()) - self.buffer.truncate(0), self.buffer.seek(0) - - -class IOWrapper(IOBase): - def __init__(self, file): - self.buffer = FastIO(file) - self.flush = self.buffer.flush - self.writable = self.buffer.writable - self.write = lambda s: self.buffer.write(s.encode("ascii")) - self.read = lambda: self.buffer.read().decode("ascii") - self.readline = lambda: self.buffer.readline().decode("ascii") - - -sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) -input = lambda: sys.stdin.readline().rstrip("\r\n") - -# endregion - -if __name__ == "__main__": - main() - - - -# 비재귀 머지 소트 트리 -import bisect -import sys -input = sys.stdin.readline - -class SortTree: - def __init__(self, values): - self.tree = [[x] for x in values] - self.size = len(self.tree) - self.tree = [None] * self.size + self.tree - for i in range(self.size - 1, 0, -1): - self.tree[i] = sorted(self.tree[i * 2] + self.tree[i * 2 + 1]) - - def count_less_than(self, beg: int, end: int, k: int): - l, r = beg + self.size, end + self.size - 1 - ret = 0 - while l <= r: - if l % 2: - ret += bisect.bisect_right(self.tree[l], k) - if not r % 2: - ret += bisect.bisect_right(self.tree[r], k) - l, r = (l + 1) >> 1, (r - 1) >> 1 - return ret - -N = int(input()) -A = [int(x) for x in input().split()] -M = int(input()) -tree = SortTree(A) - -ans = [0]*M -for t in range(M): - i, j, k = [int(x) for x in input().split()] - ans[t] = (j-i+1) - tree.count_less_than(i-1, j, k) - -sys.stdout.write("\n".join(map(str,ans)) + "\n") - - - -# 풀이 3 -from sys import stdin -from bisect import bisect -input = stdin.readline -N = int(input()) -A = list(map(int, input().split())) -M = int(input()) -start, end = 0, N-1 -segSize = 1 -while segSize < N: - segSize <<= 1 -segTree = [-1] * (segSize * 2) - -def build(): - for i in range(segSize, segSize * 2): - try: - segTree[i] = [A[i-segSize]] - except: - segTree[i] = [] - for i in range(segSize-1, 0, -1): - segTree[i] = sorted(segTree[i<<1] + segTree[i<<1|1]) - -def query(l, r, k): - l += segSize - r += segSize - res = 0 - while l < r: - if l&1: - res += len(segTree[l]) - bisect(segTree[l], k) - l += 1 - if r&1: - r -= 1 - res += len(segTree[r]) - bisect(segTree[r], k) - l >>= 1 - r >>= 1 - return res - -build() -for _ in range(M): - left, right, value = map(int, input().split()) - print(query(left - 1, right, value)) - - - -# https://www.acmicpc.net/problem/13544 -# 머지소트트리, 세그먼트 트리로도 해보기 - -import sys -from math import ceil, log2 -from bisect import bisect_right - - -# 머지소트 트리 생성 -def infalte_tree(nodes): - height = ceil(log2(len(nodes))) - tree = [list() for _ in range(2 << height)] - end_layer = 1 << height - - for seq, num in enumerate(nodes): - tree[end_layer + seq] = [num] - - end_layer >>= 1 - while end_layer: - for i in range(end_layer): - # 병합정렬 - arr1_idx = arr2_idx = 0 - - while arr1_idx < len(tree[(end_layer + i) * 2]) and arr2_idx < len(tree[(end_layer + i) * 2 + 1]): - if tree[(end_layer + i) * 2][arr1_idx] < tree[(end_layer + i) * 2 + 1][arr2_idx]: - tree[(end_layer + i)].append(tree[(end_layer + i) * 2][arr1_idx]) - arr1_idx += 1 - else: - tree[(end_layer + i)].append(tree[(end_layer + i) * 2 + 1][arr2_idx]) - arr2_idx += 1 - - # 남은 원소 넣어주기 - if arr1_idx != len(tree[(end_layer + i) * 2]): - for e in range(arr1_idx, len(tree[(end_layer + i) * 2])): - tree[(end_layer + i)].append(tree[(end_layer + i) * 2][e]) - - # 남은 원소 넣어주기 - if arr2_idx != len(tree[(end_layer + i) * 2 + 1]): - for e in range(arr2_idx, len(tree[(end_layer + i) * 2 + 1])): - tree[(end_layer + i)].append(tree[(end_layer + i) * 2 + 1][e]) - - end_layer >>= 1 - - return tree - - -# query_start ~ query_end 내 정렬 된 구간 반환 -def search(tree, tree_len, query_start, query_end): - result = [] - - # bottom-up 방식 - node_start = tree_len + query_start - 1 - node_end = tree_len + query_end - - while node_start < node_end: - if node_start & 1: - result.append(tree[node_start]) - node_start += 1 - if node_end & 1: - result.append(tree[node_end - 1]) - node_end -= 1 - - node_start >>= 1 - node_end >>= 1 - - return result - - -if __name__ == '__main__': - sys.stdin.readline() # 노드의 개수, 필요없음 - nodes = [*map(int, sys.stdin.readline().split())] - n_query = int(sys.stdin.readline()) - tree = infalte_tree(nodes) - tree_len = 1 << ceil(log2(len(nodes))) - - for _ in range(n_query): - # 문제 조건에 맞게 인덱스 변경 - src, dst, target = map(int, sys.stdin.readline().split()) - cnt = 0 - - for portion in search(tree, tree_len, src, dst): - cnt += len(portion) - bisect_right(portion, target) - - print(cnt) - - -# 머지트리 -import sys -from bisect import bisect -from math import log2, ceil - - -def merge(arr1, arr2): - res = [] - i = j = 0 - while True: - if i == len(arr1): - return res + arr2[j:] - - if j == len(arr2): - return res + arr1[i:] - - if arr1[i] <= arr2[j]: - res.append(arr1[i]) - i += 1 - - else: - res.append(arr2[j]) - j += 1 - - -n = int(sys.stdin.readline()) -num = list(map(int, sys.stdin.readline().split())) -height = ceil(log2(n)) -tree = [[] for _ in range(2 ** (height + 1))] - -for i in range(n): - tree[2 ** height + i] = [num[i]] - -for h in range(height - 1, -1, -1): - for i in range(2 ** h, 2 ** (h + 1)): - tree[i] = merge(tree[2 * i], tree[2 * i + 1]) - - -def partial(a, b, k): - res = 0 - a += 2 ** height - 1 - b += 2 ** height - 1 - while a <= b: - if a % 2: - res += len(tree[a]) - bisect(tree[a], k) - a += 1 - if b % 2 == 0: - res += len(tree[b]) - bisect(tree[b], k) - b -= 1 - a //= 2 - b //= 2 - - return res - - -for _ in range(int(sys.stdin.readline())): - print(partial(*map(int, sys.stdin.readline().split()))) - - - -# https://www.acmicpc.net/problem/13537 -# segment tree: save sorted list, do binary search - -from bisect import bisect_left -from sys import stdin - -n = int(stdin.readline().strip()) -seq = [[int(i)] for i in stdin.readline().split()] -tree = [[] for _ in range(n)] + seq - -# initialize -for i in range(n - 1, -1, -1): - left = tree[i << 1] - right = tree[i << 1 | 1] - # l, r = 0, 0 - # while l < len(left) and r < len(right): - # if left[l] < right[r]: - # tree[i].append(left[l]) - # l += 1 - # elif left[l] > right[r]: - # tree[i].append(right[r]) - # r += 1 - # else: - # tree[i].append(left[l]) - # tree[i].append(right[r]) - # l += 1 - # r += 1 - # if l != len(left): - # tree[i] += left[l:] - # if r != len(right): - # tree[i] += right[r:] - tree[i] = sorted(left + right) - - -def query(start, end, target): - start += n - 1 - end += n - 1 - target += 1 - res = 0 - while start < end: - if start & 1: - idx = bisect_left(tree[start], target) - res += len(tree[start]) - idx - start += 1 - if not end & 1: - idx = bisect_left(tree[end], target) - res += len(tree[end]) - idx - end -= 1 - start >>= 1 - end >>= 1 - - if start == end: - idx = bisect_left(tree[start], target) - res += len(tree[start]) - idx - - return res - - -m = int(stdin.readline().strip()) -for _ in range(m): - i, j, k = map(int, stdin.readline().split()) - print(query(i, j, k)) - - - - -# 머지트리 -import bisect, sys - -class MergesortTree(): - - def __init__(self, n): - self.n = 2 ** (n - 1).bit_length() - self.data = [[] for _ in range(2 * self.n)] - - def set(self, k, v): - self.data[k + self.n - 1].append(v) - - def build(self): - for k in reversed(range(self.n - 1)): - A, B = self.data[k * 2 + 1], self.data[k * 2 + 2] - i = j = 0 - while i < len(A) and j < len(B): - if A[i] < B[j]: self.data[k].append(A[i]); i += 1 - else: self.data[k].append(B[j]); j += 1 - while i < len(A): self.data[k].append(A[i]); i += 1 - while j < len(B): self.data[k].append(B[j]); j += 1 - - def greater(self, l, r, k): - L = l + self.n - R = r + self.n - ret = 0 - while L < R: - if R & 1: - R -= 1 - ret += len(self.data[R - 1]) - bisect.bisect(self.data[R - 1], k) - if L & 1: - ret += len(self.data[L - 1]) - bisect.bisect(self.data[L - 1], k) - L += 1 - L >>= 1 - R >>= 1 - return ret - -if __name__ == '__main__': - input = sys.stdin.readline - N = int(input()) - A = list(map(int, input().split())) - Q = int(input()) - L = 0 - - ST = MergesortTree(N) - for i, s in enumerate(A): - ST.set(i, s) - ST.build() - for _ in range(Q): - i, j, k = map(int, input().split()) - L = ST.greater(i - 1, j, k) - print(L) \ No newline at end of file diff --git "a/13544 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2543.py" "b/13544 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2543.py" deleted file mode 100644 index bb9b40f..0000000 --- "a/13544 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2543.py" +++ /dev/null @@ -1,392 +0,0 @@ -#!/usr/bin/env python -import os -import sys -from io import BytesIO, IOBase - - -def main(): - N = int(input()) - a = list(map(int,input().split())) - depth = 17 - b = a + [0] * ((1 << depth) - N) - mst = [] - mstCur = [] - for i in range(1 << depth): - mstCur.append([b[i]]) - mst.append(mstCur) - for d in range(1,depth + 1): - mstCur = [] - for i in range(1 << depth - d): - mstCurCur = mst[-1][i << 1] + mst[-1][(i << 1) + 1] - mstCurCur.sort() - mstCur.append(mstCurCur) - mst.append(mstCur) - def query(j, p): - ans = 0 - depth = 0 - while j != 0: - if j & 1: - # Find how many there are on mst[depth][j - 1] - l = 0 - r = len(mst[depth][j - 1]) - while l < r: - k = (l + r) // 2 - if mst[depth][j - 1][k] > p: - r = k - else: - l = k + 1 - ans += len(mst[depth][j - 1]) - l - j //= 2 - depth += 1 - return ans - M = int(input()) - last_ans = 0 - for _ in range(M): - a,b,c = map(int,input().split()) - a ^= last_ans - b ^= last_ans - c ^= last_ans - last_ans = query(b, c) - query(a - 1, c) - print(last_ans) - - -# region fastio - -BUFSIZE = 8192 - - -class FastIO(IOBase): - newlines = 0 - - def __init__(self, file): - self._fd = file.fileno() - self.buffer = BytesIO() - self.writable = "x" in file.mode or "r" not in file.mode - self.write = self.buffer.write if self.writable else None - - def read(self): - while True: - b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) - if not b: - break - ptr = self.buffer.tell() - self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) - self.newlines = 0 - return self.buffer.read() - - def readline(self): - while self.newlines == 0: - b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) - self.newlines = b.count(b"\n") + (not b) - ptr = self.buffer.tell() - self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) - self.newlines -= 1 - return self.buffer.readline() - - def flush(self): - if self.writable: - os.write(self._fd, self.buffer.getvalue()) - self.buffer.truncate(0), self.buffer.seek(0) - - -class IOWrapper(IOBase): - def __init__(self, file): - self.buffer = FastIO(file) - self.flush = self.buffer.flush - self.writable = self.buffer.writable - self.write = lambda s: self.buffer.write(s.encode("ascii")) - self.read = lambda: self.buffer.read().decode("ascii") - self.readline = lambda: self.buffer.readline().decode("ascii") - - -sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) -input = lambda: sys.stdin.readline().rstrip("\r\n") - -# endregion - -if __name__ == "__main__": - main() - - -# https://www.acmicpc.net/problem/7469 -# 머지소트트리, 세그먼트 트리로도 해보기 - -import sys -from math import ceil, log2 -from bisect import bisect_right - - -# 머지소트 트리 생성 -def infalte_tree(nodes): - height = ceil(log2(len(nodes))) - tree = [list() for _ in range(2 << height)] - end_layer = 1 << height - - for seq, num in enumerate(nodes): - tree[end_layer + seq] = [num] - - end_layer >>= 1 - while end_layer: - for i in range(end_layer): - # 병합정렬 - arr1_idx = arr2_idx = 0 - - while arr1_idx < len(tree[(end_layer + i) * 2]) and arr2_idx < len(tree[(end_layer + i) * 2 + 1]): - if tree[(end_layer + i) * 2][arr1_idx] < tree[(end_layer + i) * 2 + 1][arr2_idx]: - tree[(end_layer + i)].append(tree[(end_layer + i) * 2][arr1_idx]) - arr1_idx += 1 - else: - tree[(end_layer + i)].append(tree[(end_layer + i) * 2 + 1][arr2_idx]) - arr2_idx += 1 - - # 남은 원소 넣어주기 - if arr1_idx != len(tree[(end_layer + i) * 2]): - for e in range(arr1_idx, len(tree[(end_layer + i) * 2])): - tree[(end_layer + i)].append(tree[(end_layer + i) * 2][e]) - - # 남은 원소 넣어주기 - if arr2_idx != len(tree[(end_layer + i) * 2 + 1]): - for e in range(arr2_idx, len(tree[(end_layer + i) * 2 + 1])): - tree[(end_layer + i)].append(tree[(end_layer + i) * 2 + 1][e]) - - end_layer >>= 1 - - return tree - - -# query_start ~ query_end 내 정렬 된 구간 반환 -def search(tree, tree_len, query_start, query_end): - result = [] - - # bottom-up 방식 - node_start = tree_len + query_start - 1 - node_end = tree_len + query_end - - while node_start < node_end: - if node_start & 1: - result.append(tree[node_start]) - node_start += 1 - if node_end & 1: - result.append(tree[node_end - 1]) - node_end -= 1 - - node_start >>= 1 - node_end >>= 1 - - return result - - -if __name__ == '__main__': - sys.stdin.readline() # 노드의 개수, 필요없음 - nodes = [*map(int, sys.stdin.readline().split())] - n_query = int(sys.stdin.readline()) - tree = infalte_tree(nodes) - tree_len = 1 << ceil(log2(len(nodes))) - answer = 0 - - for _ in range(n_query): - i, j, k = map(int, sys.stdin.readline().split()) - src = answer ^ i - dst = answer ^ j - target = answer ^ k - cnt = 0 - - for portion in search(tree, tree_len, src, dst): - cnt += len(portion) - bisect_right(portion, target) - - answer = cnt - print(answer) - - -import bisect, sys - -class MergesortTree(): - - def __init__(self, n): - self.n = 2 ** (n - 1).bit_length() - self.data = [[] for _ in range(2 * self.n)] - - def set(self, k, v): - self.data[k + self.n - 1].append(v) - - def build(self): - for k in reversed(range(self.n - 1)): - A, B = self.data[k * 2 + 1], self.data[k * 2 + 2] - i = j = 0 - while i < len(A) and j < len(B): - if A[i] < B[j]: self.data[k].append(A[i]); i += 1 - else: self.data[k].append(B[j]); j += 1 - while i < len(A): self.data[k].append(A[i]); i += 1 - while j < len(B): self.data[k].append(B[j]); j += 1 - - def greater(self, l, r, k): - L = l + self.n - R = r + self.n - ret = 0 - while L < R: - if R & 1: - R -= 1 - ret += len(self.data[R - 1]) - bisect.bisect(self.data[R - 1], k) - if L & 1: - ret += len(self.data[L - 1]) - bisect.bisect(self.data[L - 1], k) - L += 1 - L >>= 1 - R >>= 1 - return ret - -if __name__ == '__main__': - input = sys.stdin.readline - N = int(input()) - A = list(map(int, input().split())) - Q = int(input()) - L = 0 - - ST = MergesortTree(N) - for i, s in enumerate(A): - ST.set(i, s) - ST.build() - for _ in range(Q): - i, j, k = map(int, input().split()) - i ^= L; j ^= L; k ^= L - L = ST.greater(i - 1, j, k) - print(L) - - -from sys import stdin -from bisect import bisect -input = stdin.readline -N = int(input()) -A = list(map(int, input().split())) -M = int(input()) -segSize = 1 -while segSize < N: - segSize <<= 1 -segTree = [0] * (segSize * 2) -ans = 0 - -def build(): - global segTree - for i in range(segSize, segSize * 2): - try: - segTree[i] = [A[i - segSize]] - except: - segTree[i] = [] - for i in range(segSize-1, 0, -1): - segTree[i] = sorted(segTree[i<<1] + segTree[i<<1|1]) - -def query(l, r, k): - l += segSize - r += segSize - res = 0 - while l < r: - if l&1: - res += len(segTree[l]) - bisect(segTree[l], k) - l += 1 - if r&1: - r -= 1 - res += len(segTree[r]) - bisect(segTree[r], k) - l >>= 1 - r >>= 1 - return res - -build() -for _ in range(M): - l, r, k = map(int, input().split()) - l ^= ans - r ^= ans - k ^= ans - ans = query(l - 1, r, k) - print(ans) - -import sys -import bisect -input = sys.stdin.readline -output = sys.stdout.write - -N = int(input()) -st = 1 -while st1: - ed = tmp - tmp = tmp>>1 - for i in range(tmp,ed): - l,r = 0,0 - left,right = len(tree[i<<1]),len(tree[i<<1|1]) - while le or ne>1 - return query(node<<1,ns,mid,s,e,k)+query(node<<1|1,mid+1,ne,s,e,k) -M = int(input()) -ans = 0 -for i in range(M): - a,b,c = map(int,input().split()) - i,j,k = a^ans,b^ans,c^ans - ans = query(1,1,st,i,j,k) - output("%d\n"%ans) - - -import sys -from bisect import bisect -input = sys.stdin.readline -print = sys.stdout.write - -def init(): - for i in range(N): - arr[i+L].append(nums[i]) - for i in range(L-1, 0, -1): - p = q = 0 - al, bl = len(arr[i*2]), len(arr[i*2+1]) - while p < al and q < bl: - if arr[i*2][p] <= arr[i*2+1][q]: - arr[i].append(arr[i*2][p]) - p += 1 - else: - arr[i].append(arr[i*2+1][q]) - q += 1 - while p < al: - arr[i].append(arr[i*2][p]) - p += 1 - while q < bl: - arr[i].append(arr[i*2+1][q]) - q += 1 - -def query(l, r, k): - l += L-1; r += L-1 - ret = 0 - len_arr = 1 - while l <= r: - if l%2 == 1: - ret += len(arr[l]) - bisect(arr[l], k) - l += 1 - if r%2 == 0: - ret += len(arr[r]) - bisect(arr[r], k) - r -= 1 - l //= 2; r //= 2 - return ret - -N = int(input()) -L = 1 << N.bit_length() -arr = [[] for i in range(L*2)] -nums = list(map(int, input().split())) -Q = int(input()) -init() -last_ans = 0 -for i in range(Q): - l, r, k = map(int, input().split()) - l ^= last_ans; r ^= last_ans; k ^= last_ans - last_ans = query(l, r, k) - print(str(last_ans)+'\n') \ No newline at end of file diff --git "a/13547 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254 5.py" "b/13547 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254 5.py" deleted file mode 100644 index c6c3bd8..0000000 --- "a/13547 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254 5.py" +++ /dev/null @@ -1,253 +0,0 @@ -def tree_update(i,diff): - while i<=N: - tree[i]+=diff - i+=i&-i -def tree_sum(i): - r=0 - while i: - r+=tree[i] - i&=i-1 - return r -import sys -input=sys.stdin.readline -N=int(input()) -tree=[0]*(N+5) -a=[0]*1000005 -b=[0]*(N+5) -for idx,i in enumerate(map(int,input().split())): - b[idx+1]=a[i] - a[i]=idx+1 -M=int(input()) -query=[tuple(map(int,input().split()))+(i,)for i in range(M)] -query.sort(key=lambda x:x[1]) -ans=[0]*M -cur=0 -for i in range(1,1+N): - if b[i]: - tree_update(b[i],-1) - tree_update(i,1) - while cur>>[BEGIN] teflib.fenwicktree.FenwickTree [v1.3] (Copied from teflib/fenwicktree.py)<<< -class FenwickTree: - """Fenwick tree for sum operation.""" - - def __init__(self, nums_or_size: Union[Iterable[float], int]): - if isinstance(nums_or_size, int): - self._size = nums_or_size - self._arr = [0] * nums_or_size - self._tree = [0] * nums_or_size - else: - self._arr = list(nums_or_size) - self._size = len(self._arr) - self._tree = self._arr[:] - for i, num in enumerate(self._tree): - if i | (i + 1) < self._size: - self._tree[i | (i + 1)] += num - - def update(self, pos: int, num: float): - self._arr[pos] += num - while pos < self._size: - self._tree[pos] += num - pos |= pos + 1 - - def set(self, pos: int, num: float): - self.update(pos, num - self._arr[pos]) - - def get(self, pos: int) -> float: - return self._arr[pos] - - def query(self, beg: int, end: int) -> float: - res = 0 - l, r = beg - 1, end - 1 - while r >= 0: - res += self._tree[r] - r = (r & (r + 1)) - 1 - while l >= 0: - res -= self._tree[l] - l = (l & (l + 1)) - 1 - return res -# >>>[END] teflib.fenwicktree.FenwickTree [v1.3]<<< - - -def main(): - N = int(sys.stdin.readline()) - A = [int(x) for x in sys.stdin.readline().split()] - queries = [[] for _ in range(N)] - M = int(sys.stdin.readline()) - for query_num in range(M): - i, j = [int(x) for x in sys.stdin.readline().split()] - queries[j - 1].append((i - 1, query_num)) - - last_pos = dict() - fenwick = FenwickTree(N) - answers = [None] * M - for i, a_i in enumerate(A): - try: - fenwick.update(last_pos[a_i], -1) - except KeyError: - pass - fenwick.update(i, 1) - last_pos[a_i] = i - for l, query_num in queries[i]: - answers[query_num] = fenwick.query(l, i + 1) - - print(*answers, sep='\n') - - -if __name__ == '__main__': - main() - - diff --git "a/13549\354\210\250\353\260\224\352\274\255\354\247\2103.py" "b/13549\354\210\250\353\260\224\352\274\255\354\247\2103.py" index 6364869..795d634 100644 --- "a/13549\354\210\250\353\260\224\352\274\255\354\247\2103.py" +++ "b/13549\354\210\250\353\260\224\352\274\255\354\247\2103.py" @@ -1,29 +1,29 @@ -import sys -input = sys.stdin.readline -from collections import deque - -N,K = map(int,input().split()) -queue=deque() -time = [-1]*100001 - -def BFS(N,K): - queue.append(N) - time[N] = 0 - while queue: - N = queue.popleft() - if N==K: - print(time[K]) - exit() - for next_node in (2*N,N+1,N-1): - if 0<=next_node<100001 and time[next_node]==-1: - if next_node == 2*N: - # 위상이 같을때는 queue앞에 넣어주어도 됨.(위상 = level) - queue.appendleft(next_node) - time[next_node] = time[N] - else: - queue.append(next_node) - time[next_node] = time[N]+1 -if N graph[i][k] + graph[k][j]: - graph[i][j] = graph[i][k] + graph[k][j] - -min_sum_user = float('inf') -for i in range(1,N+1): - sum_friends = 0 - for j in range(N+1): - if graph[i][j] != float('inf'): - sum_friends += graph[i][j] - if min_sum_user > sum_friends: - min_sum_user = sum_friends - answer = i -print(answer) \ No newline at end of file diff --git "a/13905\354\204\270\353\266\200.py" "b/13905\354\204\270\353\266\200.py" deleted file mode 100644 index ea30145..0000000 --- "a/13905\354\204\270\353\266\200.py" +++ /dev/null @@ -1,38 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def is_possible(limit): - queue = deque() - queue.append(s) - visited = {i: False for i in range(1,N+1)} - visited[s] = True - while queue: - cur_node = queue.popleft() - if cur_node == e: - return True - for next_node, next_limit in graph[cur_node]: - if not visited[next_node] and limit <= next_limit: - visited[next_node] = True - queue.append(next_node) - return False - -N, M = map(int, input().split()) -s, e = map(int, input().split()) -graph = {i: [] for i in range(1,N+1)} -for _ in range(M): - a,b,c = map(int, input().split()) - graph[a].append([b,c]) - graph[b].append([a,c]) -left = 1 -right = 1000000 -answer = 0 -while left <= right: - mid = (left + right)//2 - if is_possible(mid): - left = mid + 1 - answer = mid - else: - right = mid - 1 - -print(answer) \ No newline at end of file diff --git "a/13913 \354\210\250\353\260\224\352\274\255\354\247\2104_re.py" "b/13913 \354\210\250\353\260\224\352\274\255\354\247\2104_re.py" deleted file mode 100644 index ca87f05..0000000 --- "a/13913 \354\210\250\353\260\224\352\274\255\354\247\2104_re.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(start,target): - queue = deque() - queue.append([start,0,[start]]) - visited = [False]*400001 - visited[start] = True - while queue: - cur,cur_time,cur_path = queue.popleft() - if cur==target: - return cur_time ,cur_path - for next_node in (cur-1,cur+1,cur*2): - if 0<=next_node<=200000 and not visited[next_node]: - visited[next_node] = True - queue.append([next_node,cur_time+1,cur_path+[next_node]]) - -N, K = map(int, input().split()) -if K <= N: - print(N-K) - print(*[i for i in range(N,K-1,-1)]) - exit() -time, path = bfs(N,K) -print(time) -print(*path) \ No newline at end of file diff --git "a/13913\354\210\250\353\260\224\352\274\255\354\247\2104.py" "b/13913\354\210\250\353\260\224\352\274\255\354\247\2104.py" index 58331ae..bc86f8e 100644 --- "a/13913\354\210\250\353\260\224\352\274\255\354\247\2104.py" +++ "b/13913\354\210\250\353\260\224\352\274\255\354\247\2104.py" @@ -1,32 +1,32 @@ -from collections import deque - -# 어차피 time(move)배열에 전에 어떤 숫자에서 이동 했는지 다 기록해놨음. -# 즉경로같이 이전에 어디서 왔나 알아야 하는 것들은 전부 dp처럼 기록해서 처리. -# answer arr에 목적지부터 이동한 time횟수만큼 dp역추적해서 지나간 path전부 저장 후 역순으로 프린트. -def path(x): - arr = [] - temp = x - for _ in range(dist[x]+1): - arr.append(temp) - temp = move[temp] - print(' '.join(map(str, arr[::-1]))) - -def bfs(): - q = deque() - q.append(N) - while q: - x = q.popleft() - if x == K: - print(dist[x]) - path(x) - return x - for i in (x+1, x-1, 2*x): - if 0<=i<=100000 and dist[i]==0: - q.append(i) - dist[i] = dist[x] + 1 - move[i] = x - -N, K = map(int, input().split()) -dist = [0]*100001 -move = [0]*100001 +from collections import deque + +# 어차피 time(move)배열에 전에 어떤 숫자에서 이동 했는지 다 기록해놨음. +# 즉경로같이 이전에 어디서 왔나 알아야 하는 것들은 전부 dp처럼 기록해서 처리. +# answer arr에 목적지부터 이동한 time횟수만큼 dp역추적해서 지나간 path전부 저장 후 역순으로 프린트. +def path(x): + arr = [] + temp = x + for _ in range(dist[x]+1): + arr.append(temp) + temp = move[temp] + print(' '.join(map(str, arr[::-1]))) + +def bfs(): + q = deque() + q.append(N) + while q: + x = q.popleft() + if x == K: + print(dist[x]) + path(x) + return x + for i in (x+1, x-1, 2*x): + if 0<=i<=100000 and dist[i]==0: + q.append(i) + dist[i] = dist[x] + 1 + move[i] = x + +N, K = map(int, input().split()) +dist = [0]*100001 +move = [0]*100001 bfs() \ No newline at end of file diff --git "a/13977\354\235\264\355\225\255\352\263\204\354\210\230\354\231\200 \354\277\274\353\246\254.py" "b/13977\354\235\264\355\225\255\352\263\204\354\210\230\354\231\200 \354\277\274\353\246\254.py" deleted file mode 100644 index 5129323..0000000 --- "a/13977\354\235\264\355\225\255\352\263\204\354\210\230\354\231\200 \354\277\274\353\246\254.py" +++ /dev/null @@ -1,28 +0,0 @@ -# 페르마의 소정리. -# p가 소수이고 a가 p의 배수가 아닐 경우(서로소일경우)a^(p-1) = 1 (mod p) -from sys import stdin, stdout - - -def pow(n, k): - if k == 1: - return n - pow_half = pow(n, k//2) - if k % 2 == 0: - return (pow_half ** 2) % MOD - else: - return (pow_half ** 2 * n) % MOD - -def inverse(n): - return pow(factorial[n], MOD-2) - -MOD = 1000000007 -factorial = [1] * 4000001 -for idx in range(2, 4000001): - factorial[idx] = (factorial[idx-1] * idx) % MOD - -m = int(input()) -for _ in range(m): - n, k = map(int, stdin.readline().split()) - stdout.write(str((factorial[n] * inverse(n-k) * inverse(k)) % MOD)) - stdout.write('\n') -stdout.flush() \ No newline at end of file diff --git a/14002LIS.py b/14002LIS.py index c6a5a79..ed2b897 100644 --- a/14002LIS.py +++ b/14002LIS.py @@ -1,21 +1,21 @@ -# 백준 14002 -N = int(input()) -arr = list(map(int, input().split())) -dp = [1]*N - -for i in range(1, N): - for j in range(i): - if arr[i]>arr[j]: - dp[i] = max(dp[i], dp[j]+1) - -print(max(dp)) - -order = max(dp) -lst = [] -for i in range(N-1, -1, -1): - if dp[i]==order: - lst.append(arr[i]) - order-=1 -# lst.reverse() -while lst: - print(lst.pop(), end=' ') +# 백준 14002 +N = int(input()) +arr = list(map(int, input().split())) +dp = [1]*N + +for i in range(1, N): + for j in range(i): + if arr[i]>arr[j]: + dp[i] = max(dp[i], dp[j]+1) + +print(max(dp)) + +order = max(dp) +lst = [] +for i in range(N-1, -1, -1): + if dp[i]==order: + lst.append(arr[i]) + order-=1 +# lst.reverse() +while lst: + print(lst.pop(), end=' ') diff --git "a/14003\352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264 5.py" "b/14003\352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264 5.py" deleted file mode 100644 index 8c4d6af..0000000 --- "a/14003\352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264 5.py" +++ /dev/null @@ -1,49 +0,0 @@ -import sys -from bisect import bisect_left -input = sys.stdin.readline - -n=int(input()) -a=list(map(int,input().split())) - -# 현 배열과 이진탐색 리스트. -q=[] -temp=[] -for x in a: - # 큐가 비어있거나 증가수열인자일때 넣는다. temp에는 q에 x가 들어간 위치를 표시한다. //그냥 마지막 인자보다 크면 깔금하게 넣고 - if not q or x>q[-1]: - q.append(x) - temp.append((len(q)-1,x)) - else: - # 이진탐색으로 queue내에서 x의 index를 찾은 후 그 값을 x로 변경. 마지막 인자보다 작으면 안에서 나보다 큰놈 찾아서 앞으로 들어간다. - q[bisect_left(q,x)]=x - # temp에도 동일하게 x의 위치와 인자를 삽입해준다. - temp.append((bisect_left(q,x),x)) - -ans=[] -last_idx=len(q)-1 -# 검사한 모든 인자 idx부터 0번 인덱스까지 역순으로 검사한다. -for i in range(len(temp)-1,-1,-1): - # temp의 index값이 큐에 들어간 마지막 인덱스 값과 같다면 - if temp[i][0]==last_idx: - # 엔서에 그 tmp인자x를 삽입하고 검사 인덱스를 한단계 낮춘다. - ans.append(temp[i][1]) - last_idx-=1 - # 총 길이와 -print(len(ans)) -# ans배열을 뒤집어 순서대로 출력한다. -print(*reversed(ans)) - - -""" -bisect_left 구현. - -def lower_bound(start,end,x): - while start < end: - mid = (start+end)//2 - - if tmp[mid] < x: - start = mid + 1 - else: - end = mid - return end -""" \ No newline at end of file diff --git a/1406.py b/1406.py deleted file mode 100644 index 0f8c13d..0000000 --- a/1406.py +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - - -lst = list(input().rstrip()) -cursor = len(lst) -M = int(input()) - - -for i in range(M): - order = list(input().split()) - if order[0] == "L" and cursor != 0: - cursor -=1 - continue - if order[0] == "D" and cursor != len(lst): - cursor +=1 - continue - if order[0] =="P": - lst = lst[:cursor]+[order[1]]+lst[cursor:] - cursor+=1 - continue - if order[0] == "B" and cursor != 0: - lst = lst[:cursor-1]+lst[cursor:] - cursor-=1 - continue - -print(''.join(lst)) \ No newline at end of file diff --git "a/1406_insert_delete_\354\212\244\355\203\235\354\234\274\353\241\234 \352\265\254\355\230\204.py" "b/1406_insert_delete_\354\212\244\355\203\235\354\234\274\353\241\234 \352\265\254\355\230\204.py" deleted file mode 100644 index a31ba7b..0000000 --- "a/1406_insert_delete_\354\212\244\355\203\235\354\234\274\353\241\234 \352\265\254\355\230\204.py" +++ /dev/null @@ -1,21 +0,0 @@ -from sys import stdin - -stk1 = list(stdin.readline().strip()) -stk2 = [] -n = int(input()) -for line in stdin: - if line[0] == 'L': - if stk1: - stk2.append(stk1.pop()) - else: continue - elif line[0] == 'D': - if stk2: - stk1.append(stk2.pop()) - else: continue - elif line[0] == 'B': - if stk1: - stk1.pop() - else: continue - elif line[0] == 'P': - stk1.append(line[2]) -print(''.join(stk1 + list(reversed(stk2)))) \ No newline at end of file diff --git "a/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\202\264\352\272\274.py" "b/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\202\264\352\272\274.py" index 82cfbcc..e369b7b 100644 --- "a/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\202\264\352\272\274.py" +++ "b/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\202\264\352\272\274.py" @@ -1,38 +1,38 @@ -import sys -input = sys.stdin.readline -from collections import deque - - - - -S = int(input()) -screen = 1 -board = 1 -queue = deque() -time = [0]*1001 -# 영선이는 효빈이에게 이모티콘 S개를 보낸다. - -# 각 연산은 1초씩 소모. -# 화면에 있는 이모티콘을 모두 복사해서 클립보드에 저장한다. -# 클립보드에 있는 모든 이모티콘을 화면에 붙여넣기 한다. -# 화면에 있는 이모티콘 중 하나를 삭제한다. - -# 최초 1개 -> s개를 만드는데 연산은 저장 붙혀넣기 2초에 2배. or 1초에 클립보드 만큼 가져올 수 있음. 1초에 -1 -# -# -# 핵심 아이디어는 time을 2차원배열 time[screen][board]형태로 만들어야 겹치는 값이 안들어감. -# 변하는 변수가 2개여서 쌍으로 움직여야하고 1차원 dp가 값이 중복해서 들어간다? => 2차원 dp로 변경. -queue.append([screen,board]) -while queue: - screen,board = queue.popleft() - if screen == S: - print(time[S]) - break - for next in (screen-1,screen,screen+board): - if 0<=next < 1001 and not time[next]: - if next == screen: - board = screen - queue.append([next,board]) - time[next] = time[screen] + 1 - - +import sys +input = sys.stdin.readline +from collections import deque + + + + +S = int(input()) +screen = 1 +board = 1 +queue = deque() +time = [0]*1001 +# 영선이는 효빈이에게 이모티콘 S개를 보낸다. + +# 각 연산은 1초씩 소모. +# 화면에 있는 이모티콘을 모두 복사해서 클립보드에 저장한다. +# 클립보드에 있는 모든 이모티콘을 화면에 붙여넣기 한다. +# 화면에 있는 이모티콘 중 하나를 삭제한다. + +# 최초 1개 -> s개를 만드는데 연산은 저장 붙혀넣기 2초에 2배. or 1초에 클립보드 만큼 가져올 수 있음. 1초에 -1 +# +# +# 핵심 아이디어는 time을 2차원배열 time[screen][board]형태로 만들어야 겹치는 값이 안들어감. +# 변하는 변수가 2개여서 쌍으로 움직여야하고 1차원 dp가 값이 중복해서 들어간다? => 2차원 dp로 변경. +queue.append([screen,board]) +while queue: + screen,board = queue.popleft() + if screen == S: + print(time[S]) + break + for next in (screen-1,screen,screen+board): + if 0<=next < 1001 and not time[next]: + if next == screen: + board = screen + queue.append([next,board]) + time[next] = time[screen] + 1 + + diff --git "a/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\213\265.py" "b/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\213\265.py" index ce781f7..3fed4d9 100644 --- "a/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\213\265.py" +++ "b/14226\354\235\264\353\252\250\355\213\260\354\275\230_\353\213\265.py" @@ -1,25 +1,25 @@ -from collections import deque -n = int(input()) -dist = [[-1]* (n+1) for _ in range(n+1)] -q = deque() - - -q.append((1,0)) # 화면 이모티콘 개수, 클립보드 이모티콘 개수 -dist[1][0] = 0 -while q: - s,c = q.popleft() - if dist[s][s] == -1: # 방문하지 않았으면 - dist[s][s] = dist[s][c] + 1 - q.append((s,s)) - if s+c <= n and dist[s+c][c] == -1: - dist[s+c][c] = dist[s][c] + 1 - q.append((s+c, c)) - if s-1 >= 0 and dist[s-1][c] == -1: - dist[s-1][c] = dist[s][c] + 1 - q.append((s-1, c)) -answer = -1 -for i in range(n+1): - if dist[n][i] != -1: - if answer == -1 or answer > dist[n][i]: - answer = dist[n][i] +from collections import deque +n = int(input()) +dist = [[-1]* (n+1) for _ in range(n+1)] +q = deque() + + +q.append((1,0)) # 화면 이모티콘 개수, 클립보드 이모티콘 개수 +dist[1][0] = 0 +while q: + s,c = q.popleft() + if dist[s][s] == -1: # 방문하지 않았으면 + dist[s][s] = dist[s][c] + 1 + q.append((s,s)) + if s+c <= n and dist[s+c][c] == -1: + dist[s+c][c] = dist[s][c] + 1 + q.append((s+c, c)) + if s-1 >= 0 and dist[s-1][c] == -1: + dist[s-1][c] = dist[s][c] + 1 + q.append((s-1, c)) +answer = -1 +for i in range(n+1): + if dist[n][i] != -1: + if answer == -1 or answer > dist[n][i]: + answer = dist[n][i] print(answer) \ No newline at end of file diff --git "a/14238\354\266\234\352\267\274\352\270\260\353\241\235.py" "b/14238\354\266\234\352\267\274\352\270\260\353\241\235.py" deleted file mode 100644 index 63833c9..0000000 --- "a/14238\354\266\234\352\267\274\352\270\260\353\241\235.py" +++ /dev/null @@ -1,47 +0,0 @@ -import sys -input = sys.stdin.readline - - -S = input().strip() -n = len(S) - -dp = [[[[[0 for _ in range(3)] for _ in range(3)] for _ in range(51)] for _ in range(51)] for _ in range(51)] - -ans = [0] * 50 -def go(a, b, c, p1, p2): - if a < 0 or b < 0 or c < 0: - return False - if a == 0 and b == 0 and c == 0: - return True - if dp[a][b][c][p1][p2]: - return False - dp[a][b][c][p1][p2] = True - ans[n-a-b-c] = 'A' - if go(a - 1, b, c, 0, p1): - return True - if p1 != 1: - ans[n-a-b-c] = 'B' - if go(a, b - 1, c, 1, p1): - return True - if p1 != 2 and p2 != 2: - ans[n-a-b-c] = 'C' - if go(a, b, c - 1, 2, p1): - return True - return False - - - -an = 0 -bn = 0 -cn = 0 -for s in S: - if s == 'A': - an += 1 - elif s == 'B': - bn += 1 - elif s == 'C': - cn += 1 -if go(an, bn, cn, 0, 0): - print(''.join(ans[:n])) -else: - print(-1) \ No newline at end of file diff --git a/14324Rain.py b/14324Rain.py index 4b4ecca..29f3743 100644 --- a/14324Rain.py +++ b/14324Rain.py @@ -1,42 +1,42 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def BFS(x,y,h): - global result - queue = deque() - queue.append([x,y]) - dx = [0,0,1,-1] - dy = [1,-1,0,0] - out_rain = False - cnt = 1 - visited[x][y] = True - while queue: - x,y = queue.popleft() - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx 2d convert -def to_matrix(l,m) : - return [l[i:i+m] for i in range(0, len(l), m)] - -# itertools의 product를 이용해서 비트마스크 제너레이터 만들기 -# e.g) (0,0,0,0), (0,0,0,1) ... (1,1,1,1) -a = itertools.product([0, 1], repeat=n*m) -ans = 0 - -# 가로부터 합계를 구해주고 세로 합계 구해줘서 더함 -for x in a: - bit_mask = to_matrix(x, m) - sumh = 0 - - for i in range(n): - hori = 0 - for j in range(m): - if bit_mask[i][j] == 0: - hori = 10 * hori + x_lst[i][j] - if bit_mask[i][j] == 1 or j == m - 1: - sumh = sumh + hori - hori = 0 - - sumv = 0 - - for j in range(m): - vert = 0 - for i in range(n): - if bit_mask[i][j] == 1: - vert = 10 * vert + x_lst[i][j] - if bit_mask[i][j] == 0 or i == n - 1: - sumv = sumv + vert - vert = 0 - - sum_all = sumh + sumv - - ans = max(ans, sum_all) - +import itertools + +# input +n, m = map(int, input().split()) +x_lst = [] +for _ in range(n): + x_lst.append(list(map(int, (input())))) + +# matrix 1d -> 2d convert +def to_matrix(l,m) : + return [l[i:i+m] for i in range(0, len(l), m)] + +# itertools의 product를 이용해서 비트마스크 제너레이터 만들기 +# e.g) (0,0,0,0), (0,0,0,1) ... (1,1,1,1) +a = itertools.product([0, 1], repeat=n*m) +ans = 0 + +# 가로부터 합계를 구해주고 세로 합계 구해줘서 더함 +for x in a: + bit_mask = to_matrix(x, m) + sumh = 0 + + for i in range(n): + hori = 0 + for j in range(m): + if bit_mask[i][j] == 0: + hori = 10 * hori + x_lst[i][j] + if bit_mask[i][j] == 1 or j == m - 1: + sumh = sumh + hori + hori = 0 + + sumv = 0 + + for j in range(m): + vert = 0 + for i in range(n): + if bit_mask[i][j] == 1: + vert = 10 * vert + x_lst[i][j] + if bit_mask[i][j] == 0 or i == n - 1: + sumv = sumv + vert + vert = 0 + + sum_all = sumh + sumv + + ans = max(ans, sum_all) + print(ans) \ No newline at end of file diff --git "a/1439\353\222\244\354\247\221\352\270\260.py" "b/1439\353\222\244\354\247\221\352\270\260.py" deleted file mode 100644 index 6f26b5b..0000000 --- "a/1439\353\222\244\354\247\221\352\270\260.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -s = input().rstrip() -N = len(s) -cnt=0 -for i in range(len(s)-1): - if s[i] != s[i+1]: - cnt+=1 -if cnt%2: - print(cnt//2+1) -else: - print(cnt//2) \ No newline at end of file diff --git "a/14405\355\224\274\354\271\264\354\270\204.py" "b/14405\355\224\274\354\271\264\354\270\204.py" deleted file mode 100644 index 37608a6..0000000 --- "a/14405\355\224\274\354\271\264\354\270\204.py" +++ /dev/null @@ -1,3 +0,0 @@ - - -print('YES' if not input().replace('pi',' ').replace('ka',' ').replace('chu',' ').strip() else 'NO') \ No newline at end of file diff --git "a/14417\355\214\260\353\246\260\353\223\234\353\241\254\352\263\274 \354\277\274\353\246\2542.py" "b/14417\355\214\260\353\246\260\353\223\234\353\241\254\352\263\274 \354\277\274\353\246\2542.py" deleted file mode 100644 index 6c1020f..0000000 --- "a/14417\355\214\260\353\246\260\353\223\234\353\241\254\352\263\274 \354\277\274\353\246\2542.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def manacher(s): - n = len(s) - P = [0]*n - c = 0 - r = 0 - - for i in range(n): - - if i > r: - P[i] = 0 - else: - P[i] = min(P[2*c-i],r-i) - while i-P[i]-1 > 0 and i+P[i]+1 < n and s[i+P[i]+1] == s[i-P[i]-1]: - P[i] += 1 - if r < i + P[i]: - r = i + P[i] - c = i - return P - -st = input().rstrip() -a_table = manacher('#' + '#'.join(st) + '#') -M = int(input()) -for _ in range(M): - start, length = map(int, input().split()) - cnt = 0 - for i in range(len(a_table)): - if a_table[i] >= length and i - a_table[i] == start*2+1: - cnt += 1 - print(cnt) diff --git "a/14425\353\254\270\354\236\220\354\227\264\354\247\221\355\225\251.py" "b/14425\353\254\270\354\236\220\354\227\264\354\247\221\355\225\251.py" deleted file mode 100644 index 4b841ed..0000000 --- "a/14425\353\254\270\354\236\220\354\227\264\354\247\221\355\225\251.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M = map(int,input().split()) -S = {} -for _ in range(N): - S[input().rstrip()] = 1 -cnt=0 -for _ in range(M): - a = input().rstrip() - try: - if S[a] ==1: - cnt+=1 - except: - continue - -print(cnt) \ No newline at end of file diff --git "a/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254 16.c++" "b/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254 16.c++" deleted file mode 100644 index 186aaf0..0000000 --- "a/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254 16.c++" +++ /dev/null @@ -1,82 +0,0 @@ -#include -#include -#include -#include -#include - -using namespace std; - -typedef pair pii; - -const int INF = 1e9 + 1; - -pii init(vector &arr, vector &tree, int node, int start, int end) -{ - if (start == end) - return tree[node] = { arr[start], start }; - - int mid = (start + end) / 2; - - return tree[node] = min(init(arr, tree, node * 2, start, mid), init(arr, tree, node * 2 + 1, mid + 1, end)); -} - -pii update(vector &tree, int node, int start, int end, int idx, int val) -{ - if (!(start <= idx && idx <= end)) - return tree[node]; - - if (start == end) - return tree[node] = { val, start }; - - int mid = (start + end) / 2; - - return tree[node] = min(update(tree, node * 2, start, mid, idx, val), update(tree, node * 2 + 1, mid + 1, end, idx, val)); -} - -pii query(vector &tree, int node, int start, int end, int left, int right) -{ - if (right < start || left > end) - return{ INF, INF }; - - if (left <= start && end <= right) - return tree[node]; - - int mid = (start + end) / 2; - - return min(query(tree, node * 2, start, mid, left, right), query(tree, node * 2 + 1, mid + 1, end, left, right)); -} -int main() -{ - int n; - scanf("%d", &n); - - vector arr(n); - for (int i = 0; i < n; i++) - scanf("%d", &arr[i]); - - int h = (int)ceil(log2(n)); - int tree_size = (1 << (h + 1)); - - vector tree(tree_size); - - init(arr, tree, 1, 0, n - 1); - - int m; - scanf("%d", &m); - - while (m--) - { - int num, i, j; - scanf("%d %d %d", &num, &i, &j); - - if (num == 1) - update(tree, 1, 0, n - 1, i - 1, j); - else - printf("%d\n", query(tree, 1, 0, n - 1, i - 1, j - 1).second + 1); - } - - return 0; -} - - -출처: https://www.crocus.co.kr/1208 [Crocus] \ No newline at end of file diff --git "a/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\25416_\353\202\250\354\235\230\354\275\224\353\223\234.py" "b/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\25416_\353\202\250\354\235\230\354\275\224\353\223\234.py" deleted file mode 100644 index dbb0238..0000000 --- "a/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\25416_\353\202\250\354\235\230\354\275\224\353\223\234.py" +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -import os -import sys -from io import BytesIO, IOBase - -class SegmentTree: - def __init__(self, data, default=0, func=max): - """initialize the segment tree with data""" - self._default = default - self._func = func - self._len = len(data) - self._size = _size = 1 << (self._len - 1).bit_length() - - self.data = [default] * (2 * _size) - self.data[_size:_size + self._len] = data - for i in reversed(range(_size)): - self.data[i] = func(self.data[i + i], self.data[i + i + 1]) - - def __delitem__(self, idx): - self[idx] = self._default - - def __getitem__(self, idx): - return self.data[idx + self._size] - - def __setitem__(self, idx, value): - idx += self._size - self.data[idx] = value - idx >>= 1 - while idx: - self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) - idx >>= 1 - - def __len__(self): - return self._len - - def query(self, start, stop): - """func of data[start, stop)""" - start += self._size - stop += self._size - - res_left = res_right = self._default - while start < stop: - if start & 1: - res_left = self._func(res_left, self.data[start]) - start += 1 - if stop & 1: - stop -= 1 - res_right = self._func(self.data[stop], res_right) - start >>= 1 - stop >>= 1 - - return self._func(res_left, res_right) - - def __repr__(self): - return "SegmentTree({0})".format(self.data) - -def main(): - N = int(input()) - A = list(map(int,input().split())) - for i in range(N): - A[i] *= 100000 - A[i] += i - AA = SegmentTree(A, default = 10 ** 15, func = min) - M = int(input()) - for _ in range(M): - q = list(map(int,input().split())) - if q[0] == 1: - AA[q[1] - 1] = q[2] * 100000 + q[1] - 1 - else: - print(AA.query(q[1] - 1, q[2]) % 100000 + 1) - - -# region fastio - -BUFSIZE = 8192 - - -class FastIO(IOBase): - newlines = 0 - - def __init__(self, file): - self._fd = file.fileno() - self.buffer = BytesIO() - self.writable = "x" in file.mode or "r" not in file.mode - self.write = self.buffer.write if self.writable else None - - def read(self): - while True: - b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) - if not b: - break - ptr = self.buffer.tell() - self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) - self.newlines = 0 - return self.buffer.read() - - def readline(self): - while self.newlines == 0: - b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) - self.newlines = b.count(b"\n") + (not b) - ptr = self.buffer.tell() - self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) - self.newlines -= 1 - return self.buffer.readline() - - def flush(self): - if self.writable: - os.write(self._fd, self.buffer.getvalue()) - self.buffer.truncate(0), self.buffer.seek(0) - - -class IOWrapper(IOBase): - def __init__(self, file): - self.buffer = FastIO(file) - self.flush = self.buffer.flush - self.writable = self.buffer.writable - self.write = lambda s: self.buffer.write(s.encode("ascii")) - self.read = lambda: self.buffer.read().decode("ascii") - self.readline = lambda: self.buffer.readline().decode("ascii") - - -sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) -input = lambda: sys.stdin.readline().rstrip("\r\n") - -# endregion - -if __name__ == "__main__": - main() \ No newline at end of file diff --git "a/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254_\353\202\250\354\235\2302.py" "b/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254_\353\202\250\354\235\2302.py" deleted file mode 100644 index 860eeaa..0000000 --- "a/14428 \354\210\230\354\227\264\352\263\274 \354\277\274\353\246\254_\353\202\250\354\235\2302.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -pin = sys.stdin.readline -INF = (1000000001,0) - -def update(i,x): - n = i+tsize-1 - tree[n] = (x,i) - while n>1: - n //= 2 - tree[n] = min(tree[n*2],tree[n*2+1]) - -def rmin(L,R): - L += tsize-1; R += tsize-1 - ans = INF - while L <= R: - if L%2==1: ans = min(ans,tree[L]); L += 1 - if R%2==0: ans = min(ans,tree[R]); R -= 1 - L //= 2; R //= 2 - return ans[1] - -N = int(pin()) -tsize = 1 -while tsize < N: tsize *= 2 -tree = [INF for _ in range(tsize*2)] -A = [*map(int,pin().split())] -for n in range(N): update(n+1,A[n]) -M = int(pin()) -for m in range(M): - Q,a,b = map(int,pin().split()) - if Q==1: update(a,b) - else: print(rmin(a,b)) \ No newline at end of file diff --git "a/14428\354\210\230\354\227\264\354\277\274\353\246\25416 \353\202\2504.py" "b/14428\354\210\230\354\227\264\354\277\274\353\246\25416 \353\202\2504.py" deleted file mode 100644 index f3777a7..0000000 --- "a/14428\354\210\230\354\227\264\354\277\274\353\246\25416 \353\202\2504.py" +++ /dev/null @@ -1,63 +0,0 @@ -# https://www.acmicpc.net/problem/14428 -# Segment Tree - -from sys import stdin - -n = int(stdin.readline().strip()) -seq = [0] + list(map(int, stdin.readline().split())) - - -def helper(first, second): - return min(sorted([first, second]), key=lambda x: seq[x]) - - -# Initialize Segment Tree -tree = [0 for _ in range(n)] + [i for i in range(1, n + 1)] -for i in range(n - 1, -1, -1): - # idx_l = tree[2 * i] - # idx_r = tree[2 * i ^ 1] - # if seq[idx_l] <= seq[idx_r]: - # tree[i] = idx_l - # else: - # tree[i] = idx_r - tree[i] = helper(tree[2 * i], tree[2 * i ^ 1]) - - -def query(left, right): - left += n - 1 - right += n - 1 - res = tree[left] - while left < right: - if left % 2 == 1: - res = helper(res, tree[left]) - left += 1 - if right % 2 == 0: - res = helper(res, tree[right]) - right -= 1 - left //= 2 - right //= 2 - - if left == right: - res = helper(res, tree[right]) - - return res - - -def update(pos, new): - seq[pos] = new - pos += n - 1 - while pos > 1: - tree[pos // 2] = helper(tree[pos], tree[pos ^ 1]) - pos //= 2 - - -m = int(stdin.readline().strip()) -for _ in range(m): - a, b, c = map(int, stdin.readline().split()) - if a == 1: - update(b, c) - # print(seq) - # print(tree) - - else: - print(query(b, c)) \ No newline at end of file diff --git "a/14428\354\210\230\354\227\264\354\277\274\353\246\25416_\353\202\2503.py" "b/14428\354\210\230\354\227\264\354\277\274\353\246\25416_\353\202\2503.py" deleted file mode 100644 index e31fbf4..0000000 --- "a/14428\354\210\230\354\227\264\354\277\274\353\246\25416_\353\202\2503.py" +++ /dev/null @@ -1,92 +0,0 @@ -import sys - -# limit for array size -N = 1000000 - -# Max size of tree -tree = [0] * (2 * N) -idxTree = [-1] * (2*N) - -def build(arr): - # insert leaf nodes in tree - for i in range(n): - tree[n + i] = arr[i] - idxTree[n + i] = i - - # build the tree by calculating parents - for i in range(n - 1, 0, -1): - tree[i] = min(tree[i << 1], tree[i << 1 | 1]) - # print(f'tree[{i}] {tree[i]} = i << 1-> {i << 1} * i << 1 | 1 ->{i << 1 | 1}') - if tree[i << 1] < tree[i << 1 | 1]: - idxTree[i] = idxTree[i << 1] - elif tree[i << 1] == tree[i << 1 | 1]: - idxTree[i] = min(idxTree[i << 1],idxTree[i << 1 | 1]) - else: - idxTree[i] = idxTree[i << 1 | 1] - # idxTree[i] = idxTree[i << 1] if tree[i << 1] < tree[i << 1 | 1] else idxTree[i << 1 | 1] - -def updateTreeNode(p, value): - # set value at position p - tree[p + n] = value - p = p + n - # move upward and update parents - i = p - while i > 1: - tree[i >> 1] = min(tree[i],tree[i ^ 1]) - if tree[i] < tree[i ^ 1]: - idxTree[i >> 1] = idxTree[i] - elif tree[i] == tree[i ^ 1]: - idxTree[i >> 1] = min(idxTree[i],idxTree[i ^ 1]) - else: - idxTree[i >> 1] = idxTree[i ^ 1] - # idxTree[i >> 1] = idxTree[i] if tree[i] < tree[i ^ 1] else idxTree[i ^ 1] - # print(f'idxtree {i >> 1} updated to {idxTree[i >> 1]}') - i >>= 1 - -# function to get sum on interval [l, r) - -def query(l, r): - res = int(1e13) - idx = -1 - # loop to find the sum in the range - l += n - r += n - while l < r: - if l & 1: - if tree[l] < res: - idx = idxTree[l] - # print(f'idx set to {idx} cause tree[l] == res') - elif tree[l] == res: - # idx = min(idx,l) - idx = min(idx, idxTree[l]) - # print(f'idx set to {idx} cause tree[l] == res') - res = min(res, tree[l]) - l += 1 - if r & 1: - r -= 1 - if tree[r] < res: - idx = idxTree[r] - # print(f'idx set to {idx}') - elif tree[r] == res: - # idx = min(idx,r) - idx = min(idx, idxTree[r]) - # print(f'idx set to {idx}') - res = min(res, tree[r]) - l >>= 1 - r >>= 1 - - return idx,res - - -N = int(sys.stdin.readline().rstrip()) -lt = [int(x) for x in sys.stdin.readline().rstrip().split()] -Q = int(sys.stdin.readline().rstrip()) -n = len(lt) -build(lt) -for i in range(Q): - c,a,b = [int(x) for x in sys.stdin.readline().rstrip().split()] - if c == 1: - updateTreeNode(a - 1, b) - elif c == 2: - idx,val = query(a-1, b) - print(f'{idx+1}') \ No newline at end of file diff --git "a/14428\354\210\230\354\227\264\355\200\230\353\246\25416_\353\202\2505.py" "b/14428\354\210\230\354\227\264\355\200\230\353\246\25416_\353\202\2505.py" deleted file mode 100644 index 9c8ba4d..0000000 --- "a/14428\354\210\230\354\227\264\355\200\230\353\246\25416_\353\202\2505.py" +++ /dev/null @@ -1,71 +0,0 @@ -"""Solution code for "BOJ 14428. 수열과 쿼리 16". - -- Problem link: https://www.acmicpc.net/problem/14428 -- Solution link: http://www.teferi.net/ps/problems/boj/14428 - -(This code was generated by Import Inliner v0.1) -""" - -import sys -from typing import Callable, Iterable, TypeVar - -T = TypeVar('T') - - -# >>>[BEGIN] teflib.segmenttree.SegmentTree [v1.2] (Copied from teflib/segmenttree.py)<<< -class SegmentTree: - """Non-recursive segment tree supporting point update and range query.""" - - def __init__(self, - values: Iterable[T], - merge: Callable[[T, T], T] = min): - l = list(values) - self._size = len(l) - self._tree = l + l - self._merge = merge - for i in range(self._size - 1, 0, -1): - self._tree[i] = merge(self._tree[i * 2], self._tree[i * 2 + 1]) - - def update(self, pos: int, value: T): - i = pos + self._size - while i: - self._tree[i] = self._merge(self._tree[i], value) - i >>= 1 - - def set(self, pos: int, value: T): - i = pos + self._size - while i: - self._tree[i] = value - value = self._merge(value, self._tree[i ^ 1]) - i >>= 1 - - def query(self, beg: int, end: int) -> T: - ret = self._tree[beg + self._size] - l, r = beg + self._size + 1, end + self._size - 1 - while l <= r: - if l % 2: - ret = self._merge(self._tree[l], ret) - if not r % 2: - ret = self._merge(self._tree[r], ret) - l, r = (l + 1) >> 1, (r - 1) >> 1 - return ret -# >>>[END] teflib.segmenttree.SegmentTree [v1.2]<<< - - -def main(): - N = int(sys.stdin.readline()) - A = [int(x) for x in sys.stdin.readline().split()] - segtree = SegmentTree((a_i, i + 1) for i, a_i in enumerate(A)) - M = int(sys.stdin.readline()) - for i in range(M): - query = [int(x) for x in sys.stdin.readline().split()] - if query[0] == 1: - _, i, v = query - segtree.set(i - 1, (v, i)) - else: - _, i, j = query - print(segtree.query(i - 1, j)[1]) - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git "a/14442\353\262\275 \353\266\200\354\210\230\352\263\240 \354\235\264\353\217\231\355\225\230\352\270\2602.py" "b/14442\353\262\275 \353\266\200\354\210\230\352\263\240 \354\235\264\353\217\231\355\225\230\352\270\2602.py" deleted file mode 100644 index aefd3b2..0000000 --- "a/14442\353\262\275 \353\266\200\354\210\230\352\263\240 \354\235\264\353\217\231\355\225\230\352\270\2602.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(x,y): - queue = deque() - queue.append([x,y,0]) - visited = [[[0]*(K+1) for _ in range(M)] for _ in range(N)] - visited[x][y][0] = 1 - while queue: - x,y,b_cnt = queue.popleft() - if x==N-1 and y==M-1: - return visited[x][y][b_cnt] - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0<=nx= n or y < 0 or y >= m - -def dijkstra(): - while q: - d, x, y = heappop(q) - if b[x][y] == 'F': - print(dist[x][y]//G, dist[x][y]%G) - return - for i in range(4): - nx, ny = x+dx[i], y+dy[i] - if out(nx, ny): - continue - nd = d+a[nx][ny] - if dist[nx][ny] > nd: - dist[nx][ny] = nd - heappush(q, (nd, nx, ny)) - - -n, m = map(int, input().split()) -b = [list(input().strip()) for _ in range(n)] -a = [[0]*m for _ in range(n)] -dist = [[1e9]*m for _ in range(n)] -dx, dy, G = (-1, 0, 1, 0), (0, 1, 0, -1), 2500 -q = [] - - -for i in range(n): - for j in range(m): - if b[i][j] == 'S': - heappush(q, (0, i, j)) - dist[i][j] = 0 - elif b[i][j] == 'g': - a[i][j] = G - for k in range(4): - ni, nj = i+dx[k], j+dy[k] - if not out(ni, nj) and b[ni][nj] == '.': - a[ni][nj] = 1 -dijkstra() \ No newline at end of file diff --git "a/14467 \354\206\214\352\260\200 \352\270\270\354\235\204 \352\261\264\353\204\210\352\260\204 \354\235\264\354\234\2401.py" "b/14467 \354\206\214\352\260\200 \352\270\270\354\235\204 \352\261\264\353\204\210\352\260\204 \354\235\264\354\234\2401.py" deleted file mode 100644 index 1be89ad..0000000 --- "a/14467 \354\206\214\352\260\200 \352\270\270\354\235\204 \352\261\264\353\204\210\352\260\204 \354\235\264\354\234\2401.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -state, cnt = {}, 0 -for _ in range(N): - a, b = map(int, input().split()) - if a in state and state[a] != b: cnt += 1 - state[a] = b -print(cnt) \ No newline at end of file diff --git "a/14499\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.py" "b/14499\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.py" deleted file mode 100644 index fc96d9c..0000000 --- "a/14499\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.py" +++ /dev/null @@ -1,62 +0,0 @@ -import sys -input = sys.stdin.readline - -# 1은 동쪽 -def turn_east(): - dice[1][2], dice[3][0] = dice[3][0], dice[1][2] - dice[1] = [dice[1][2]]+dice[1][:2] -# 2는 서쪽 -def turn_west(): - dice[1][0], dice[3][0] = dice[3][0], dice[1][0] - dice[1] = dice[1][1:] + [dice[1][0]] -# 3은 북쪽 -def turn_north(): - temp = dice[0][0] - dice[0][0] = dice[1][1] - dice[1][1] = dice[2][0] - dice[2][0] = dice[3][0] - dice[3][0] = temp -# 4는 남쪽 -def turn_south(): - temp = dice[3][0] - dice[3][0] = dice[2][0] - dice[2][0] = dice[1][1] - dice[1][1] = dice[0][0] - dice[0][0] = temp - -N,M,x,y,K = map(int,input().split()) -dice = [[0],[0,0,0],[0],[0]] -maps = [] -for _ in range(N): - maps.append(list(map(int,input().split()))) - -orders = list(map(int,input().split())) -for i in range(K): - if orders[i]==1: - if not y+1=0: - continue - y=y-1 - turn_west() - elif orders[i]==3: - if not x-1>=0: - continue - x=x-1 - turn_north() - elif orders[i]==4: - if not x+1=0: - max_sum = max(s+matrix[nx][ny]+matrix[init_x+1][init_y-1],max_sum) - if init_y+1=0: - max_sum = max(s+matrix[nx][ny]+matrix[init_x-1][init_y+1],max_sum) - - -N, M = map(int, input().split()) -matrix = [list(map(int, input().split())) for _ in range(N)] -visited = [[False]*M for _ in range(N)] -dx = [0,0,-1,1] -dy = [1,-1,0,0] - -max_sum = 0 -for i in range(N): - for j in range(M): - visited[i][j] = True - dfs(i,j,1,matrix[i][j],i,j) - visited[i][j] = False -print(max_sum) \ No newline at end of file diff --git "a/14500\355\205\214\355\212\270\353\241\234\353\257\270\353\205\270.py" "b/14500\355\205\214\355\212\270\353\241\234\353\257\270\353\205\270.py" index f4401d0..71eb8dc 100644 --- "a/14500\355\205\214\355\212\270\353\241\234\353\257\270\353\205\270.py" +++ "b/14500\355\205\214\355\212\270\353\241\234\353\257\270\353\205\270.py" @@ -1,57 +1,57 @@ -import sys -input = sys.stdin.readline - -# 사방 -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] - -# 빠큐모양 고려해야될 4개. -mfinger = [[[0, 1], [0, 2], [-1, 1]], [[0, 1], [0, 2], [1, 1]], -[[1, 0], [2, 0], [1, 1]], [[1, 0], [1, -1], [2, 0]]] - - -n, m = map(int, input().split()) -s = [] -# check박스 -visit = [[0] * m for _ in range(n)] - -# DFS 들어가고 나오고 max값만 비교. -# 먼가 이거 상하향은 고려안해도 될것 같은 느낌인데.. -# (2방향으로 DFS 하고 L자 삐져나오는 모양이랑 미음자 따로 계산해주는 게 날듯. 3가지 케이스니까.) -def dfs(x, y, cnt, num): - global result - if cnt == 4: - result = max(result, num) - return - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0 <= nx < n and 0 <= ny < m and visit[nx][ny] == 0: - visit[nx][ny] = 1 - dfs(nx, ny, cnt + 1, num + s[nx][ny]) - visit[nx][ny] = 0 - -# 빠큐값만 따로계산해서 max치 비교(빠큐는 DFS로 탐색되는 모양이 아니기 때문.) -def middlefinger(x, y): - global result - for i in mfinger: - try: - num = s[x][y] + s[x + i[0][0]][y + i[0][1]] + s[x + i[1][0]][y + i[1][1]] + s[x + i[2][0]][y + i[2][1]] - except: - num = 0 - result = max(result, num) - -# matrix 입력 -for i in range(n): - s.append(list(map(int, input().split()))) - -# 탐색 전 result 초기화 -result = 0 -# 모든 점에 대해 dfs및 빠큐탐색 진행. -for i in range(n): - for j in range(m): - visit[i][j] = 1 - dfs(i, j, 1, s[i][j]) - visit[i][j] = 0 - middlefinger(i, j) +import sys +input = sys.stdin.readline + +# 사방 +dx = [1, -1, 0, 0] +dy = [0, 0, -1, 1] + +# 빠큐모양 고려해야될 4개. +mfinger = [[[0, 1], [0, 2], [-1, 1]], [[0, 1], [0, 2], [1, 1]], +[[1, 0], [2, 0], [1, 1]], [[1, 0], [1, -1], [2, 0]]] + + +n, m = map(int, input().split()) +s = [] +# check박스 +visit = [[0] * m for _ in range(n)] + +# DFS 들어가고 나오고 max값만 비교. +# 먼가 이거 상하향은 고려안해도 될것 같은 느낌인데.. +# (2방향으로 DFS 하고 L자 삐져나오는 모양이랑 미음자 따로 계산해주는 게 날듯. 3가지 케이스니까.) +def dfs(x, y, cnt, num): + global result + if cnt == 4: + result = max(result, num) + return + for i in range(4): + nx = x + dx[i] + ny = y + dy[i] + if 0 <= nx < n and 0 <= ny < m and visit[nx][ny] == 0: + visit[nx][ny] = 1 + dfs(nx, ny, cnt + 1, num + s[nx][ny]) + visit[nx][ny] = 0 + +# 빠큐값만 따로계산해서 max치 비교(빠큐는 DFS로 탐색되는 모양이 아니기 때문.) +def middlefinger(x, y): + global result + for i in mfinger: + try: + num = s[x][y] + s[x + i[0][0]][y + i[0][1]] + s[x + i[1][0]][y + i[1][1]] + s[x + i[2][0]][y + i[2][1]] + except: + num = 0 + result = max(result, num) + +# matrix 입력 +for i in range(n): + s.append(list(map(int, input().split()))) + +# 탐색 전 result 초기화 +result = 0 +# 모든 점에 대해 dfs및 빠큐탐색 진행. +for i in range(n): + for j in range(m): + visit[i][j] = 1 + dfs(i, j, 1, s[i][j]) + visit[i][j] = 0 + middlefinger(i, j) print(result) \ No newline at end of file diff --git "a/14500\355\205\214\355\212\270\353\241\234\353\257\270\353\205\270_2xm.py" "b/14500\355\205\214\355\212\270\353\241\234\353\257\270\353\205\270_2xm.py" deleted file mode 100644 index cd1bbd4..0000000 --- "a/14500\355\205\214\355\212\270\353\241\234\353\257\270\353\205\270_2xm.py" +++ /dev/null @@ -1,43 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(x,y,sum_t,depth): - global max_sum - if depth==4: - max_sum = max(sum_t,max_sum) - return - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx N: - dp[i] = dp[i + 1] - else: - dp[i] = max(dp[i + 1], P[i] + dp[i + T[i]]) - -print(dp[0]) \ No newline at end of file diff --git "a/14501\355\207\264\354\202\254_3\355\212\270.py" "b/14501\355\207\264\354\202\254_3\355\212\270.py" deleted file mode 100644 index 483117e..0000000 --- "a/14501\355\207\264\354\202\254_3\355\212\270.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -T = [] -P = [] -dp=[] -for _ in range(N): - t,p = map(int,input().split()) - T.append(t) - P.append(p) - dp.append(p) -dp.append(0) -for i in range(N-1,-1,-1): - if i + T[i] > N: - dp[i] = dp[i+1] - else: - dp[i] = max(dp[i+1],dp[i+T[i]]+P[i]) - -print(dp[0]) - \ No newline at end of file diff --git "a/14502 \354\227\260\352\265\254\354\206\214.py" "b/14502 \354\227\260\352\265\254\354\206\214.py" deleted file mode 100644 index b52262f..0000000 --- "a/14502 \354\227\260\352\265\254\354\206\214.py" +++ /dev/null @@ -1,52 +0,0 @@ -import sys -input = sys.stdin.readline -from itertools import combinations -from collections import deque - -def bfs(walls): - q = deque() - visited = [[False]*M for _ in range(N)] - ret = 0 - for wall in walls: - i, j = wall - lab[i][j] = 1 - for v in virus: - x, y = v - q.append((x,y)) - visited[x][y] = True - while q: - x, y = q.popleft() - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - if 0 <= nx < N and 0 <= ny < M and not visited[nx][ny] and not lab[nx][ny]: - visited[nx][ny] = True - q.append((nx,ny)) - ret += 1 - for wall in walls: - i, j = wall - lab[i][j] = 0 - return ret - - -N, M = map(int, input().split()) -lab = [list(map(int, input().split())) for _ in range(N)] - -dx = [0,0,-1,1] -dy = [1,-1,0,0] - -cnt = 0 -virus = [] -candidates = [] -for i in range(N): - for j in range(M): - if not lab[i][j]: - candidates.append((i,j)) - cnt += 1 - elif lab[i][j]==2: - virus.append((i,j)) - -max_area = 0 -wall_sets = combinations(candidates,3) -for wall_set in wall_sets: - max_area = max(cnt - bfs(wall_set)-3,max_area) -print(max_area) diff --git "a/14502\354\227\260\352\265\254\354\206\214.py" "b/14502\354\227\260\352\265\254\354\206\214.py" deleted file mode 100644 index aad3c7c..0000000 --- "a/14502\354\227\260\352\265\254\354\206\214.py" +++ /dev/null @@ -1,52 +0,0 @@ -import sys -input = sys.stdin.readline - - -def BFS(): - global max_result - copy = [[0] * m for i in range(n)] - for i in range(n): - for j in range(m): - copy[i][j] = s[i][j] - result = 0 - arr = [] - for i in range(n): - for j in range(m): - if copy[i][j] == 2: - arr.append([i, j]) - while arr: - a, b = arr[0][0], arr[0][1] - del arr[0] - for i in range(4): - ax = a + dx[i] - ay = b + dy[i] - if 0 <= ax and 0 <= ay and ax < n and ay < m: - if copy[ax][ay] == 0: - copy[ax][ay] = 2 - arr.append([ax, ay]) - for i in copy: - for j in i: - if j == 0: - result += 1 - max_result = max(max_result, result) -# 벽 3개를 세우는 조합. -def DFS(cnt): - if cnt == 3: - BFS() - return - for i in range(n): - for j in range(m): - if s[i][j] == 0: - s[i][j] = 1 - DFS(cnt + 1) - s[i][j] = 0 -n, m = map(int, input().split()) -s = [] -dx = [0, 0, -1, 1] -dy = [-1, 1, 0, 0] -max_result = 0 -for i in range(n): - s.append(list(map(int, input().split()))) - -DFS(0) -print(max_result) \ No newline at end of file diff --git "a/14503\353\241\234\353\264\207\354\262\255\354\206\214\352\270\260.py" "b/14503\353\241\234\353\264\207\354\262\255\354\206\214\352\270\260.py" deleted file mode 100644 index a30cca1..0000000 --- "a/14503\353\241\234\353\264\207\354\262\255\354\206\214\352\270\260.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -input =sys.stdin.readline -from collections import deque - -def BFS(r,c,d): - queue =deque() - queue.append([r,c,d]) - cnt=1 # 현재 위치를 청소한다. - areas[r][c]=2 - while queue: - x,y,dir = queue.popleft() - for n_dir in ((dir-1)%4,(dir-2)%4,(dir-3)%4,dir): # 현재위치에서 왼쪽부터 차례대로 인접한 칸을 탐색한다. - nx=x+dx[n_dir] # 왼쪽에 청소할공간 없다면 다시 회전 - ny=y+dy[n_dir] - if not areas[nx][ny]: # 청소 안했으면 그 방향으로 회전한다음 한칸 전진하고 1번. - areas[nx][ny]=2 - cnt+=1 - queue.append([nx,ny,n_dir]) - break - else: # 네방향 아무데도 진입 못한경우. - nx=x-dx[dir] - ny=y-dy[dir] - if areas[nx][ny]==1:# 뒤쪽 벽. 작동 정지. - print(cnt) - return - else: # 벽 아니면 후진 - queue.append([nx,ny,dir]) - -dx=[-1,0,1,0] -dy=[0,1,0,-1] - -N,M = map(int,input().split()) -r,c,d = map(int,input().split()) -areas = [list(map(int,input().split())) for _ in range(N)] - -BFS(r,c,d) - diff --git "a/1455 \353\222\244\354\247\221\352\270\2602.py" "b/1455 \353\222\244\354\247\221\352\270\2602.py" deleted file mode 100644 index 2d72131..0000000 --- "a/1455 \353\222\244\354\247\221\352\270\2602.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -def xor(a, b): - for row in range(a + 1): - for col in range(b + 1): - matrix[row][col] ^= 1 - - -n, m = map(int, input().split()) -matrix = [list(map(int, list(input().rstrip()))) for __ in range(n)] -cnt = 0 -for row in range(n - 1, -1, -1): - for col in range(m - 1, -1, -1): - if matrix[row][col]: - cnt += 1 - xor(row, col) -print(cnt) \ No newline at end of file diff --git "a/14594\353\217\231\353\260\251\355\224\204\353\241\234\354\240\235\355\212\270.py" "b/14594\353\217\231\353\260\251\355\224\204\353\241\234\354\240\235\355\212\270.py" deleted file mode 100644 index 6a62db3..0000000 --- "a/14594\353\217\231\353\260\251\355\224\204\353\241\234\354\240\235\355\212\270.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -M = int(input()) -rooms = [1] * (N+1) -break_wall=[] - -for _ in range(M): - x, y = map(int, input().split()) - break_wall.append([x,y]) - -for left,right in break_wall: - for i in range(left,right): - rooms[i] = 0 - -print(sum(rooms)-1) \ No newline at end of file diff --git "a/14621 \353\202\230\353\247\214 \354\225\210\353\220\230\353\212\224 \354\227\260\354\225\240.py" "b/14621 \353\202\230\353\247\214 \354\225\210\353\220\230\353\212\224 \354\227\260\354\225\240.py" deleted file mode 100644 index 6981b96..0000000 --- "a/14621 \353\202\230\353\247\214 \354\225\210\353\220\230\353\212\224 \354\227\260\354\225\240.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - -def find(x): - if parent[x] == x: - return x - parent[x] = find(parent[x]) - return parent[x] - -def union(a,b): - a = find(a) - b = find(b) - - if level[a] >= level[b]: - parent[b] = a - if level[a]==level[b]: - level[a] +=1 - else: - parent[a] = b - -N, M = map(int, input().split()) -sex = [0] + list(input().split()) -arr = [] -parent = {i:i for i in range(1,N+1)} -level = {i:0 for i in range(1,N+1)} -for _ in range(M): - u, v, d = map(int, input().split()) - arr.append([d,u,v]) -arr.sort() -answer = 0 -for i in range(M): - dist,start,end = arr[i] - if find(start) != find(end) and sex[start] != sex[end]: - union(start,end) - answer += dist -target = find(1) -for i in range(2,N+1): - if target != find(i): - print(-1) - exit() -else: - print(answer) \ No newline at end of file diff --git "a/14627\355\214\214\353\213\255\355\214\214\353\213\255.py" "b/14627\355\214\214\353\213\255\355\214\214\353\213\255.py" deleted file mode 100644 index a172e97..0000000 --- "a/14627\355\214\214\353\213\255\355\214\214\353\213\255.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -input = sys.stdin.readline - - -def isPossible(length): - cnt = 0 - for pa in pas: - cnt += pa//length - if cnt >= C: - return True - return False - - -S, C = map(int, input().split()) -pas = [int(input()) for _ in range(S)] - -start = 1 -end = max(pas) -answer = (start+end)//2 -while start <= end: - mid = (start+end)//2 - if isPossible(mid): - start = mid+1 - answer = mid - else: - end = mid-1 -rest = sum(pas) - answer*C - -print(rest) \ No newline at end of file diff --git "a/14676\354\230\201\354\232\260\353\212\224\354\202\254\352\270\260\352\276\274.py" "b/14676\354\230\201\354\232\260\353\212\224\354\202\254\352\270\260\352\276\274.py" deleted file mode 100644 index c8042fc..0000000 --- "a/14676\354\230\201\354\232\260\353\212\224\354\202\254\352\270\260\352\276\274.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M, K = map(int,input().split()) -graph = {i: [] for i in range(1,N+1)} -level = {i: 0 for i in range(1,N+1)} -built = {i:0 for i in range(1,N+1)} -for _ in range(M): - a, b = map(int, input().split()) - graph[a] += [b] - level[b] += 1 - -for _ in range(K): - command, building = map(int, input().split()) - if command==1: - if not level[building]: - built[building] += 1 - if built[building]==1: - for next in graph[building]: - level[next] -= 1 - else: - print('Lier!') - exit() - else: - if built[building] >=1: - built[building] -= 1 - if not built[building]: - for next in graph[building]: - level[next] += 1 - else: - print('Lier!') - exit() - -print('King-God-Emperor') diff --git "a/14696\353\224\261\354\247\200\353\206\200\354\235\264.py" "b/14696\353\224\261\354\247\200\353\206\200\354\235\264.py" deleted file mode 100644 index 6c6a059..0000000 --- "a/14696\353\224\261\354\247\200\353\206\200\354\235\264.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -for _ in range(N): - a_cnt = [0]*5 - b_cnt = [0]*5 - a_n, *a_card = map(int, input().split()) - b_n, *b_card = map(int, input().split()) - for card in a_card: - a_cnt[card] += 1 - for card in b_card: - b_cnt[card] += 1 - for i in range(1,5): - if a_cnt[-i] > b_cnt[-i]: - print('A') - break - elif a_cnt[-i] < b_cnt[-i]: - print('B') - break - else: - print('D') - \ No newline at end of file diff --git "a/1469\354\210\214\354\202\254\354\235\264\354\210\230\354\227\264_\354\235\264\354\231\234\355\213\200.py" "b/1469\354\210\214\354\202\254\354\235\264\354\210\230\354\227\264_\354\235\264\354\231\234\355\213\200.py" deleted file mode 100644 index af1de59..0000000 --- "a/1469\354\210\214\354\202\254\354\235\264\354\210\230\354\227\264_\354\235\264\354\231\234\355\213\200.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(idx,answer): - if idx==length: - print(*answer) - exit() - for num in X: - if not visited[num]: - continue - elif visited[num]==1: - if idx>num and answer[idx-num-1]==num: - visited[num]-=1 - DFS(idx+1,answer+[num]) - visited[num]+=1 - else: - visited[num]-=1 - DFS(idx+1,answer+[num]) - visited[num]+=1 - -# 집합 X의 모든 수는 두번등장 -# i등장하고 cnt해서 i+1후에는 i가 다시 나와야함. - -N = int(input()) -X = list(map(int,input().split())) -visited ={x:2 for x in X} -arr = X+X -length = len(arr) -arr.sort() - -for num in X: - visited[num]-=1 - DFS(1,[num]) - visited[num]+=1 -print(-1) \ No newline at end of file diff --git "a/14725 \352\260\234\353\257\270\352\265\264.py" "b/14725 \352\260\234\353\257\270\352\265\264.py" deleted file mode 100644 index f2c89da..0000000 --- "a/14725 \352\260\234\353\257\270\352\265\264.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -class Trie: - def __init__(self): - self.root = {} # children - - def add(self, foods): - cur = self.root - for food in foods: - if food not in cur: - cur[food] = {} # dictonary => children - cur = cur[food] - cur[0] = True # leaf node - - def travel(self, level, cur): - if 0 in cur: - return - - cur_children = sorted(cur) - - for child in cur_children: - print("--"*level + child) - self.travel(level+1, cur[child]) - -N = int(sys.stdin.readline().strip()) -nest = Trie() -for _ in range(N): - input_line = sys.stdin.readline().split() - K = input_line[0 ] - foods = input_line[1:] - nest.add(foods) -nest.travel(0, nest.root) - diff --git "a/14728\353\262\274\353\235\275\354\271\230\352\270\260_DFS.py" "b/14728\353\262\274\353\235\275\354\271\230\352\270\260_DFS.py" index 5650d67..5b360b7 100644 --- "a/14728\353\262\274\353\235\275\354\271\230\352\270\260_DFS.py" +++ "b/14728\353\262\274\353\235\275\354\271\230\352\270\260_DFS.py" @@ -1,32 +1,32 @@ -import sys -input = sys.stdin.readline - - -N,T = map(int,input().split()) -# 여러 단원을 융합한 문제는 출제하지 않는다. -# 한 단원에 한 문제를 출제한다. 단 그 단원에 모든 내용을 알고 있어야 풀수 있다. - -score_table = [list(map(int,input().split())) for _ in range(N)] -score_table.append([1000000000,0]) -check = [False]*101 -max_score = 0 - -def DFS(v,sum_score,sum_time,last_score): - global max_score - if sum_time > T: - max_score = max(max_score,(sum_score-last_score)) - return - for i in range(v,N+1): - if not check[i]: - check[i] = True - sum_time += score_table[i][0] - last_score = score_table[i][1] - sum_score += last_score - DFS(i+1,sum_score,sum_time,last_score) - check[i] = False - sum_time -= score_table[i][0] - sum_score -= last_score - - -DFS(0,0,0,0) +import sys +input = sys.stdin.readline + + +N,T = map(int,input().split()) +# 여러 단원을 융합한 문제는 출제하지 않는다. +# 한 단원에 한 문제를 출제한다. 단 그 단원에 모든 내용을 알고 있어야 풀수 있다. + +score_table = [list(map(int,input().split())) for _ in range(N)] +score_table.append([1000000000,0]) +check = [False]*101 +max_score = 0 + +def DFS(v,sum_score,sum_time,last_score): + global max_score + if sum_time > T: + max_score = max(max_score,(sum_score-last_score)) + return + for i in range(v,N+1): + if not check[i]: + check[i] = True + sum_time += score_table[i][0] + last_score = score_table[i][1] + sum_score += last_score + DFS(i+1,sum_score,sum_time,last_score) + check[i] = False + sum_time -= score_table[i][0] + sum_score -= last_score + + +DFS(0,0,0,0) print(max_score) \ No newline at end of file diff --git "a/14728\353\262\274\353\235\275\354\271\230\352\270\260_DP.py" "b/14728\353\262\274\353\235\275\354\271\230\352\270\260_DP.py" index 0a33569..e19b7aa 100644 --- "a/14728\353\262\274\353\235\275\354\271\230\352\270\260_DP.py" +++ "b/14728\353\262\274\353\235\275\354\271\230\352\270\260_DP.py" @@ -1,17 +1,17 @@ -import sys -input = sys.stdin.readline - -N, T = map(int, input().split()) -score_table = [list(map(int,input().split())) for _ in range(N)] -dp = [[0]*(T+1) for _ in range(N+1)] - - -for i in range(1, N+1): #N개 과목에 대해 누적값 검사 - for j in range(1, T+1): #j시간에 대해 누적값 검사. - if j >= score_table[i-1][0]: #i번째 과목을 공부할 수 있는 시간이 되면 공부 시작. - dp[i][j] = max(dp[i-1][j], dp[i-1][j-score_table[i-1][0]] + score_table[i-1][1]) - else: - dp[i][j] = dp[i-1][j] - -print(dp[N][T]) - +import sys +input = sys.stdin.readline + +N, T = map(int, input().split()) +score_table = [list(map(int,input().split())) for _ in range(N)] +dp = [[0]*(T+1) for _ in range(N+1)] + + +for i in range(1, N+1): #N개 과목에 대해 누적값 검사 + for j in range(1, T+1): #j시간에 대해 누적값 검사. + if j >= score_table[i-1][0]: #i번째 과목을 공부할 수 있는 시간이 되면 공부 시작. + dp[i][j] = max(dp[i-1][j], dp[i-1][j-score_table[i-1][0]] + score_table[i-1][1]) + else: + dp[i][j] = dp[i-1][j] + +print(dp[N][T]) + diff --git "a/1476\353\202\240\354\247\234\352\263\204\354\213\274.py" "b/1476\353\202\240\354\247\234\352\263\204\354\213\274.py" index c13ad95..02dfc0b 100644 --- "a/1476\353\202\240\354\247\234\352\263\204\354\213\274.py" +++ "b/1476\353\202\240\354\247\234\352\263\204\354\213\274.py" @@ -1,21 +1,21 @@ -import sys -input = sys.stdin.readline - - -# E 1~15, S 1~28, M 1~19 -E,S,M = map(int,input().split()) -cnt=0 -while 1: - if E==S and S==M: - print(cnt + E) - break - E -= 1 - S -= 1 - M -= 1 - if E==0: - E=15 - if S==0: - S=28 - if M==0: - M=19 +import sys +input = sys.stdin.readline + + +# E 1~15, S 1~28, M 1~19 +E,S,M = map(int,input().split()) +cnt=0 +while 1: + if E==S and S==M: + print(cnt + E) + break + E -= 1 + S -= 1 + M -= 1 + if E==0: + E=15 + if S==0: + S=28 + if M==0: + M=19 cnt+=1 \ No newline at end of file diff --git "a/14888\354\227\260\354\202\260\354\236\220.py" "b/14888\354\227\260\354\202\260\354\236\220.py" deleted file mode 100644 index 31f4585..0000000 --- "a/14888\354\227\260\354\202\260\354\236\220.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(i,sum_t): - if i==N-1: - answer.append(sum_t) - return - for x in tool: - if x=='+' and tools[0]: - tools[0] -=1 - DFS(i+1,sum_t+arr[i+1]) - tools[0] +=1 - elif x=='-' and tools[1]: - tools[1] -=1 - DFS(i+1,sum_t-arr[i+1]) - tools[1] +=1 - elif x=='*' and tools[2]: - tools[2] -=1 - DFS(i+1,sum_t*arr[i+1]) - tools[2] +=1 - else: - if tools[3]: - tools[3] -=1 - if sum_t>=0: - DFS(i+1,sum_t//arr[i+1]) - else: - DFS(i+1,-((-sum_t)//arr[i+1])) - tools[3] +=1 - -N = int(input()) -arr = list(map(int,input().split())) -tools = list(map(int,input().split())) -tool = '+-*/' -answer = [] - -DFS(0,arr[0]) -# tools에서 N-1개롤 뽑는 조합. -# 최댓값과 최솟값 계산 -print(max(answer)) -print(min(answer)) \ No newline at end of file diff --git "a/14888\354\227\260\354\202\260\354\236\220\353\201\274\354\233\214\353\204\243\352\270\260.py" "b/14888\354\227\260\354\202\260\354\236\220\353\201\274\354\233\214\353\204\243\352\270\260.py" deleted file mode 100644 index 816358f..0000000 --- "a/14888\354\227\260\354\202\260\354\236\220\353\201\274\354\233\214\353\204\243\352\270\260.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(idx,calculate): - if idx==N: - answer.append(calculate) - return - num = seqs[idx] - for operator in '+-*/': - if operator == '+'and opers[0]: - opers[0] -=1 - DFS(idx+1,calculate+num) - opers[0] +=1 - elif operator == '-' and opers[1]: - opers[1] -=1 - DFS(idx+1,calculate-num) - opers[1] +=1 - elif operator == '*' and opers[2]: - opers[2] -=1 - DFS(idx+1,calculate*num) - opers[2] +=1 - elif operator == '/' and opers[3]: - if calculate <0: - opers[3] -=1 - DFS(idx+1,-((-calculate)//num)) - opers[3] +=1 - else: - opers[3] -=1 - DFS(idx+1,calculate//num) - opers[3] +=1 - -N = int(input()) -seqs = list(map(int,input().split())) -opers = list(map(int,input().split())) -answer=[] - -DFS(1,seqs[0]) - -print(max(answer)) -print(min(answer)) \ No newline at end of file diff --git "a/14889\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254.py" "b/14889\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254.py" index 54f59fb..1139285 100644 --- "a/14889\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254.py" +++ "b/14889\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254.py" @@ -1,32 +1,32 @@ -import sys - -input = sys.stdin.readline - -def dfs(idx, cnt): - global ans - # 반 나눠지면 start, link팀 합 구해서 차이 절댓값의 최솟값 전역변수 ans에 최신화 시켜줌. - if cnt == n // 2: - start, link = 0, 0 - for i in range(n-1): - for j in range(i+1,n): - if check[i] and check[j]: - start += a[i][j] + a[j][i] - elif not check[i] and not check[j]: - link += a[i][j] + a[j][i] - ans = min(ans, abs(start - link)) -# 그냥 check 가 1인거 반 0인거 반 나누기만함. - for i in range(idx, n): - if check[i]: - continue - check[i] = 1 - dfs(i + 1, cnt + 1) - check[i] = 0 - - -n = int(input()) -a = [list(map(int, input().split())) for _ in range(n)] - -check = [0 for _ in range(n)] -ans = sys.maxsize -dfs(0, 0) +import sys + +input = sys.stdin.readline + +def dfs(idx, cnt): + global ans + # 반 나눠지면 start, link팀 합 구해서 차이 절댓값의 최솟값 전역변수 ans에 최신화 시켜줌. + if cnt == n // 2: + start, link = 0, 0 + for i in range(n-1): + for j in range(i+1,n): + if check[i] and check[j]: + start += a[i][j] + a[j][i] + elif not check[i] and not check[j]: + link += a[i][j] + a[j][i] + ans = min(ans, abs(start - link)) +# 그냥 check 가 1인거 반 0인거 반 나누기만함. + for i in range(idx, n): + if check[i]: + continue + check[i] = 1 + dfs(i + 1, cnt + 1) + check[i] = 0 + + +n = int(input()) +a = [list(map(int, input().split())) for _ in range(n)] + +check = [0 for _ in range(n)] +ans = sys.maxsize +dfs(0, 0) print(ans) \ No newline at end of file diff --git "a/14889\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254_re.py" "b/14889\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254_re.py" deleted file mode 100644 index 7fa58f6..0000000 --- "a/14889\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254_re.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(start,depth): - global ans - if depth==N//2: - start,link=0,0 - for i in range(N-1): - for j in range(i+1,N): - if visited[i] and visited[j]: - start += sinerge[i][j] + sinerge[j][i] - elif not visited[i] and not visited[j]: - link += sinerge[i][j] + sinerge[j][i] - ans = min(ans,abs(start-link)) - for i in range(start,N): - if not visited[i]: - visited[i] = True - DFS(i+1,depth+1) - visited[i] = False - -N = int(input()) -sinerge = [list(map(int,input().split())) for _ in range(N)] - -# 팀에i,j가 속하면 능력치는 sinerge[i][j] + sinerge[j][i] 다 가져감. -# 모든 원소를 두 집단으로 나눠 차이를 최소로 할때 차이의 최솟값은? -# 일단 두 집단으로 나누는 경우의 수. N개중에 N//2개를 뽑는 조합. -# DFS로 depth N//2까지 탐색. sum구하고 차이 저장. - -visited = [False]*N -ans=float('inf') -DFS(0,0) -print(ans) \ No newline at end of file diff --git "a/14890 \352\262\275\354\202\254\353\241\234.py" "b/14890 \352\262\275\354\202\254\353\241\234.py" deleted file mode 100644 index 83eec52..0000000 --- "a/14890 \352\262\275\354\202\254\353\241\234.py" +++ /dev/null @@ -1,55 +0,0 @@ -import sys -input = sys.stdin.readline - -def check(li): - sw = [False for _ in range(n)] - for i in range(n - 1): - if li[i] == li[i + 1]: - continue - if abs(li[i] - li[i + 1]) > 1: - return False - # 내리막길 - if li[i] > li[i + 1]: - # 내리막길 층수 - temp = li[i + 1] - # 내리막길 앞쪽 l까지 체크. - for j in range(i + 1, i + 1 + l): - if 0 <= j < n: - # 층수 변동있으면 실패 - if li[j] != temp: return False - # 이미 전 층수변동시 사용한 칸이면 실패 - if sw[j] == True: return False - sw[j] = True - else: - return False - # 오르막길 - else: - temp = li[i] - for j in range(i, i - l, -1): - if 0 <= j < n: - if li[j] != temp: return False - if sw[j] == True: return False - sw[j] = True - else: - return False - # 검사 끝나면 성공. - return True - -n, l = map(int, input().split()) -s = [list(map(int, input().split())) for _ in range(n)] - -# 가로검사 -cnt = 0 -for i in s: - if check(i): - cnt += 1 - -# 세로배열 검사 -for i in range(n): - temp = [] - for j in range(n): - temp.append(s[j][i]) - if check(temp): - cnt += 1 - -print(cnt) \ No newline at end of file diff --git "a/14891\355\206\261\353\213\210\353\260\224\355\200\264.py" "b/14891\355\206\261\353\213\210\353\260\224\355\200\264.py" deleted file mode 100644 index 78ebcaf..0000000 --- "a/14891\355\206\261\353\213\210\353\260\224\355\200\264.py" +++ /dev/null @@ -1,49 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from copy import deepcopy - -def is_rotate(cur_gire,next_gire): - if next_gire==cur_gire+1: - if check_rotate[cur_gire][2]!=check_rotate[next_gire][6]: - return True - elif next_gire==cur_gire-1: - if check_rotate[next_gire][2]!=check_rotate[cur_gire][6]: - return True - return False - -def do_rotate(cur_gire,cur_dir): - queue=[] - queue.append([cur_gire,cur_dir]) - finished=[False]*4 - gires[cur_gire].rotate(cur_dir) - finished[cur_gire] = True - while queue: - cur_gire,cur_dir = queue.pop() - for next_gire in (cur_gire+1,cur_gire-1): - if 0<=next_gire<4 and not finished[next_gire]: - if is_rotate(cur_gire,next_gire): - queue.append([next_gire,-cur_dir]) - gires[next_gire].rotate(-cur_dir) - finished[next_gire] = True - -gires = [] -for _ in range(4): - q=deque() - temp = list(map(int,list(input().rstrip()))) - for num in temp: - q.append(num) - gires.append(q) -K = int(input()) - -for _ in range(K): - gire_num,dir = map(int,input().split()) - check_rotate=deepcopy(gires) - do_rotate(gire_num-1,dir) - -score=[1,2,4,8] -total=0 -for i in range(4): - total+=gires[i][0]*score[i] - -print(total) \ No newline at end of file diff --git "a/14912\354\210\253\354\236\220\353\271\210\353\217\204\354\210\230.py" "b/14912\354\210\253\354\236\220\353\271\210\353\217\204\354\210\230.py" deleted file mode 100644 index 511b8ee..0000000 --- "a/14912\354\210\253\354\236\220\353\271\210\353\217\204\354\210\230.py" +++ /dev/null @@ -1,6 +0,0 @@ -from collections import Counter - -n,d = input().split() -n_list = ''.join(map(str,list(range(1,int(n)+1)))) -b = Counter(n_list) -print(b[d]) \ No newline at end of file diff --git "a/14916\352\261\260\354\212\244\353\246\204\353\217\210.py" "b/14916\352\261\260\354\212\244\353\246\204\353\217\210.py" deleted file mode 100644 index 9deedcb..0000000 --- "a/14916\352\261\260\354\212\244\353\246\204\353\217\210.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -cnt = 0 -while n > 1: - if not n%5: - cnt += n//5 - n = 0 - else: - n -= 2 - cnt += 1 -print(-1 if n else cnt) \ No newline at end of file diff --git "a/14921\354\232\251\354\225\241 \355\225\251\354\204\261\355\225\230\352\270\260.py" "b/14921\354\232\251\354\225\241 \355\225\251\354\204\261\355\225\230\352\270\260.py" deleted file mode 100644 index 365aa7b..0000000 --- "a/14921\354\232\251\354\225\241 \355\225\251\354\204\261\355\225\230\352\270\260.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = list(map(int,input().split())) - -min_num = float('inf') -for i in range(N): - for j in range(N-1,0,-1): - sum_s = arr[i] + arr[j] - if abs(min_num) > abs(sum_s): - min_num = sum_s - if i == j-1: - print(min_num) - exit() - if sum_s < 0: - break - elif sum_s > 0: - continue - else: - print(0) - exit() - - diff --git "a/14921\354\232\251\354\225\241\355\225\251\354\204\261\355\225\230\352\270\260.py" "b/14921\354\232\251\354\225\241\355\225\251\354\204\261\355\225\230\352\270\260.py" deleted file mode 100644 index a9bea1e..0000000 --- "a/14921\354\232\251\354\225\241\355\225\251\354\204\261\355\225\230\352\270\260.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = list(map(int,input().split())) - -start, end = 0, N-1 -min = float('inf') - -while start < end: - _sum = arr[start] + arr[end] - if abs(min) > abs(_sum): - min = _sum - if _sum < 0: - start +=1 - else: - end -=1 - -print(min) - - diff --git "a/14923\353\257\270\353\241\234\355\203\210\354\266\234.py" "b/14923\353\257\270\353\241\234\355\203\210\354\266\234.py" deleted file mode 100644 index f625a9e..0000000 --- "a/14923\353\257\270\353\241\234\355\203\210\354\266\234.py" +++ /dev/null @@ -1,44 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def bfs(): - queue = deque() - queue.append([s_x-1,s_y-1,0,1]) - visited = [[[False for _ in range(M)] for _ in range(N)] for _ in range(2)] - visited[1][s_x-1][s_y-1] = True - while queue: - x,y,time,key = queue.popleft() - if x==t_x-1 and y==t_y-1: - return time - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx False , False-> True - if 0 <= nx <= 9 and 0 <= ny <= 9: - a[ny][nx] = not a[ny][nx] - - # 1행은 위에 먼저 끝냈고 2행부터는 위쪽에 전등이 켜져있다면 스위치를 눌러주는식으로 진행한다.(무조건 위쪽만 본다.) - for i in range(1, 10): #y좌표 - for j in range(10): #x좌표 - if not a[i-1][j]: #바로 윗 전등이 켜져있다면 스위치를 눌러줘야됨 - continue - for k in range(5): - nx = j + dx[k] - ny = i + dy[k] - if 0 <= nx <= 9 and 0 <= ny <= 9: - a[ny][nx] = not a[ny][nx] - cnt += 1 - - # 다 끝났는데 마지막열에 켜져있으면 실패. - can = True - for i in range(10): - if a[9][i] == True: - can = False - # 가능하면? ans에 최소값을 등록한다. - if can: - ans = min(cnt, ans) - -print(ans if ans != 101 else -1) \ No newline at end of file diff --git "a/14942\352\260\234\353\257\270.py" "b/14942\352\260\234\353\257\270.py" deleted file mode 100644 index 0d49185..0000000 --- "a/14942\352\260\234\353\257\270.py" +++ /dev/null @@ -1,73 +0,0 @@ -import sys, heapq - -# INF : 무한대값 -INF = 10000000000000000000000 - -# 입력부 -n = int(sys.stdin.readline()) -ant = [] -for i in range(n): - temp = int(sys.stdin.readline()) - ant.append(temp) - -# 인접 리스트 생성 -adj = [[] for _ in range(n)] -for i in range(n - 1): - a,b,c = map(int, sys.stdin.readline().split()) - adj[a - 1].append((b - 1, c)) - adj[b - 1].append((a - 1, c)) - -# ans : 정답배열, 1번 방에 사는 개미는 항상 1번이 제일 가까우므로 1을 넣고 시작 -ans = [1] - -# dijstra : 다익스트라 알고리즘 + path 갱신 -def dijstra(v): - d[v] = 0 - min_q = [] - min_q.append((d[v], v)) - while len(min_q) != 0: - distance = min_q[0][0] - current = min_q[0][1] - heapq.heappop(min_q) - if d[current] < distance: - continue - for i in range(len(adj[current])): - next = adj[current][i][0] - nextdistance = adj[current][i][1] + distance - if nextdistance < d[next]: - d[next] = nextdistance - # next에서 인접한 방들 중 가장 짧은 거리는 current다 - path[next].append(current) - heapq.heappush(min_q, (nextdistance, next)) - -d = [INF] * n -path = [[] for _ in range(n)] - -# 1번방 기준 다익스트라 -dijstra(0) -for i in range(1,n): - for j in adj[i]: - # 만일 최단 거리 방이 맞다면, 그때의 에너지 소모량도 같이 저장한다 - if j[0] == path[i][0]: - path[i].append(j[1]) - -# 1번 방의 경우 예외처리 -path[0] = [0,0] - -for i in range(1, n): - energy = ant[i] - route = i - # 지속적으로 path 배열을 타고 올라가다가 에너지가 0이하가 되면 정답 리턴 - while True: - energy -= path[route][1] - if energy < 0: - ans.append(route + 1) - break - elif route == 0: - ans.append(route + 1) - break - route = path[route][0] - -# 정답 출력 -for i in ans: - print(i) \ No newline at end of file diff --git "a/14945\353\266\210\354\236\245\353\202\234.py" "b/14945\353\266\210\354\236\245\353\202\234.py" deleted file mode 100644 index ff8b8c0..0000000 --- "a/14945\353\266\210\354\236\245\353\202\234.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -dp = [[0]*(n+1) for _ in range(n+1)] -dp[2][1] = 2 -for i in range(3,n+1): - for j in range(1,i): - dp[i][j] = (dp[i-1][j]*2 + dp[i-1][j-1] + dp[i-1][j+1])%10007 -sum_n = 0 -for i in range(1,n): - sum_n += dp[n][i] -print(sum_n%10007) \ No newline at end of file diff --git "a/1497\352\270\260\355\203\200\354\275\230\354\204\234\355\212\270.py" "b/1497\352\270\260\355\203\200\354\275\230\354\204\234\355\212\270.py" deleted file mode 100644 index 742cb80..0000000 --- "a/1497\352\270\260\355\203\200\354\275\230\354\204\234\355\212\270.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline -from itertools import combinations - -# 기타 플레이 리스트 이진수로 바꿔서 set에 저장. -N,M = map(int,input().split()) -guitars = set() -for _ in range(N): - name,pos = input().split() - bin_change='' - for chr in pos: - if chr=="Y": - bin_change += '1' - else: - bin_change += '0' - guitars.add(int(bin_change,2)) - -# 셋에서 0 제거하고 비었으면 -1출력후 종료 -guitars -={0} -if not guitars: - print(-1) - exit() -max_cnt=0 -# 1개~N개까지 set에서 추출하는 조합 검사(N이 set길이 넘어가면 자동 종료.) -for i in range(1,N+1): - for combs in combinations(guitars,i): - # total에 각각 조합마다 이진수 연산. - total=0 - for num in combs: - total |=num - # 연산한 total에서 Y몇개인지 확인. - cnt=0 - for j in range(M): - if total&(1< matrix[i][k] + matrix[k][j]: - result = -1 - -if result != -1: - for i in range(n): - for j in range(i, n): - if edge[i][j]: - result += matrix[i][j] -print(result) \ No newline at end of file diff --git "a/1509\355\216\240\353\246\260\353\223\234\353\241\254\353\266\204\355\225\240.py" "b/1509\355\216\240\353\246\260\353\223\234\353\241\254\353\266\204\355\225\240.py" deleted file mode 100644 index 650cfbe..0000000 --- "a/1509\355\216\240\353\246\260\353\223\234\353\241\254\353\266\204\355\225\240.py" +++ /dev/null @@ -1,36 +0,0 @@ -import sys -input = sys.stdin.readline - -strings = input().rstrip() -n = len(strings) - -dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)] -result = [float('inf')] * (n+1) -result[0] = 0 - -# 일단 자기자신을 분할로 갖는 펠린드롭 -for i in range(1, n+1): - dp[i][i] = 1 - -# 전놈이랑 나랑 같으면 하나 -for i in range(1, n): - if strings[i-1] == strings[i]: - dp[i][i+1] = 1 - -# i는 크기. j는 시작점. j에서 i만큼의 길이를 가진 문자열이 펠린드롬이냐를 확인. -# dp[j+1][i+j-1] 즉 문자열 j-1과 j+i-1이 같고 그 안쪽 dp가 1을 가질때 스트링을 포함한 문자열도 펠린드롭. -for i in range(2, n): - for j in range(1, n+1-i): - if strings[j-1] == strings[j+i-1] and dp[j+1][i+j-1] == 1: - dp[j][i+j] = 1 - -# i를 진행하면서 그 뒤쪽의 result값에 대해 j가 계속 최신화를 시켜주며 최솟값으로 갱신시킴. -for i in range(1, n+1): - result[i] = min(result[i], result[i-1] + 1) -# result[i-1]+1인 이유는 result[i-1]까지의 팰린드롭에 j부터 i까지의 팰린드롭 한개를 더하는 것이기 때문이다 - for j in range(i+1, n+1): - if dp[i][j] != 0: - # 팰린드롭이면 - result[j] = min(result[j], result[i-1] + 1) - -print(result[n]) \ No newline at end of file diff --git "a/1516 \352\262\214\354\236\204\352\260\234\353\260\234.py" "b/1516 \352\262\214\354\236\204\352\260\234\353\260\234.py" deleted file mode 100644 index e74ccd9..0000000 --- "a/1516 \352\262\214\354\236\204\352\260\234\353\260\234.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def topological_sort(): - visited = {i: False for i in range(1, N + 1)} - q = deque() - for node in levels: - if not levels[node]: - q.append(node) - visited[node] = True - while q: - cur_node = q.popleft() - for next_node in next_nodes[cur_node]: - levels[next_node] -= 1 - if not visited[next_node] and not levels[next_node]: - visited[next_node] = True - q.append(next_node) - max_cost = 0 - for node in pre_nodes[next_node]: - if max_cost < costs[node]: - max_cost = costs[node] - costs[next_node] += max_cost - -N = int(input()) -costs = [0] -next_nodes = {i: [] for i in range(1, N + 1)} -pre_nodes = {} -levels = {i: 0 for i in range(1, N + 1)} -for node in range(1, N + 1): - command = list(map(int, input().split())) - costs.append(command[0]) - for pre_node in command[1:-1]: - next_nodes[pre_node].append(node) - pre_nodes[node] = command[1:-1] - levels[node] = len(command) - 2 - -topological_sort() -for each in costs[1:]: - print(each) \ No newline at end of file diff --git a/1517segment.py b/1517segment.py deleted file mode 100644 index f6d3a4f..0000000 --- a/1517segment.py +++ /dev/null @@ -1,33 +0,0 @@ -import sys -from math import ceil,log2 -input=sys.stdin.readline - -# 인덱스 트리 활용. 배열 앞에서부터 자신보다 큰값이 몇개인지. -p=1000000 -def find(start,end,left,right,node): - if start>right or end=1: - tree[temp]+=1 - temp//=2 -n=int(input()) -data=list(map(int,input().split())) -size=2**ceil(log2(p)) -tree=[0]*(size*2) -ans=0 -print(tree[1048576:1048600]) -for i in data: - print(i,'z') - print(find(1,size,i+1,size,1)) - ans+=find(1,size,i+1,size,1) - update(i) - print(tree[1048576:1048600]) - -print(ans) \ No newline at end of file diff --git "a/1517\353\262\204\353\270\224\354\206\214\355\212\270.py" "b/1517\353\262\204\353\270\224\354\206\214\355\212\270.py" deleted file mode 100644 index bc23338..0000000 --- "a/1517\353\262\204\353\270\224\354\206\214\355\212\270.py" +++ /dev/null @@ -1,51 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10 ** 9) - - - -# 병합 정렬을 사용 반으로 나눈 뒤 합치는 과정에서 오른쪽 배열에 오는 수가 들어갈때 -# 왼쪽 배열에 있는 수가 남아있다면 바꿔줘야 할 쌍의 수일 것이므로 남아있는 요소들의 수만큼 정답에 더해주면 된다. -def merge_sort(start, end): - global swap, arr - size = end - start - mid = (start + end) // 2 - if size <= 1: - return - - - # divide - merge_sort(start, mid) - merge_sort(mid, end) - - # merge - new_arr = [] - idx1, idx2 = start, mid - cnt = 0 - while idx1 < mid and idx2 < end: - if arr[idx1] > arr[idx2]: - new_arr.append(arr[idx2]) - idx2 += 1 - cnt += 1 - else: # arr[idx1] < arr[idx2] - new_arr.append(arr[idx1]) - idx1 += 1 - swap += cnt - - while idx1 < mid: - new_arr.append(arr[idx1]) - idx1 += 1 - swap += cnt - while idx2 < mid: - new_arr.append(arr[idx2]) - idx2 += 1 - - # reflect - for t in range(len(new_arr)): - arr[start + t] = new_arr[t] - -n = int(input()) -arr = list(map(int, input().split())) -swap = 0 -merge_sort(0, n) -print(swap) diff --git "a/1517\353\262\204\353\270\224\354\206\214\355\212\270_\355\216\234\354\234\205.py" "b/1517\353\262\204\353\270\224\354\206\214\355\212\270_\355\216\234\354\234\205.py" deleted file mode 100644 index bb8c868..0000000 --- "a/1517\353\262\204\353\270\224\354\206\214\355\212\270_\355\216\234\354\234\205.py" +++ /dev/null @@ -1,57 +0,0 @@ -import sys - - - -# fenwick_update : 펜윅 트리인 tree의 idx번째 노드를 d로 갱신하는 함수 -def fenwick_update(tree, idx, d): - while idx <= n: - tree[idx] += d - idx += (idx & -idx) - -# fenwick_find : 펜윅 트리인 tree의 start번째 노드부터 end번째 노드까지의 합을 리턴하는 함수 -def fenwick_find(tree, start, end): - if end < start: - return 0 - res = 0 - idx = end - while idx > 0: - res += tree[idx] - idx -= (idx & -idx) - idx = start - 1 - while idx > 0: - res -= tree[idx] - idx -= (idx & -idx) - return res - -# relation_convert : 배열 arr의 원소들을 대소 관계를 유지하는 상대 값으로 바꾼 배열을 리턴하는 함수 -def relation_convert(arr): - sort_arr = sorted(arr) - mid = dict().fromkeys(sort_arr, 0) - res = [] - visited = [False] * (len(arr) + 1) - for idx, temp in enumerate(mid): - mid[temp] = idx + 1 - for i in arr: - if visited[mid[i]] == False: - res.append(mid[i]) - visited[mid[i]] = True - return res - -# 입력부 -n = int(sys.stdin.readline()) -before = list(map(int, sys.stdin.readline().split())) - -# after = before의 상대 배열 -after = relation_convert(before) - -# ftr : 펜윅 트리 -ftr = [0] * (n + 1) -ans = 0 -for i in range(len(after)): - # 자신보다 큰 수의 갯수를 ans에 저장하고 - ans += (fenwick_find(ftr, after[i], len(after))) - # 저장했으면 자신을 넣는다 - fenwick_update(ftr, after[i], 1) - -# 정답 출력 -print(ans) \ No newline at end of file diff --git "a/1535 \354\225\210\353\205\225.py" "b/1535 \354\225\210\353\205\225.py" deleted file mode 100644 index 7c6f33f..0000000 --- "a/1535 \354\225\210\353\205\225.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - - -N = int(input()) -L = [0] + list(map(int, input().split())) -P = [0] + list(map(int, input().split())) -dp = [[0] * 101 for _ in range(N+1)] - -for i in range(1, N+1): - for j in range(1, 101): - if L[i] <= j: - dp[i][j] = max(dp[i-1][j], dp[i-1][j-L[i]] + P[i]) - else: - dp[i][j] = dp[i-1][j] - -print(dp[N][99]) - diff --git "a/1541\354\236\203\354\226\264\353\262\204\353\246\260 \352\264\204\355\230\270.py" "b/1541\354\236\203\354\226\264\353\262\204\353\246\260 \352\264\204\355\230\270.py" deleted file mode 100644 index 6c68e0f..0000000 --- "a/1541\354\236\203\354\226\264\353\262\204\353\246\260 \352\264\204\355\230\270.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - - -expression = input().split('-') -new_expression = [] -for ex in expression: - nums = ex.split('+') - sum_n = 0 - for num in nums: - sum_n += int(num) - new_expression.append(sum_n) -print(2*new_expression[0] - sum(new_expression)) diff --git "a/1550_16\354\247\204\354\210\230.py" "b/1550_16\354\247\204\354\210\230.py" deleted file mode 100644 index da1100e..0000000 --- "a/1550_16\354\247\204\354\210\230.py" +++ /dev/null @@ -1,2 +0,0 @@ - -print(int(input(),16)) \ No newline at end of file diff --git "a/15552\353\271\240\353\245\270\353\215\247\354\205\210.py" "b/15552\353\271\240\353\245\270\353\215\247\354\205\210.py" index 6e8e6df..f3ec18f 100644 --- "a/15552\353\271\240\353\245\270\353\215\247\354\205\210.py" +++ "b/15552\353\271\240\353\245\270\353\215\247\354\205\210.py" @@ -1,6 +1,6 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - a,b = map(int,input().split()) +import sys +input = sys.stdin.readline + +for test in range(int(input())): + a,b = map(int,input().split()) print(a+b) \ No newline at end of file diff --git "a/15565\352\267\200\354\227\254\354\232\264\353\235\274\354\235\264\354\226\270.py" "b/15565\352\267\200\354\227\254\354\232\264\353\235\274\354\235\264\354\226\270.py" deleted file mode 100644 index b133c05..0000000 --- "a/15565\352\267\200\354\227\254\354\232\264\353\235\274\354\235\264\354\226\270.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) -dolls = list(map(int, input().split())) - -left = 0 -lion_cnt = 0 -min_size = float('inf') -for right in range(N): - - if dolls[right]==1: - lion_cnt += 1 - if lion_cnt==1: - left = right - while lion_cnt > K: - left += 1 - if dolls[left]==1: - lion_cnt -= 1 - if lion_cnt == K: - min_size = min(min_size,right-left+1) -if min_size==float('inf'): - print(-1) -else: - print(min_size) diff --git "a/15566\352\260\234\352\265\254\353\246\2541.py" "b/15566\352\260\234\352\265\254\353\246\2541.py" deleted file mode 100644 index eebb868..0000000 --- "a/15566\352\260\234\352\265\254\353\246\2541.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - - -def DFS(depth,flogs): - if depth==N: - print('YES') - print(*flogs) - exit() - for leaf in range(1,N+1): - if not visited_leaf[leaf]: # 배치 안된 잎 - for flog in range(1,N+1): - if not choosed_flog[flog]: # 배치 안된 개구리 - if leaf in favor_leaf[flog]: # 선호하는 연꽃에 배치. - # 연결된 통나무 반대편 노드 검사. 통나무 번호의 c값에 대해 양 개구리의 선호도가 일치하는지 확인. - for next_leaf,topic in graph[leaf]: - if visited_leaf[next_leaf] and frog_favor_topic[flog][topic] != frog_favor_topic[visited_leaf[next_leaf]][topic]: - return - visited_leaf[leaf] = flog - choosed_flog[flog] = True - DFS(depth+1,flogs+[flog]) - visited_leaf[leaf] = 0 - choosed_flog[flog] = False - - -N, M = map(int, input().split()) -frog_favor_topic = {i: [0] + list(map(int, input().split())) for i in range(1,N+1)} -favor_leaf = {i: list(map(int,input().split())) for i in range(1, N+1)} -graph = {i:[] for i in range(1, N+1)} -visited_leaf = {i: 0 for i in range(1,N+1)} -choosed_flog = {i: False for i in range(1,N+1)} -for _ in range(M): - a,b,c = map(int, input().split()) - graph[a].append((b,c)) - graph[b].append((a,c)) - - -DFS(0,[]) -print('NO') \ No newline at end of file diff --git "a/15566\352\260\234\352\265\254\353\246\2541_2\354\260\250\354\213\234\353\217\204.py" "b/15566\352\260\234\352\265\254\353\246\2541_2\354\260\250\354\213\234\353\217\204.py" deleted file mode 100644 index 0171d70..0000000 --- "a/15566\352\260\234\352\265\254\353\246\2541_2\354\260\250\354\213\234\353\217\204.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - - -N, M = map(int, input().split()) -frog_favor_topic = {i: [0] + list(map(int, input().split())) for i in range(1,N+1)} -favor_leaf = {i: list(map(int,input().split())) for i in range(1, N+1)} -graph = {i:[] for i in range(1, N+1)} -visited_leaf = {i: 0 for i in range(1,N+1)} -choosed_flog = {i: False for i in range(1,N+1)} -for _ in range(M): - a,b,c = map(int, input().split()) - graph[a].append((b,c)) - graph[b].append((a,c)) \ No newline at end of file diff --git "a/1561\353\206\200\354\235\264\352\263\265\354\233\220.py" "b/1561\353\206\200\354\235\264\352\263\265\354\233\220.py" deleted file mode 100644 index 487de56..0000000 --- "a/1561\353\206\200\354\235\264\352\263\265\354\233\220.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - -def isPossible(mid): - cnt=0 - for i in range(M): - cnt += mid//amusement[i] + 1 - if cnt >=N: - return True - return False -# N명의 아이들 한줄 -# M개의 1인승 놀이기구 -# 운행시간 지나면 탑승하고 있던 아이 내리고 줄 맨앞에 있던 아이가 빈 놀이기구로 들어감. -# 동시에 비어있으면 제일 앞에있는 놀이기구. - -N,M=map(int,input().split()) -amusement = list(map(int,input().split())) - -start=0 -end = 6e10 -answer=0 -while start <= end: - mid = (start + end)//2 - if isPossible(mid): - end = mid-1 - answer=mid - else: - start = mid+1 - -cnt_last_time =0 -for i in range(M): - cnt_last_time += (answer-1)//amusement[i] + 1 - -for i in range(M): - if not answer%amusement[i]: - cnt_last_time+=1 - if cnt_last_time==N: - print(i+1) - exit() \ No newline at end of file diff --git "a/1562\352\263\204\353\213\250\354\210\230.py" "b/1562\352\263\204\353\213\250\354\210\230.py" deleted file mode 100644 index 372485c..0000000 --- "a/1562\352\263\204\353\213\250\354\210\230.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) - -# dp: 비트 정보, 자릿 수, 끝나는 수 -dp = [[[0] * 10 for _ in range(101)] for _ in range(1 << 10)] - -# 처음 시작값을 1로 초기화(어떤 숫자로 시작하는지에 따른 경우의수.모두 1씩 주고 시작.) -for i in range(1, 10): - dp[1< 000001110즉 3에서 4를 추가하고싶다면 - # 1024는 계단의 숫자를 썻는지 안썼는지에 대한 경우의 수. 거기에 저장하는건. 그 전 자릿수가 +1이나 -1로 끝난것의 합을 모두 더해주는것. - for bm in range(1024): - # 0과 9는 앞뒤로 한칸씩 밖에 못더해줌 즉 0은 e<9의 전자릿수 1에서의 합만 받고 9는 e>0의 전자릿수 8의 합만 받음. - if e < 9: - dp[bm | (1< 0: - dp[bm | (1<= 0 and a[j-1][i]: - continue - if j + 1 < n and a[j+1][i]: - continue - # 선 없으면 선넣고 탐색. - a[j][i] = 1 - dfs(cnt + 1, i, r) - a[j][i] = 0 - -n, m, h = map(int, input().split()) -# a는 선이 연결되었음을 표시. -a = [[0]*h for _ in range(n)] -for _ in range(m): - x, y = map(int, input().split()) - a[y-1][x-1] = 1 - -ans, flag = sys.maxsize, 1 -for r in range(4): - dfs(0, 0, r) - if ans != sys.maxsize: - print(ans) - flag = 0 - break -if flag: - print(-1) - -""" -1. 연결을 저장하는 리스트 a를 만든다 - a는 2차 리스트인데 a[세로][가로] 로 사용한다 - 따라서 a의 크기는 n x h이다 - -2. a에 연결 관계를 저장한다 - a[y-1][x-1]은 y-1번째 세로일 때 x-1번째 가로에서 x번째 가로로 이동할 수 있음을 의미한다 - -3. dfs로 구현한 조합으로 어느 가로선을 연결할 지 정한다 - -4. dfs에서 연결할 선을 고를 때 다른 가로선과 이어지면 안되는 조건을 고려해야한다 - 현재 위치를 세로j , 가로i 라고 할 때 j-1번 째 세로와 j+1번 째 세로에 연결된 가로선이 있는지 확인한다 - -5. 연결할 가로선을 모두 고르면 move 함수를 실행해서 출발한 세로선과 도착한 세로선의 인덱스가 같은지 확인한다 - -6. 만일 같으면 ans에 가로선을 고른 개수를 저장하고 return한다 - -7. ans가 값이 변했으면 ans을 출력하고 종료한다 -""" \ No newline at end of file diff --git "a/15685\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214.py" "b/15685\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214.py" deleted file mode 100644 index fe24941..0000000 --- "a/15685\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - - -dx = [1, 0, -1, 0] -dy = [0, -1, 0, 1] - -n = int(input()) -matrix = [[0 for _ in range(101)] for _ in range(101)] - -for i in range(n): - x, y, d, g = map(int, input().split()) - # 최초 노드 x,y, 전체노드, 추가되는 노드방향성(증감성) 초기화. - matrix[x][y] = 1 - next_direction = [d] - cur_direction = [d] - # 세대수만큼 반복. - for generation in range(g + 1): - # 각 노드의 방향성에 따른 증감을 반영하며 드래곤 커브 실시. - for direction in cur_direction: - nx = x + dx[direction] - ny = y + dy[direction] - matrix[nx][ny] = 1 - x,y = nx,ny - # 세대가 지날수록 각 노드들은 방향성이 1만큼 증가. 0~3순환 - # 다음 세대에 진행할 노드방향성. - cur_direction = [(cur_direction + 1) % 4 for cur_direction in next_direction] - # 세대 순환은 가장 마지막에 도착한 노드부터 출발. - cur_direction.reverse() - # 다음 세대 추가 완료. - next_direction = next_direction + cur_direction - -# 정사각형 탐색. -cnt = 0 -for i in range(100): - for j in range(100): - if matrix[i][j] and matrix[i][j + 1] and matrix[i + 1][j] and matrix[i + 1][j + 1]: - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/15685\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214_re.py" "b/15685\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214_re.py" deleted file mode 100644 index b95da86..0000000 --- "a/15685\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214_re.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline - -delta = ((1, 0), (0, -1), (-1, 0), (0, 1)) -N = int(input()) -curves = set() -for _ in range(N): - x, y, d, g = map(int, input().split()) - # (x,y)시작, 처음 d방향으로 시작,(처음 선분하나로 시작) g 세대까지 진행.(1개추가, 2개추가, 4개 추가, 8개 추가.. 90도 회전시키며.) - curves.add((x, y)) - cur_dragon = [d] - next_dragon = [d] - for _ in range(g+1): - for d in cur_dragon: - nx, ny = x + delta[d][0], y + delta[d][1] - curves.add((nx, ny)) - x, y = nx, ny - cur_dragon = [(d + 1) % 4 for d in next_dragon[::-1]] - next_dragon = next_dragon + cur_dragon - -cnt = 0 -for i in range(100): - for j in range(100): - if (i, j) in curves and (i + 1, j) in curves and (i, j + 1) in curves and (i + 1, j + 1) in curves: - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/15686\354\271\230\355\202\250\353\260\260\353\213\254.py" "b/15686\354\271\230\355\202\250\353\260\260\353\213\254.py" index eaa6a44..c774563 100644 --- "a/15686\354\271\230\355\202\250\353\260\260\353\213\254.py" +++ "b/15686\354\271\230\355\202\250\353\260\260\353\213\254.py" @@ -1,31 +1,24 @@ -from itertools import combinations - -# 맵크기(N), 치킨집 최대 선택가능개수(M) -N, M = map(int, input().split()) -board = [list(map(int, input().split())) for _ in range(N)] - -# 빈칸(0), 집(1), 치킨집(2) // 그래프 그리기. -house = [] -chicken = [] -for i in range(N): - for j in range(N): - if board[i][j] == 1: - house.append((i, j)) - elif board[i][j] == 2: - chicken.append((i, j)) - -# 모든 치킨집 조합에 대해 -minv = float('inf') -for ch in combinations(chicken, M): - sumv = 0 - # 모든 집들에 대해 치킨집 조합에 속한 치킨집들에 대한 거리의 합이 최솟값보다 작으면 최신화.(거리값은 x좌표 차이 절댓값 + y좌표차이 절댓값.) - # min에 들어가는 인자수는 치킨집 수만큼 돌아가고 그중 각 집집마다 최솟값만 골라서 sum에 합산. - for home in house: - sumv += min([abs(home[0]-i[0])+abs(home[1]-i[1])] for i in ch) - if minv <= sumv: - break - if sumv < minv: - minv = sumv - -print(minv) - +from itertools import combinations + +# 맵크기(N), 치킨집 최대 선택가능개수(M) +N, M = map(int, input().split()) +board = [list(map(int, input().split())) for _ in range(N)] + +# 빈칸(0), 집(1), 치킨집(2) +house = [] +chicken = [] +for i in range(N): + for j in range(N): + if board[i][j] == 1: house.append((i, j)) + elif board[i][j] == 2: chicken.append((i, j)) + +minv = float('inf') +for ch in combinations(chicken, M): + sumv = 0 + for home in house: + sumv += min([abs(home[0]-i[0])+abs(home[1]-i[1]) for i in ch]) + if minv <= sumv: break + if sumv < minv: minv = sumv + +print(minv) + diff --git "a/15686\354\271\230\355\202\250\353\260\260\353\213\254_2.py" "b/15686\354\271\230\355\202\250\353\260\260\353\213\254_2.py" deleted file mode 100644 index a083294..0000000 --- "a/15686\354\271\230\355\202\250\353\260\260\353\213\254_2.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - -from itertools import combinations - -# 맵크기(N), 치킨집 최대 선택가능개수(M) -N, M = map(int, input().split()) -board = [list(map(int, input().split())) for _ in range(N)] - -# 빈칸(0), 집(1), 치킨집(2) // 그래프 그리기. -house = [] -chicken = [] -for i in range(N): - for j in range(N): - if board[i][j] == 1: - house.append((i, j)) - elif board[i][j] == 2: - chicken.append((i, j)) - -# 모든 치킨집 조합에 대해 -minv = float('inf') -for ch in combinations(chicken, M): - sumv = 0 - # 모든 집들에 대해 치킨집 조합에 속한 치킨집들에 대한 거리의 합이 최솟값보다 작으면 최신화.(거리값은 x좌표 차이 절댓값 + y좌표차이 절댓값.) - # min에 들어가는 인자수는 치킨집 수만큼 돌아가고 그중 각 집집마다 최솟값만 골라서 sum에 합산. - for home in house: - sumv += min([abs(home[0]-i[0])+abs(home[1]-i[1]) for i in ch]) - if minv <= sumv: - break - if sumv < minv: - minv = sumv - -print(minv) - diff --git "a/15723 n\353\213\250\353\205\274\353\262\225.py" "b/15723 n\353\213\250\353\205\274\353\262\225.py" deleted file mode 100644 index 19693b1..0000000 --- "a/15723 n\353\213\250\353\205\274\353\262\225.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline - - -def DFS(cur_node, target): - if cur_node==target: - return True - for next_node in graph[cur_node]: - if not visited[next_node]: - visited[next_node] = True - if DFS(next_node, target): - return True - - -n = int(input()) -graph = {i:[] for i in range(26)} -level = {i:0 for i in range(26)} -for _ in range(n): - first, arrow, end = input().split() - first_num = ord(first)-97 - end_num = ord(end)-97 - graph[first_num] += [end_num] -m = int(input()) -for _ in range(m): - first, arrow, end = input().split() - visited = {i:False for i in range(26)} - first_num = ord(first)-97 - end_num = ord(end)-97 - visited[first_num] = True - print('T' if DFS(first_num,end_num) else 'F') - diff --git "a/15724 \354\243\274\354\247\200\354\210\230.py" "b/15724 \354\243\274\354\247\200\354\210\230.py" deleted file mode 100644 index 2d0ec7d..0000000 --- "a/15724 \354\243\274\354\247\200\354\210\230.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -areas = [list(map(int, input().split())) for _ in range(N)] -K = int(input()) -dp = [[0 for _ in range(M+1)] for _ in range(N+1)] -dp[1][1] = areas[0][0] -for i in range(1,N+1): - for j in range(1,M+1): - dp[i][j] = dp[i-1][j] + dp[i][j-1] + areas[i-1][j-1] - dp[i-1][j-1] -for _ in range(K): - x1,y1,x2,y2 = map(int, input().split()) - print(dp[x2][y2] - dp[x1-1][y2] - dp[x2][y1-1] + dp[x1-1][y1-1]) - - - - - - - - - - - - - - - - - - - - - - - - - diff --git "a/15730\354\210\230\354\230\201\354\236\245\354\202\254\354\236\245\353\213\230.py" "b/15730\354\210\230\354\230\201\354\236\245\354\202\254\354\236\245\353\213\230.py" index 33a8cd5..27f7370 100644 --- "a/15730\354\210\230\354\230\201\354\236\245\354\202\254\354\236\245\353\213\230.py" +++ "b/15730\354\210\230\354\230\201\354\236\245\354\202\254\354\236\245\353\213\230.py" @@ -1,42 +1,42 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def BFS(x,y,h): - global result - queue = deque() - queue.append([x,y]) - dx = [0,0,1,-1] - dy = [1,-1,0,0] - out_rain = False - cnt = 1 - visited[x][y] = True - while queue: - x,y = queue.popleft() - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx 0: - cur_union_cnt, king = heappop(count_set) - if check[king] != check[C] and check[king] != check[H]: - power -= cur_union_cnt - K -= 1 -print(power) \ No newline at end of file diff --git "a/15789CTP_\353\257\274\352\265\254\353\213\230\355\222\200\354\235\264_union_find and set.py" "b/15789CTP_\353\257\274\352\265\254\353\213\230\355\222\200\354\235\264_union_find and set.py" deleted file mode 100644 index ef6aa0c..0000000 --- "a/15789CTP_\353\257\274\352\265\254\353\213\230\355\222\200\354\235\264_union_find and set.py" +++ /dev/null @@ -1,55 +0,0 @@ -import sys -input = sys.stdin.readline - -# 서로소 집합 자료구조 (합치기 찾기 자료구조) - -# 지원함수 1 : 유니온 - 합치기 -def union(a, b): - a = find(a) - b = find(b) - - # 갱신 내지 재정의 - if b < a: - parent[a] = b - else: - parent[b] = a - -# 지원함수 2 : find - 루트 노드를 찾을때까지 재귀적으로 반환 -def find(a): - if a == parent[a]: - return a - parent[a] = find(parent[a]) - return parent[a] - -# 정점 수, 관계 수 -N, M = map(int, input().split()) - -# 서로소 집합용 입력 정보 -parent = list(range(N+1)) - -# 간선 정보 정리 -for _ in range(M): - a, b= map(int, input().split()) - union(a,b) - - -# 그루핑 -groups = [set() for _ in range(N+1)] -for i in range(1, N+1): - groups[find(i)].add(i) - -#print(groups) -# CTP 왕국, 한솔 왕국, 동맹 기회 -C, H, K = map(int, input().split()) - -# 출력 -answer = 0 -answers = list() -for group in groups: - if C in group: - answer += len(group) - elif not H in group: - answers.append(len(group)) -answers.sort(reverse=True) - -print(answer + sum(answers[:K])) \ No newline at end of file diff --git "a/15810\355\222\215\354\204\240\352\263\265\354\236\245.py" "b/15810\355\222\215\354\204\240\352\263\265\354\236\245.py" deleted file mode 100644 index 2c05354..0000000 --- "a/15810\355\222\215\354\204\240\352\263\265\354\236\245.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline - -def isPossible(target_time): - balloon=0 - for staff in make_balloon: - balloon += target_time//staff - if balloon>=M: - return True - return False - -N,M = map(int,input().split()) -make_balloon = list(map(int,input().split())) - -start = 0 -end = 1e12 -answer = 0 -while start<=end: - mid = (start+end)//2 - if isPossible(mid): - end = mid-1 - answer=mid - else: - start = mid+1 - -print(int(answer)) \ No newline at end of file diff --git "a/15823 \354\271\264\353\223\234\355\214\251 \352\265\254\353\247\244\355\225\230\352\270\260.py" "b/15823 \354\271\264\353\223\234\355\214\251 \352\265\254\353\247\244\355\225\230\352\270\260.py" deleted file mode 100644 index 847d05a..0000000 --- "a/15823 \354\271\264\353\223\234\355\214\251 \352\265\254\353\247\244\355\225\230\352\270\260.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -N, M = map(int, input().split()) -cards = list(map(int, input().split())) -cards.append(cards[-1]) - -# 연속된 카드 묶기. 정확히 M개의 카드팩. 같은 종류 카드 두장되면 안됨. -# 카드팩의 최대 길이. -left = 0 -pack_cnt = [] -card_pack = defaultdict(int) -for right in range(N+1): - card_pack[cards[right]] += 1 - if card_pack[cards[right]] > 1: - pack_cnt.append(right-left) - while card_pack[cards[right]] > 1: - card_pack[cards[left]] -= 1 - left += 1 - -pack_cnt.sort(reverse=True) -for i in range(max(pack_cnt),1,-1): - max_cnt = 0 - for cnt in pack_cnt: - max_cnt += cnt//i - if max_cnt >= M: - print(i) - exit() -else: - print(1) \ No newline at end of file diff --git "a/15823\354\235\264\353\266\204\355\203\220\354\203\211.py" "b/15823\354\235\264\353\266\204\355\203\220\354\203\211.py" deleted file mode 100644 index 21d0646..0000000 --- "a/15823\354\235\264\353\266\204\355\203\220\354\203\211.py" +++ /dev/null @@ -1,84 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - - -def is_Possible(pack_size): - visited = defaultdict(int) - cnt = 0 - left = 0 - for right in range(N+1): - visited[cards[right]] += 1 - while visited[cards[right]] > 1: - visited[cards[left]] -= 1 - left += 1 - if right-left+1 == pack_size: - cnt += 1 - while left != right: - visited[cards[left]] -= 1 - left += 1 - if cnt >= M: - return True - return False - - - -N, M = map(int, input().split()) -cards = list(map(int, input().split())) -cards.append(cards[-1]) -left = 1 -right = N -answer = 0 -while left <= right: - mid = (left+right)//2 - if is_Possible(mid): - left = mid + 1 - answer = mid - else: - right = mid - 1 -print(answer) - - -def my_bisect(lo, hi): - answer = 0 - while lo <= hi: - mid = (lo + hi) // 2 - cnt = count_m(mid) - if cnt >= M: - answer = mid - lo = mid + 1 - else: - hi = mid - 1 - return answer - -# # 길이가 m인 윈도우(팩) 수 // 슬라이딩 윈도우가 아니라 윈도우 실패함수.를 dict로 구현. -# def count_m(mid): -# cnt = 0 -# move = 0 - -# while mid + move <= N: -# # 같은 거 중복할때까지 전진 -# visited = dict() -# for i in range(move, move + mid): -# # 중복시 다음 스타트 지점 -# # 전에 나온놈 인덱스 저장하고 중복시 여기인덱스 바로 뒤로 점프해 다시탐색(실패함수.) -# if cards[i] not in visited: -# visited[cards[i]] = i -# else: -# move = visited[cards[i]] + 1 -# break -# # 반복문 후 else = 반복문 종료시 1회 실행 -# else: -# cnt = cnt + 1 -# move = move + mid - -# return cnt - - -# N, M = map(int, input().split()) -# cards = list(map(int, input().split())) - -# # 카드팩 최소, 최대 크기 -# lo = 1 -# hi = N//M -# print(my_bisect(lo, hi)) \ No newline at end of file diff --git "a/15824 \353\204\210 \353\264\204\354\227\220\353\212\224 \354\272\241\354\202\254\354\235\264\354\213\240\354\235\264 \353\247\233\354\236\210\353\213\250\353\213\244.py" "b/15824 \353\204\210 \353\264\204\354\227\220\353\212\224 \354\272\241\354\202\254\354\235\264\354\213\240\354\235\264 \353\247\233\354\236\210\353\213\250\353\213\244.py" deleted file mode 100644 index 2cf294a..0000000 --- "a/15824 \353\204\210 \353\264\204\354\227\220\353\212\224 \354\272\241\354\202\254\354\235\264\354\213\240\354\235\264 \353\247\233\354\236\210\353\213\250\353\213\244.py" +++ /dev/null @@ -1,61 +0,0 @@ -import sys -input = sys.stdin.readline - -# 제곱을 재귀로.. 분할정복으로 해도 될듯? -def pow(a,b,c): - if b==0: - return 1 - if b==1 : - return a%c - if b%2==0: - return pow(a**2%c,b//2,c) - else: - return a*pow(a**2%c,b//2,c)%c - -N = int(input()) -menus = sorted(map(int,input().split())) -MOD = 1000000007 -minus = 0 -plus = 0 -for i in range(N): - minus += (menus[i]%MOD)*pow(2,N-i-1,MOD) - plus += (menus[i]%MOD)*pow(2,i,MOD) - plus %= MOD -print((plus-minus)%MOD) - - - -# 50점 -# import sys -# input = sys.stdin.readline - -# N = int(input()) -# menus = sorted(map(int,input().split())) -# MOD = 1000000007 -# minus = 0 -# for i in range(N-1): -# for j in range(i+1,N): -# minus += ((menus[j] - menus[i])*(2**(j-i-1)))%MOD -# print(minus%MOD) - -# logN의 파워함수. -# def power(a, n): -# ret = 1 -# while n > 0: -# if n % 2 != 0: -# ret *= a -# a *= a -# n //= 2 - -# return ret - -# logN power -# def power(n, p): -# if p == 0: -# return 1 -# # Call this only once, instead of two times. -# power_p_divided_by_2 = power(n, p // 2) -# if p % 2: -# return n * power_p_divided_by_2 * power_p_divided_by_2 -# else: -# return power_p_divided_by_2 * power_p_divided_by_2 \ No newline at end of file diff --git "a/15831 \354\244\200\355\221\234\354\235\230 \354\241\260\354\225\275\353\217\214.py" "b/15831 \354\244\200\355\221\234\354\235\230 \354\241\260\354\225\275\353\217\214.py" deleted file mode 100644 index b911a73..0000000 --- "a/15831 \354\244\200\355\221\234\354\235\230 \354\241\260\354\225\275\353\217\214.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -N, B, W = map(int, input().split()) -stone = input().rstrip() -# 까만색 B개 이하, 흰색은W개 이상 -left = 0 -w_cnt = 0 -b_cnt = 0 -max_len = 0 -for right in range(N): - if stone[right]=='W': - w_cnt += 1 - else: - b_cnt += 1 - while b_cnt > B: - if stone[left]=='W': - w_cnt -= 1 - else: - b_cnt -= 1 - left += 1 - if w_cnt>=W: - max_len = max(max_len,right-left+1) -print(max_len) \ No newline at end of file diff --git "a/15886\353\202\264 \354\204\240\353\254\274\354\235\204 \353\260\233\354\225\204\354\244\2302.py" "b/15886\353\202\264 \354\204\240\353\254\274\354\235\204 \353\260\233\354\225\204\354\244\2302.py" deleted file mode 100644 index d3314c6..0000000 --- "a/15886\353\202\264 \354\204\240\353\254\274\354\235\204 \353\260\233\354\225\204\354\244\2302.py" +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -maps = input() -cnt = 1 -for i in range(1,N): - if maps[i]=='E': - if maps[i-1]=='W': - cnt +=1 -print(cnt) \ No newline at end of file diff --git "a/15900 \353\202\230\353\254\264\355\203\210\354\266\234.py" "b/15900 \353\202\230\353\254\264\355\203\210\354\266\234.py" deleted file mode 100644 index 3f2959a..0000000 --- "a/15900 \353\202\230\353\254\264\355\203\210\354\266\234.py" +++ /dev/null @@ -1,70 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque,defaultdict - - -# 왜? BFS로 안풀림? -def BFS(start): - q = deque() - q.append([start,0]) - vi[start] = True - a = 0 - while q: - c_n,d = q.popleft() - for n_n in g[c_n]: - if not vi[n_n]: - vi[n_n]=True - q.append([n_n,d+1]) - if len(g[n_n])==1: - a += d+1 - return a - -N = int(input()) -g = defaultdict(list) -vi = {i: False for i in range(1,N+1)} -for _ in range(N-1): - a, b = map(int, input().split()) - g[a] += [b] - g[b] += [a] - -print("Yes" if BFS(1)&1 else "No") - - - -# ''' -# [리프노드-루트노드까지의 거리]의 총 합이 홀수냐 짝수냐를 묻는 문제...인가? -# ''' -# import sys -# from collections import deque -# input = sys.stdin.readline - -# N = int(input()) -# graphs = [[] for _ in range(N+1)] -# for _ in range(N-1): -# a, b = map(int, input().split()) -# graphs[a].append(b) -# graphs[b].append(a) - -# q = deque() -# # 노드번호, 거리 -# q.append([1,0]) -# vi = [0] * (N+1) -# vi[1] = 1 - -# a = 0 -# while q: -# cur, d = q.popleft() -# # 리프 여부 체크 -# flag = True -# for next in graphs[cur]: -# if not vi[next]: -# q.append([next, d+1]) -# vi[next] = 1 -# flag = False -# if flag: -# a += d - -# if a%2: -# print('Yes') -# else: -# print('No') \ No newline at end of file diff --git "a/15927 \355\232\214\353\254\270\354\235\200 \355\232\214\353\254\270\354\225\204\353\213\210\354\225\274.py" "b/15927 \355\232\214\353\254\270\354\235\200 \355\232\214\353\254\270\354\225\204\353\213\210\354\225\274.py" deleted file mode 100644 index 18a7dac..0000000 --- "a/15927 \355\232\214\353\254\270\354\235\200 \355\232\214\353\254\270\354\225\204\353\213\210\354\225\274.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - -s = input().rstrip() -n = len(s) -start = 0 -end = n-1 -s_dic = {i:0 for i in range(26)} -while True: - diff --git "a/15927\355\232\214\353\254\270\354\235\200 \355\232\214\353\254\270\354\235\264 \354\225\204\353\213\210\354\225\274.py" "b/15927\355\232\214\353\254\270\354\235\200 \355\232\214\353\254\270\354\235\264 \354\225\204\353\213\210\354\225\274.py" deleted file mode 100644 index caa0a85..0000000 --- "a/15927\355\232\214\353\254\270\354\235\200 \355\232\214\353\254\270\354\235\264 \354\225\204\353\213\210\354\225\274.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -inmput = sys.stdin.readline - - -def check(a,left,right): - while left < right: - if a[left] != a[right]: - return 0 - left += 1 - right -= 1 - return 1 - - -s = input().rstrip() -n = len(s) -# 최대 길이가 회문 아니면 n -if not check(s,0,n-1): - print(n) -# 최대길이에서 하나뺀게 회문 아니면 n-1 -elif not check(s,0,n-2): - print(n-1) -else: - print(-1) \ No newline at end of file diff --git "a/1595 \353\266\201\354\252\275\353\202\230\353\235\274\354\235\230 \353\217\204\353\241\234.py" "b/1595 \353\266\201\354\252\275\353\202\230\353\235\274\354\235\230 \353\217\204\353\241\234.py" deleted file mode 100644 index 6aeb0b2..0000000 --- "a/1595 \353\266\201\354\252\275\353\202\230\353\235\274\354\235\230 \353\217\204\353\241\234.py" +++ /dev/null @@ -1,175 +0,0 @@ -# import sys - -# lines = sys.stdin.readlines() -# e = [] -# for line in lines: -# line = line.rstrip() -# if line: e.append(tuple(map(int,line.split()))) - -# n = len(e)+1 -# adj = [[] for i in range(n+1)] -# for a,b,w in e: -# adj[a].append((b,w)) -# adj[b].append((a,w)) - -# max_u, max_w = 0,0 -# visit = [False]*(n+1) -# S = [(1,0)] -# visit[1]=True -# while S: -# next_node,w = S.pop() -# if w>max_w: max_u=next_node; max_w=w -# for v,dw in adj[next_node]: -# if not visit[v]: -# S.append((v,w+dw)) -# visit[v]=True - -# visit = [False]*(n+1) -# S = [(max_u,0)] -# visit[max_u]=True -# max_u, max_w = 0,0 -# while S: -# next_node,w = S.pop() -# if w>max_w: max_u=next_node; max_w=w -# for v,dw in adj[next_node]: -# if not visit[v]: -# S.append((v,w+dw)) -# visit[v]=True -# print(max_w) - - -# # 다익스트라 -# import heapq -# import sys - -# si = sys.stdin.readline -# INF = 987654321 - - -# def get_max_value(): -# ret = 0 -# for node in node_list: -# if ret < distance[node]: -# ret = distance[node] -# return ret - - -# def dijkstra(start): -# q = [] -# distance[start] = 0 -# heapq.heappush(q, (0, start)) -# while q: -# dist, now = heapq.heappop(q) - -# if distance[now] < dist: -# continue - -# for j in graph[now]: -# nxt = j[0] -# cost = dist + j[1] -# if distance[nxt] > cost: -# distance[nxt] = cost -# heapq.heappush(q, (cost, nxt)) - - -# graph = [[] for _ in range(10001)] -# distance = [INF] * 10001 -# node_list = set() - -# while True: -# try: -# a, b, c = map(int, si().split(" ")) -# graph[a].append((b, c)) -# graph[b].append((a, c)) -# node_list.add(a) -# node_list.add(b) -# except: -# break - -# dijkstra(1) -# ret = 0 -# start = 0 -# for node in node_list: -# if ret < distance[node]: -# start = node -# ret = distance[node] - -# distance = [INF] * 10001 -# dijkstra(start) -# print(get_max_value()) - - - -# # bfs -from collections import deque -import sys -tree = [[] for _ in range(10001)] - -for line in sys.stdin: - splitted = line.split() - if len(splitted) != 3: - break - a, b, c = map(int, splitted) - tree[a].append((b, c)) - tree[b].append((a, c)) - -def find_farthest(node): - q = deque([(node, 0)]) # node and weight - visited = [False for _ in range(10001)] - visited[node] = True - max_node, max_weight = node, 0 - while q: - cur, cur_weight = q.popleft() - if max_weight < cur_weight: - max_node, max_weight = cur, cur_weight - for nxt, weight in tree[cur]: - if not visited[nxt]: - visited[nxt] = True - nxt_weight = cur_weight + weight - q.append((nxt, nxt_weight)) - return max_node, max_weight - -anchor_node, _ = find_farthest(1) -_, farthest_distance = find_farthest(anchor_node) -print(farthest_distance) - - -# 간단한 bfs -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(start): - q = deque() - q.append((start, 0)) - visited = [False for __ in range(10001)] - visited[start] = True - max_dist = 0 - target_node = 0 - while q: - cur_node, cur_dist = q.popleft() - for next_node, next_dist in graph[cur_node]: - if visited[next_node]: - continue - visited[next_node] = True - dist = next_dist + cur_dist - if dist > max_dist: - max_dist, target_node = dist, next_node - q.append((next_node, dist)) - return (target_node, max_dist) - - -edges = [] -while 1: - try: - a, b, c = map(int, input().split()) - edges.append((a, b, c)) - except: - break -n = len(edges) -graph = {i: [] for i in range(10001)} -for edge in edges: - a, b, c = edge - graph[a].append((b, c)) - graph[b].append((a, c)) -print(bfs(bfs(1)[0])[1]) \ No newline at end of file diff --git "a/15961\355\232\214\354\240\204\354\264\210\353\260\245.py" "b/15961\355\232\214\354\240\204\354\264\210\353\260\245.py" deleted file mode 100644 index c93ad1d..0000000 --- "a/15961\355\232\214\354\240\204\354\264\210\353\260\245.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -N, d, k, c = map(int,input().split()) -sushi = [] -for _ in range(N): - sushi.append(int(input())) -sushi.extend(sushi) - -left = 0 -right = 0 -max_cnt = 0 -eat = defaultdict(int) - -eat[c] += 1 - -for right in range(len(sushi)): - eat[sushi[right]] += 1 - - if right >= k-1: - max_cnt = max(max_cnt,len(eat)) - eat[sushi[left]] -= 1 - if eat[sushi[left]] == 0: - del eat[sushi[left]] - left += 1 - -print(max_cnt) \ No newline at end of file diff --git "a/15988 \353\215\224\355\225\230\352\270\2603.py" "b/15988 \353\215\224\355\225\230\352\270\2603.py" deleted file mode 100644 index 434f51f..0000000 --- "a/15988 \353\215\224\355\225\230\352\270\2603.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -def findCase(n): - dp[1] = 1 - dp[2] = 2 - dp[3] = 4 - if n>3: - for i in range(4,n+1): - if dp[i]: - continue - dp[i] = (dp[i-1] + dp[i-2] + dp[i-3])%1000000009 - return dp[n] - -T = int(input()) -dp = [0] * 1000001 - -for test in range(T): - n = int(input()) - - print(findCase(n)) \ No newline at end of file diff --git a/15988.py b/15988.py index 5e3e269..e85c9a2 100644 --- a/15988.py +++ b/15988.py @@ -1,14 +1,14 @@ -import sys -input = sys.stdin.readline - -dp = [0 for i in range(1000001)] -dp[0] = 1 -dp[1] = 1 -dp[2] = 2 -for i in range(3, 1000001): - dp[i] = dp[i - 1] % 1000000009 + dp[i - 2] % 1000000009 + dp[i - 3] % 1000000009 - -t = int(input()) -for i in range(t): - n = int(input()) +import sys +input = sys.stdin.readline + +dp = [0 for i in range(1000001)] +dp[0] = 1 +dp[1] = 1 +dp[2] = 2 +for i in range(3, 1000001): + dp[i] = dp[i - 1] % 1000000009 + dp[i - 2] % 1000000009 + dp[i - 3] % 1000000009 + +t = int(input()) +for i in range(t): + n = int(input()) print(dp[n] % 1000000009) \ No newline at end of file diff --git "a/15988_123\353\215\224\355\225\230\352\270\260.py" "b/15988_123\353\215\224\355\225\230\352\270\260.py" index 434f51f..85965f8 100644 --- "a/15988_123\353\215\224\355\225\230\352\270\260.py" +++ "b/15988_123\353\215\224\355\225\230\352\270\260.py" @@ -1,21 +1,21 @@ -import sys -input = sys.stdin.readline - -def findCase(n): - dp[1] = 1 - dp[2] = 2 - dp[3] = 4 - if n>3: - for i in range(4,n+1): - if dp[i]: - continue - dp[i] = (dp[i-1] + dp[i-2] + dp[i-3])%1000000009 - return dp[n] - -T = int(input()) -dp = [0] * 1000001 - -for test in range(T): - n = int(input()) - +import sys +input = sys.stdin.readline + +def findCase(n): + dp[1] = 1 + dp[2] = 2 + dp[3] = 4 + if n>3: + for i in range(4,n+1): + if dp[i]: + continue + dp[i] = (dp[i-1] + dp[i-2] + dp[i-3])%1000000009 + return dp[n] + +T = int(input()) +dp = [0] * 1000001 + +for test in range(T): + n = int(input()) + print(findCase(n)) \ No newline at end of file diff --git "a/15989 1,2,3\353\215\224\355\225\230\352\270\2604.py" "b/15989 1,2,3\353\215\224\355\225\230\352\270\2604.py" deleted file mode 100644 index 8aa6983..0000000 --- "a/15989 1,2,3\353\215\224\355\225\230\352\270\2604.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -T = int(input()) -dp = [0]*10001 -dp[0] = 1 -dp[1] = 1 -dp[2] = 2 -dp[3] = 3 -for i in range(4,10001): - dp[i] = dp[i-1] + dp[i-2] - dp[i-3] - if not i % 3: - dp[i] += 1 -for _ in range(T): - print(dp[int(input())]) \ No newline at end of file diff --git "a/15990 \353\215\224\355\225\230\352\270\2605.py" "b/15990 \353\215\224\355\225\230\352\270\2605.py" index 6408697..90fdee6 100644 --- "a/15990 \353\215\224\355\225\230\352\270\2605.py" +++ "b/15990 \353\215\224\355\225\230\352\270\2605.py" @@ -1,17 +1,15 @@ -MAX = 100000 -mod = 1000000009 -DP = [[0]*(3+1) for _ in range(MAX+1)] - -DP[0] = [0, 0, 0, 0] -DP[1] = [0, 1, 0, 0] -DP[2] = [0, 0, 1, 0] -DP[3] = [0, 1, 1, 1] - -for i in range(4, MAX + 1): - DP[i][1] = (DP[i - 1][2] + DP[i - 1][3]) % mod - DP[i][2] = (DP[i - 2][1] + DP[i - 2][3]) % mod - DP[i][3] = (DP[i - 3][1] + DP[i - 3][2]) % mod - -for _ in range(int(input())): - N = int(input()) - print(sum(DP[N])% mod) \ No newline at end of file +class A: + def __init__(self, name): + self.name=name + +class B(A): + gene = 'XX' + +class C(A): + gene = 'XY' + +class D(B,C): + pass + +baby = D('baby') +print(baby.gene) \ No newline at end of file diff --git "a/15991 1,2,3\353\215\224\355\225\230\352\270\2606.py" "b/15991 1,2,3\353\215\224\355\225\230\352\270\2606.py" deleted file mode 100644 index 01a84a4..0000000 --- "a/15991 1,2,3\353\215\224\355\225\230\352\270\2606.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - -dp = [1,1,2,2,3,3] -for i in range(6,100001): - dp.append((dp[i-2]+dp[i-4]+dp[i-6])%1000000009) - -for _ in range(int(input())): - n = int(input()) - print(dp[n]) \ No newline at end of file diff --git "a/15992 1,2,3\353\215\224\355\225\230\352\270\2607.py" "b/15992 1,2,3\353\215\224\355\225\230\352\270\2607.py" deleted file mode 100644 index 48eae03..0000000 --- "a/15992 1,2,3\353\215\224\355\225\230\352\270\2607.py" +++ /dev/null @@ -1,21 +0,0 @@ - -dp = {j:{} for j in range(1001)} -dp[1][1] = 1 -dp[2][1] = 1 -dp[3][1] = 1 - -def solve(n,m): - if m<1 or n<1: # basis - return 0 - if m in dp[n].keys(): - return dp[n][m] - else: # optimal substructure - dp[n][m] = solve(n-3, m-1) + solve(n-2, m-1) + solve(n-1, m-1) - return dp[n][m] - -import sys -sys.setrecursionlimit(1000000) -T = int(sys.stdin.readline()) -for i in range(T): - n,m = map(int, sys.stdin.readline().strip().split()) - print(solve(n,m)%1000000009) \ No newline at end of file diff --git "a/15993 1,2,3\353\215\224\355\225\230\352\270\2608.py" "b/15993 1,2,3\353\215\224\355\225\230\352\270\2608.py" deleted file mode 100644 index 011c1ca..0000000 --- "a/15993 1,2,3\353\215\224\355\225\230\352\270\2608.py" +++ /dev/null @@ -1,23 +0,0 @@ -from sys import stdin - - -if __name__ == '__main__': - MAX, ODD, EVEN = 100001, 0, 1 - divisor = 1000000009 - dp = [[0] * 100001 for _ in range(2)] - - dp[ODD][1] = 1 - dp[ODD][2], dp[EVEN][2] = 1, 1 - dp[ODD][3], dp[EVEN][3] = 2, 2 - - for i in range(4, MAX): - dp[ODD][i] = \ - (dp[EVEN][i - 1] + dp[EVEN][i - 2] + dp[EVEN][i - 3]) % divisor - dp[EVEN][i] = \ - (dp[ODD][i - 1] + dp[ODD][i - 2] + dp[ODD][i - 3]) % divisor - - t = int(stdin.readline()) - - for _ in range(t): - n = int(stdin.readline()) - print(dp[ODD][n], dp[EVEN][n]) \ No newline at end of file diff --git "a/1613 \354\227\255\354\202\254.py" "b/1613 \354\227\255\354\202\254.py" deleted file mode 100644 index dcb61fd..0000000 --- "a/1613 \354\227\255\354\202\254.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -n, k = map(int, input().split()) -matrix = [[0] * n for __ in range(n)] -for __ in range(k): - a, b = map(lambda x : int(x) - 1, input().split()) - matrix[a][b] = 1 - -for k in range(n): - for i in range(n): - for j in range(n): - if matrix[i][k] and matrix[k][j]: - matrix[i][j] = 1 -for __ in range(int(input())): - a, b = map(lambda x : int(x) - 1, input().split()) - if matrix[a][b]: - print(-1) - elif matrix[b][a]: - print(1) - else: - print(0) \ No newline at end of file diff --git "a/16139\354\235\270\352\260\204-\354\273\264\355\223\250\355\204\260 \354\203\201\355\230\270\354\236\221\354\232\251.py" "b/16139\354\235\270\352\260\204-\354\273\264\355\223\250\355\204\260 \354\203\201\355\230\270\354\236\221\354\232\251.py" deleted file mode 100644 index 977ac9c..0000000 --- "a/16139\354\235\270\352\260\204-\354\273\264\355\223\250\355\204\260 \354\203\201\355\230\270\354\236\221\354\232\251.py" +++ /dev/null @@ -1,45 +0,0 @@ -import sys -input = sys.stdin.readline -print = sys.stdout.write - -s = input().rstrip() -n = len(s) -sub_set = [[0 for _ in range(26)] for _ in range(n)] -for i in range(n): - for j in range(i,n): - sub_set[j][ord(s[i])-97] += 1 - -q = int(input()) -for _ in range(q): - alp, l, r = input().split() - l,r = int(l), int(r) - l_value = sub_set[l-1][ord(alp)-97] if l>0 else 0 - r_value = sub_set[r][ord(alp)-97] - print(f'{r_value - l_value}\n') - - - -# # 남의코드 가로세로만 바뀜. -# import sys -# input = sys.stdin.readline - -# s = input().rstrip() -# d = [[0] * 26 for _ in range(len(s) + 1)] - -# for i in range(1, len(s) + 1): -# x = ord(s[i - 1]) - ord("a") -# for j in range(26): -# if j == x: -# d[i][j] = d[i - 1][j] + 1 -# continue -# d[i][j] = d[i - 1][j] - -# n = int(input()) -# for _ in range(n): -# x, l, r = input().rstrip().split() -# x = ord(x) - ord("a") -# r = int(r) -# l = int(l) - -# ans = d[r + 1][x] - d[l][x] -# sys.stdout.write(str(ans) + "\n") \ No newline at end of file diff --git "a/16159 1,2,3\353\215\224\355\225\230\352\270\2609.py" "b/16159 1,2,3\353\215\224\355\225\230\352\270\2609.py" deleted file mode 100644 index 5f18517..0000000 --- "a/16159 1,2,3\353\215\224\355\225\230\352\270\2609.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - - -MOD = 1000000009 -# 숫자 n을 m개를 써서 만드는 경우의 수. n * n 까지 가능. -dp = [[0] * 1001 for _ in range(1001)] -dp[1][1] = 1 - -dp[2][1] = 1 -dp[2][2] = 1 - -dp[3][1] = 1 -dp[3][2] = 2 -dp[3][3] = 1 -for i in range(4, 1001): - for j in range(1, i + 1): - dp[i][j] = (dp[i - 1][j - 1] + dp[i - 2][j - 1] + dp[i - 3][j - 1]) % MOD - - -for _ in range(int(input())): - n, m = map(int, input().split()) - - print(sum(dp[n][:m + 1]) % MOD) \ No newline at end of file diff --git "a/16163#15164\353\262\210\354\240\234\353\263\264.py" "b/16163#15164\353\262\210\354\240\234\353\263\264.py" deleted file mode 100644 index 0a85f08..0000000 --- "a/16163#15164\353\262\210\354\240\234\353\263\264.py" +++ /dev/null @@ -1,44 +0,0 @@ -import sys -input = sys.stdin.readline - - -def manacher(string): - n = len(string) - a = [0] * n # i번째 문자를 중심으로 하는 가장 긴 팰린드롬 반지름 크기. - c = 0 # 중심점(center) 초기화 - r = 0 # 시작점에서 가장 먼 반경(펠린드롬 끝나는 인덱스중 가장 큰 값.) - answer = 0 - for now in range(n): - if string[now] != '#': - answer +=1 - # i번째 문자가 now 아래쪽에 있는 문자를 중심으로 하는 팰린드롬 범위 밖의 문자라는 뜻. - # 때문에 now 이전에 얻은 정보를 재활용하지 못하고 i를 기준으로 초기화시켜 재계산함. - if r < now: - a[now] = 0 - # i번째 문자가 i미만의 문자를 중심으로 하는 팰린드롬에 속한다면? - # 1. i를 중심으로 하는 가장 긴 팰린드롬이 기존 최장 팰린드롬인 c를 중심으로 하는 가장 긴 팰린드롬에 완전히 속하는 경우 -> i의 c점에 대한 대칭점 now'을 기준으로 하는 펠린드롬은 i를 기준으로 하는 팰린드롬과 완전한 대칭. a[now]=a[now']인데 p[now']은 이전에 구해놓았기 때문에 연산 안해도됨. - # 2. i를 중심으로 하는 가장 긴 팰린드롬이 c를 중심으로 한느 가장 긴 팰린드롬에 일부만 포함된느 경우 -> 초기 반지름 a[now] = ((c+a[c])-now)가 보장이됨(가장 긴 펠린드롬의 오른쪽 한계로부터 i만큼 왼쪽으로 줄인 반지름에서 (c+a[c])-now+1부터 비교 시작) - # 3. i를 중심으로 한느 가장 긴 팰린드롬이 c < i인 c를 중심으로 하는 가장 긴 팰린드롬과 겹치는 경우. (c의 날개와 i의 날개가 동일지점인 경우) - # 역시 case 2처럼 a[now] = ((c+a[c])-now)만큼의 반지름이 보장이 됨. 그 이후로 부터 비교하면 됨. now'은 (2*c)-i이므로 now'의 날개와 r-i값중 더 작은 곳을 보장받고 움직이면 됨. - else: - a[now] = min(a[(2*c) - now], r - now) - answer += a[now]//2 - - # i번째 인덱스 기준 가장 긴 펠린드롬 반지름을 펼쳤을 시 0~len(s)의 범위 안에 존재해야하며 - # i기준 a[now](반지름)만큼 펼친 그 양옆문자도 같으면?(-1.+1인덱스가 같으면) - # a[now]+1(반지름 확장) - while(now-a[now]-1>=0 and now+a[now]+1 < n and string[now-a[now]-1] == string[now+a[now]+1]): - a[now] = a[now] + 1 - if string[now + a[now]] != '#': - answer +=1 - # 시작점에서 가장 먼 반경인 now + a[now]가 기존 최장 반지름 길이 r보다 크므로 - # r초기화, 중심점 c는 현재 최장 펠린드롬의 중심점인 i로 초기화. - # 결국 r,c는 현 시점에서 가장 먼 팰린드롬의 날개값(가장 멀리갈때 초기화됨.) - # a[now]가 0이어도 r보다 i가 커지면 갱신됨. - if (r < now + a[now]): - r = now + a[now] - c = now - return answer - -s = input().rstrip() -print(manacher('#' + '#'.join(s)+'#')) \ No newline at end of file diff --git "a/16168\355\215\274\353\240\210\354\235\264\353\223\234.py" "b/16168\355\215\274\353\240\210\354\235\264\353\223\234.py" deleted file mode 100644 index 39b14a1..0000000 --- "a/16168\355\215\274\353\240\210\354\235\264\353\223\234.py" +++ /dev/null @@ -1,49 +0,0 @@ -import sys -input =sys.stdin.readline - - -def find(x): - if parent[x] ==x: - return x - parent[x] = find(parent[x]) - return parent[x] - -def union(a,b): - a = find(a) - b = find(b) - - if level[a] >= level[b]: - parent[b] = a - if level[a]==level[b]: - level[a] += 1 - else: - parent[a] = b - -V, E = map(int, input().split()) - -graph = {i: [] for i in range(1,V+1)} -parent = {i: i for i in range(1,V+1)} -level = {i: 0 for i in range(1,V+1)} -for _ in range(E): - a, b = map(int, input().split()) - if find(a) != find(b): - union(a,b) - if a>b: - a,b = b,a - graph[a].append(b) - graph[b].append(a) - - -pivot = find(1) -for node in range(2,V+1): - if pivot != find(node): - print("NO") - exit() - - -cnt = 0 -for start_node in range(1,V+1): - if len(graph[start_node])&1: - cnt += 1 - -print('YES' if not cnt or cnt==2 else 'NO') \ No newline at end of file diff --git "a/16194\354\271\264\353\223\234\352\265\254\353\247\244\355\225\230\352\270\2602.py" "b/16194\354\271\264\353\223\234\352\265\254\353\247\244\355\225\230\352\270\2602.py" index 1be51b3..97ee37a 100644 --- "a/16194\354\271\264\353\223\234\352\265\254\353\247\244\355\225\230\352\270\2602.py" +++ "b/16194\354\271\264\353\223\234\352\265\254\353\247\244\355\225\230\352\270\2602.py" @@ -1,14 +1,14 @@ -N = int(input()) - -p = [0] + list(map(int,input().split())) -dp = [False for _ in range(N+1)] - - -for i in range(1, N+1): - for k in range(1, i+1): - if dp[i] == False : - dp[i] = dp[i-k]+p[k] - else : - dp[i] = min(dp[i], dp[i-k]+p[k]) - +N = int(input()) + +p = [0] + list(map(int,input().split())) +dp = [False for _ in range(N+1)] + + +for i in range(1, N+1): + for k in range(1, i+1): + if dp[i] == False : + dp[i] = dp[i-k]+p[k] + else : + dp[i] = min(dp[i], dp[i-k]+p[k]) + print(dp[N]) \ No newline at end of file diff --git "a/16198 \354\227\220\353\204\210\354\247\200 \353\252\250\354\234\274\352\270\260.py" "b/16198 \354\227\220\353\204\210\354\247\200 \353\252\250\354\234\274\352\270\260.py" deleted file mode 100644 index 699a61a..0000000 --- "a/16198 \354\227\220\353\204\210\354\247\200 \353\252\250\354\234\274\352\270\260.py" +++ /dev/null @@ -1,5 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -w = list(map(int, input().split())) diff --git "a/16202 MST\352\262\214\354\236\204.py" "b/16202 MST\352\262\214\354\236\204.py" deleted file mode 100644 index 4fa1718..0000000 --- "a/16202 MST\352\262\214\354\236\204.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - - -def find(x): - if parent[x] == x: - return x - parent[x] = find(parent[x]) - return parent[x] - -def union(a,b): - a = find(a) - b = find(b) - - if level[a] >= level[b]: - parent[b] = a - if level[a] == level[b]: - level[a] += 1 - else: - parent[a] = b - -N, M, K = map(int, input().split()) -edges = [] -for i in range(1,M+1): - a, b = map(int, input().split()) - edges.append((i,a,b)) -for i in range(K): - answer = 0 - cnt = 0 - parent = {i: i for i in range(1,N+1)} - level = {i: 0 for i in range(1,N+1)} - for edge in edges[i:]: - c, a, b = edge - if find(a) != find(b): - union(a,b) - cnt += 1 - answer += c - if cnt == N-1: - print(answer, end = ' ') - break - else: - print(0, end=' ') \ No newline at end of file diff --git "a/16206 \353\241\244\354\274\200\354\235\264\355\201\254.py" "b/16206 \353\241\244\354\274\200\354\235\264\355\201\254.py" deleted file mode 100644 index 74485cb..0000000 --- "a/16206 \353\241\244\354\274\200\354\235\264\355\201\254.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -cakes = list(map(int, input().split())) -cakes.sort(key=lambda x: (x%10,x)) -cake_cnt = 0 -for cake in cakes: - cnt = cake//10 - if not cake%10: - if cnt-1 <= M: - cake_cnt += cnt - M -= cnt -1 - else: - cake_cnt += M - M -= M - else: - if cnt <= M: - cake_cnt += cnt - M -= cnt - else: - cake_cnt += M - M -= M -print(cake_cnt) diff --git "a/16208 \352\267\200\354\260\256\354\235\214.py" "b/16208 \352\267\200\354\260\256\354\235\214.py" deleted file mode 100644 index b2ce85d..0000000 --- "a/16208 \352\267\200\354\260\256\354\235\214.py" +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -arr = list(map(int, input().split())) -arr.sort() -total = sum(arr) -answer = 0 -for num in arr: - answer += num * (total - num) - total -= num -print(answer) \ No newline at end of file diff --git "a/1620\353\202\230\353\212\224\354\225\274 \355\217\254\354\274\223\353\252\254 \353\247\210\354\212\244\355\204\260 \354\235\264\353\213\244\354\206\234.py" "b/1620\353\202\230\353\212\224\354\225\274 \355\217\254\354\274\223\353\252\254 \353\247\210\354\212\244\355\204\260 \354\235\264\353\213\244\354\206\234.py" deleted file mode 100644 index b4715f4..0000000 --- "a/1620\353\202\230\353\212\224\354\225\274 \355\217\254\354\274\223\353\252\254 \353\247\210\354\212\244\355\204\260 \354\235\264\353\213\244\354\206\234.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -# 검색은 hash table -N,M = map(int,input().split()) -poc_num = defaultdict(int) -poc_name = defaultdict(str) - -for i in range(1,N+1): - a = input().rstrip() - poc_num[a] = i - poc_name[i] = a - -for _ in range(M): - b = input().rstrip() - if b.isdigit(): - print(poc_name[int(b)]) - else: - print(poc_num[b]) \ No newline at end of file diff --git "a/1622\352\263\265\355\206\265\354\210\234\354\227\264.py" "b/1622\352\263\265\355\206\265\354\210\234\354\227\264.py" deleted file mode 100644 index e2b5d53..0000000 --- "a/1622\352\263\265\355\206\265\354\210\234\354\227\264.py" +++ /dev/null @@ -1,48 +0,0 @@ -from collections import defaultdict - -while True: - try: - a=input() - b=input() - alpha1=defaultdict(int) - alpha2=defaultdict(int) - ans='' - for s in a: - alpha1[s]+=1 - for s in b: - alpha2[s]+=1 - s = [] - for char in alpha1: - if char in alpha2: - s.append(char) - s.sort() - for char in s: - ans += char*min(alpha1[char],alpha2[char]) - print(ans) - except: - break -# 다른코드 -try: - while 1: - a=input();b=input();l=[] - for i in a: - if i in b: - l+=[i]; - b=b.replace(i,"",1) - l.sort(); - print("".join(l)) -except: - pass -# 다른코드 -while True : - try : - a=input() - b=input() - except : - break - ans = "" - s = "abcdefghijklmnopqrstuvwxyz" - for i in s : - cnt = min(a.count(i), b.count(i)) - ans += i*cnt - print (ans) diff --git "a/16234\354\235\270\352\265\254\354\235\264\353\217\231.py" "b/16234\354\235\270\352\265\254\354\235\264\353\217\231.py" deleted file mode 100644 index ae4eab1..0000000 --- "a/16234\354\235\270\352\265\254\354\235\264\353\217\231.py" +++ /dev/null @@ -1,56 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from math import floor - -def search_unions(x,y): - queue = deque() - nation_cnt=1 - sum_population = maps[x][y] - queue.append([x,y]) - finish_union[x][y] = union_num - while queue: - x,y = queue.popleft() - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0<=nx 조사했을 시 연합국가가 하나도 없을 시. - if not unions: - break - - # 한 사이클 동안 모든 연합국가에 대해 평균값 부여(소숫점 버림.) - for k in range(len(unions)): - for i in range(N): - for j in range(N): - if finish_union[i][j]==k: - maps[i][j] = unions[k] - cycle += 1 -print(cycle) \ No newline at end of file diff --git "a/16235\353\202\230\353\254\264 \354\236\254\355\205\214\355\201\254.py" "b/16235\353\202\230\353\254\264 \354\236\254\355\205\214\355\201\254.py" deleted file mode 100644 index fa21d97..0000000 --- "a/16235\353\202\230\353\254\264 \354\236\254\355\205\214\355\201\254.py" +++ /dev/null @@ -1,103 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def spring_summer(): - for i in range(n): - for j in range(n): - len_t = len(tree_map[i][j]) - for k in range(len_t): - if tree_map[i][j][k] <= area[i][j]: - area[i][j] -= tree_map[i][j][k] - tree_map[i][j][k] += 1 - else: - for _ in range(len_t-k): - area[i][j] += tree_map[i][j].pop() // 2 - break -def fall_winter(): - for i in range(n): - for j in range(n): - for k in tree_map[i][j]: - if k % 5: - continue - for l in range(8): - x = i + dx[l] - y = j + dy[l] - if 0 <= x < n and 0 <= y < n: - tree_map[x][y].appendleft(1) - area[i][j] += energy[i][j] -dx = [1, -1, 0, 0, 1, -1, 1, -1] -dy = [0, 0, -1, 1, 1, -1, -1, 1] -n, m, k = map(int, input().split()) -energy = [list(map(int, input().split())) for _ in range(n)] -tree_map = [[deque() for _ in range(n)] for _ in range(n)] -area = [[5] * n for _ in range(n)] -for i in range(m): - x, y, z = map(int, input().split()) - tree_map[x - 1][y - 1].append(z) -for i in range(k): - spring_summer() - fall_winter() -answer = 0 -for i in range(n): - for j in range(n): - answer += len(tree_map[i][j]) -print(answer) - - - - -###다른사람 -import sys -input = sys.stdin.readline - - -def solve(): - n, m, k = map(int, input().split()) - land = [[5]*n for _ in range(n)] - tree = [[{} for _ in range(n)] for _ in range(n)] - S2D2 = [list(map(int, input().split())) for _ in range(n)] - for _ in range(m): - r, c, a = map(int, input().split()) - tree[r-1][c-1][a] = 1 - for _ in range(k): - ng = [[{} for _ in range(n)] for _ in range(n)] - for r in range(n): - for c in range(n): - if not tree[r][c]: - land[r][c] += S2D2[r][c] - continue - tmp = more = 0 - for age, count in sorted(tree[r][c].items()): - if (can := min(land[r][c]//age, count)): - land[r][c] -= age*can - if (nxt := age+1) not in ng[r][c]: - ng[r][c][nxt] = 0 - ng[r][c][nxt] += can - if nxt % 5 == 0: - tmp += can - more += (age >> 1)*(count-can) - land[r][c] += more + S2D2[r][c] - if tmp: - if r > 0: - ng[r-1][c][1] = ng[r-1][c].get(1, 0) + tmp - if c > 0: - ng[r-1][c-1][1] = ng[r-1][c-1].get(1, 0)+tmp - if c < n-1: - ng[r-1][c+1][1] = ng[r-1][c+1].get(1, 0)+tmp - if r < n-1: - ng[r+1][c][1] = ng[r+1][c].get(1, 0)+tmp - if c > 0: - ng[r+1][c-1][1] = ng[r+1][c-1].get(1, 0)+tmp - if c < n-1: - ng[r+1][c+1][1] = ng[r+1][c+1].get(1, 0)+tmp - if c > 0: - ng[r][c-1][1] = ng[r][c-1].get(1, 0)+tmp - if c < n-1: - ng[r][c+1][1] = ng[r][c+1].get(1, 0)+tmp - tree = ng - print(sum(sum(tree[i//n][i % n].values()) for i in range(n**2))) - - -if __name__ == '__main__': - solve() \ No newline at end of file diff --git "a/16236 \354\225\204\352\270\260\354\203\201\354\226\264.py" "b/16236 \354\225\204\352\270\260\354\203\201\354\226\264.py" deleted file mode 100644 index bee84b2..0000000 --- "a/16236 \354\225\204\352\270\260\354\203\201\354\226\264.py" +++ /dev/null @@ -1,71 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def eat_fish(fish, s, c): - fish.sort() - x, y = fish[0] - aquarium[x][y] = 0 - c += 1 - if c==s: - s += 1 - c = 0 - return (x, y, s, c) - - -def find_fish(start): - global time - x, y, size, cnt = start - q = deque() - q.append((x,y)) - visited = [[False]*N for _ in range(N)] - visited[x][y] = True - tmp = 0 - while q: - feed = [] - for _ in range(len(q)): - x, y = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N and not visited[nx][ny]: - if aquarium[nx][ny] and aquarium[nx][ny] < size: - feed.append((nx,ny)) - elif not aquarium[nx][ny] or aquarium[nx][ny] == size: - visited[nx][ny] = True - q.append((nx, ny)) - tmp += 1 - if feed: - return tmp, eat_fish(feed, size, cnt) - return 0, 0 - -def call_mother(baby_size): - for i in range(N): - for j in range(N): - if aquarium[i][j] and aquarium[i][j] < baby_size: - return True - return False - - -N = int(input()) -delta = ((-1,0),(0,-1),(0,1),(1,0)) -baby_shark = 0 -aquarium = [] -for i in range(N): - fish = list(map(int, input().split())) - aquarium.append(fish) - if not baby_shark: - for j in range(N): - if fish[j]==9: - aquarium[i][j] = 0 - baby_shark = (i, j, 2, 0) - break - -time = 0 -while call_mother(baby_shark[2]): - t, baby_shark = find_fish(baby_shark) - time += t - if not baby_shark: - break -print(time) - diff --git "a/16236\354\225\204\352\270\260\354\203\201\354\226\264.py" "b/16236\354\225\204\352\270\260\354\203\201\354\226\264.py" deleted file mode 100644 index 3758e06..0000000 --- "a/16236\354\225\204\352\270\260\354\203\201\354\226\264.py" +++ /dev/null @@ -1,84 +0,0 @@ -import sys -from collections import deque -input = sys.stdin.readline - - -def find_baby_shark(N, matrix): - for i in range(N): - for j in range(N): - if matrix[i][j] == 9: - matrix[i][j] = 0 - baby_shark = (i,j,2,0) - return baby_shark - - -def find_feed(N, matrix, size): - feeds = [] - for i in range(N): - for j in range(N): - if 0 < matrix[i][j] < size: - feeds.append([i,j]) - return feeds - - -def find_target(x, y, arr): - min_dist = 41 - for feed in arr: - dist = abs(feed[0] - x) + abs(feed[1] - y) - if dist < min_dist: - min_dist = dist - target_x, target_y = feed[0], feed[1] - return target_x, target_y - - -def BFS(x, y, target_x, target_y, size): - visited = [[-1 for _ in range(N)] for _ in range(N)] - queue = deque() - queue.append([x,y]) - visited[x][y] = 0 - eat_feed = [] - while queue: - x,y = queue.popleft() - if x==target_x and y==target_y: - eat_feed.append([x,y,visited[x][y]]) - return eat_feed - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - # 나보다 크기가 큰 물고기가 있는 칸은 못지나감. - if 0 <= nx < N and 0 <= ny < N and visited[nx][ny]==-1: - if matrix[nx][ny] <= size: - visited[nx][ny] = visited[x][y] + 1 - queue.append([nx, ny]) - if 0 < matrix[nx][ny] < size: - eat_feed.append([nx,ny,visited[nx][ny]]) - -N = int(input()) -matrix = [list(map(int, input().split())) for _ in range(N)] -time = 0 - -dx = [-1, 0, 0, 1] -dy = [0, -1, 1, 0] - -x, y, size, eat_cnt = find_baby_shark(N, matrix) - -# 상태공간 돌며 나보다 크기가 작은게 있으면 순회 종료. BFS시작. 찾아서 잡아먹음. 거리 차이만큼 시간 증가. -while True: - feed_box = find_feed(N, matrix, size) - if feed_box: - target_x, target_y = find_target(x, y, feed_box) - arr = BFS(x, y, target_x, target_y, size) - if arr: - arr.sort(key = lambda x: (x[2], x[0],x[1])) - x, y,plus_time = arr[0][0],arr[0][1],arr[0][2] - matrix[x][y] = 0 - time += plus_time - eat_cnt += 1 - if eat_cnt == size: # 먹은 갯수가 내 크기랑 같아지면 크기 업 먹은갯수 초기화 - size += 1 - eat_cnt = 0 - else: # 다 돌았는데 작은거 없으면 탐색 종료 - print(time) - exit() - - diff --git "a/16236\354\225\204\352\270\260\354\203\201\354\226\264_\353\202\250\354\235\230\354\275\224\353\223\234.py" "b/16236\354\225\204\352\270\260\354\203\201\354\226\264_\353\202\250\354\235\230\354\275\224\353\223\234.py" deleted file mode 100644 index 56b7772..0000000 --- "a/16236\354\225\204\352\270\260\354\203\201\354\226\264_\353\202\250\354\235\230\354\275\224\353\223\234.py" +++ /dev/null @@ -1,52 +0,0 @@ -from collections import deque -import sys -def bfs(i, j): - visit = [[0] * n for i in range(n)] - visit[i][j] = 1 - eat = [] - dist = [[0] * n for i in range(n)] - q = deque() - q.append([i, j]) - while q: - x, y = q.popleft() - for k in range(4): - nx = x + dx[k] - ny = y + dy[k] - if 0 <= nx < n and 0 <= ny < n and visit[nx][ny] == 0: - if s[nx][ny] <= s[i][j] or s[nx][ny] == 0: - q.append([nx, ny]) - visit[nx][ny] = 1 - dist[nx][ny] = dist[x][y] + 1 - if s[nx][ny] < s[i][j] and s[nx][ny] != 0: - eat.append([nx, ny, dist[nx][ny]]) - if not eat: - return -1, -1, -1 - eat.sort(key = lambda x : (x[2], x[0], x[1])) - return eat[0][0], eat[0][1], eat[0][2] -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] -input = sys.stdin.readline -n = int(input()) -s = [] -for i in range(n): - a = list(map(int, input().split())) - s.append(a) - for j in range(n): - if a[j] == 9: - s[i][j] = 2 - start = [i, j] -exp = 0 -cnt = 0 -while True: - i, j = start[0], start[1] - ex, ey, dist = bfs(i, j) - if ex == -1: break - s[ex][ey] = s[i][j] - s[i][j] = 0 - start = [ex, ey] - exp += 1 - if exp == s[ex][ey]: - exp = 0 - s[ex][ey] += 1 - cnt += dist -print(cnt) \ No newline at end of file diff --git "a/1629\352\263\261\354\205\210.py" "b/1629\352\263\261\354\205\210.py" index 0c845f4..874e007 100644 --- "a/1629\352\263\261\354\205\210.py" +++ "b/1629\352\263\261\354\205\210.py" @@ -1,24 +1,18 @@ -import sys -input = sys.stdin.readline - -A, B, C = map(int, input().split(' ')) - -# 정복 -def conq(length): - # 정복 : length가 1이 되면 A를 반환하겠다.(최소단위 연산의 정복) - if length == 1: - return A %C - # 짝수면 좌우로 찢고 - if length % 2 == 0: - # 분할 (곱해야하는 length를 반으로 나눠가며 계산하겠다.) - left = conq(length // 2) - # 조합(함수 반환시마다 양쪽을 곱해서 올라가겠다.) - return left * left %C - # 홀수면 좌우로 찢고 남은A하나 곱해준다. - else: - left = conq(length // 2) - return left * left * A %C - - -print(conq(B)) - +import sys +input = sys.stdin.readline + +a, b, c = map(int, input().split(' ')) + +def conq(length): + if length == 1: + return a %c + if length % 2 == 0: + left = conq(length // 2) + return left * left %c + else: + left = conq(length // 2) + return left * left * a %c + + +print(conq(b)) + diff --git "a/1633\354\265\234\352\263\240\354\235\230 \355\214\200 \353\247\214\353\223\244\352\270\260.py" "b/1633\354\265\234\352\263\240\354\235\230 \355\214\200 \353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 6561977..0000000 --- "a/1633\354\265\234\352\263\240\354\235\230 \355\214\200 \353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,152 +0,0 @@ -from operator import itemgetter - -inputList = [] - -while True: - try: - line = input() - inputList.append(list(map(int, line.split()))) - except EOFError: - break - -# id 값 추가 -# 0 - id, 1 - while value, 2 - black value -for idx, val in enumerate(inputList): - inputList[idx].insert(0, idx) - -orderByWhite = sorted(inputList, key=itemgetter(1, 2), reverse=True) -orderByBlack = sorted(inputList, key=itemgetter(2, 1), reverse=True) -checkList = [-1] * len(inputList) - -cnt = 0 -whiteIndex = 0 -blackIndex = 0 -whiteCnt = 0 -blackCnt = 0 -result = 0 - -whiteSameCnt = 0 -blackSameCnt = 0 - -while whiteCnt + blackCnt < 30: - if checkList[orderByWhite[whiteIndex][0]] == 1: - whiteIndex = whiteIndex + 1 - continue - if checkList[orderByBlack[blackIndex][0]] == 1: - blackIndex = blackIndex + 1 - continue - - if blackCnt >= 15: - if whiteSameCnt > 0 and orderByWhite[whiteIndex][1] < orderByWhite[whiteIndex][2]: - whiteSameCnt = whiteSameCnt - 1 - result = result + orderByWhite[whiteIndex][2] - else: - result = result + orderByWhite[whiteIndex][1] - checkList[orderByWhite[whiteIndex][0]] = 1 - whiteIndex = whiteIndex + 1 - whiteCnt = whiteCnt + 1 - continue - elif whiteCnt >= 15: - if blackSameCnt > 0 and orderByBlack[blackIndex][2] < orderByBlack[blackIndex][1]: - blackSameCnt = blackSameCnt - 1 - result = result + orderByBlack[blackIndex][1] - else: - result = result + orderByBlack[blackIndex][2] - checkList[orderByBlack[blackIndex][0]] = 1 - blackIndex = blackIndex + 1 - blackCnt = blackCnt + 1 - continue - - if orderByWhite[whiteIndex][1] > orderByBlack[blackIndex][2]: - checkList[orderByWhite[whiteIndex][0]] = 1 - result = result + orderByWhite[whiteIndex][1] - whiteCnt = whiteCnt + 1 - whiteIndex = whiteIndex + 1 - elif orderByWhite[whiteIndex][1] < orderByBlack[blackIndex][2]: - checkList[orderByBlack[blackIndex][0]] = 1 - result = result + orderByBlack[blackIndex][2] - blackCnt = blackCnt + 1 - blackIndex = blackIndex + 1 - else: - # orderdByWhite 내 black 값과 orderedByBlack 내 white 값을 비교해 작은값이 있는 것을 우선순위로 넣어줌 - # 이후 메인 값 비교시 낮은 값이 들어가는 상황을 막기 위함 - if orderByWhite[whiteIndex][2] > orderByBlack[blackIndex][1]: - checkList[orderByBlack[blackIndex][0]] = 1 - result = result + orderByBlack[blackIndex][2] - blackCnt = blackCnt + 1 - blackIndex = blackIndex + 1 - blackSameCnt = blackSameCnt + 1 - elif orderByWhite[whiteIndex][2] < orderByBlack[blackIndex][1]: - checkList[orderByWhite[whiteIndex][0]] = 1 - result = result + orderByWhite[whiteIndex][1] - whiteCnt = whiteCnt + 1 - whiteIndex = whiteIndex + 1 - whiteSameCnt = whiteSameCnt + 1 - else: - if whiteCnt < blackCnt: - checkList[orderByWhite[whiteIndex][0]] = 1 - result = result + orderByWhite[whiteIndex][1] - whiteCnt = whiteCnt + 1 - whiteIndex = whiteIndex + 1 - whiteSameCnt = whiteSameCnt + 1 - else: - checkList[orderByBlack[blackIndex][0]] = 1 - result = result + orderByBlack[blackIndex][2] - blackCnt = blackCnt + 1 - blackIndex = blackIndex + 1 - blackSameCnt = blackSameCnt + 1 - -print(result) - - -# 풀이2: -"""BOJ Q1633 - 최고의 팀 만들기 (https://www.acmicpc.net/problem/1633) - -DP of O(|candidates| * |white player| * |black player|) -""" - -import sys - -BLACK_PLAYER_COUNT = 15 -WHITE_PLAYER_COUNT = 15 - -player_scores = [[int(x) for x in line.split()] for line in sys.stdin.readlines()] -table = [[0 for x in range(BLACK_PLAYER_COUNT + 1)] for y in range(WHITE_PLAYER_COUNT + 1)] -next_table = [[0 for x in range(BLACK_PLAYER_COUNT + 1)] for y in range(WHITE_PLAYER_COUNT + 1)] - -# 백을 취할때랑 흑을취할때랑 취하지 않을떄중 큰 것을 고름. -for white_score, black_score in player_scores: - for i in range(BLACK_PLAYER_COUNT + 1): - for j in range(WHITE_PLAYER_COUNT + 1): - next_table[i][j] = max(table[i][j], - table[i - 1][j] + white_score if i > 0 else 0, - table[i][j - 1] + black_score if j > 0 else 0) - next_table, table = table, next_table -print(table[BLACK_PLAYER_COUNT][WHITE_PLAYER_COUNT]) - - - - -#dp -li = [] -while True: - try: - temp = list(map(int, input().split())) - li.append(temp) - except: - break - -dp = [[0] * 16 for _ in range(16)] # dp[w][b] -for white, black in li: - for w in range(15, -1, -1): - for b in range(15, -1, -1): - if w - 1 < 0 and b - 1 < 0: - continue - elif w - 1 < 0: - dp[w][b] = max(dp[w][b - 1] + black, dp[w][b]) - elif b - 1 < 0 : - dp[w][b] = max(dp[w - 1][b] + white, dp[w][b]) - else: - dp[w][b] = max(dp[w - 1][b] + white, dp[w][b - 1] + black, dp[w][b]) - -print(dp[15][15]) \ No newline at end of file diff --git "a/1637\353\202\240\354\271\264\353\241\234\354\232\264 \353\210\210.py" "b/1637\353\202\240\354\271\264\353\241\234\354\232\264 \353\210\210.py" deleted file mode 100644 index 6f3d7d9..0000000 --- "a/1637\353\202\240\354\271\264\353\241\234\354\232\264 \353\210\210.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -def get_sum(target): - total = 0 - for i in range(N): - if target >= arr[i][0]: - total += ((min(arr[i][1],target) - arr[i][0])//arr[i][2]) + 1 - return total - -N = int(input()) -arr = [list(map(int, input().split())) for _ in range(N)] -left = 0 -right = 2147483648 -while left < right: - mid = (left + right)//2 - if not get_sum(mid)&1: - left = mid + 1 - else: - right = mid -if left == 2147483648: - print('NOTHING') -else: - print(left,get_sum(left) - get_sum(left-1)) \ No newline at end of file diff --git "a/16401 \352\263\274\354\236\220 \353\202\230\353\210\240\354\243\274\352\270\260.py" "b/16401 \352\263\274\354\236\220 \353\202\230\353\210\240\354\243\274\352\270\260.py" deleted file mode 100644 index c8d691e..0000000 --- "a/16401 \352\263\274\354\236\220 \353\202\230\353\210\240\354\243\274\352\270\260.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -M, N = map(int, input().split()) -L = list(map(int, input().split())) -start, end = 1, max(L) -answer = 0 -while start <= end: - target_l = (start + end) // 2 - if sum([each_l // target_l for each_l in L]) >= M: - answer = target_l - start = target_l + 1 - else: - end = target_l - 1 -print(answer) \ No newline at end of file diff --git "a/16432 \353\226\241\354\236\245\354\210\230\354\231\200 \355\230\270\353\236\221\354\235\264.py" "b/16432 \353\226\241\354\236\245\354\210\230\354\231\200 \355\230\270\353\236\221\354\235\264.py" deleted file mode 100644 index 890078a..0000000 --- "a/16432 \353\226\241\354\236\245\354\210\230\354\231\200 \355\230\270\353\236\221\354\235\264.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(cnt,dduks,yesterday): - global answer - if cnt == N: - for d in dduks: - print(d) - exit() - for dduk in days[cnt]: - if dduk != yesterday and not ate[cnt][dduk-1]: - ate[cnt][dduk-1] = True - DFS(cnt+1, dduks + [dduk],dduk) - -N = int(input()) -days = [] -answer = [] -for _ in range(N): - m,*dduk = map(int, input().split()) - days.append(dduk) -ate = {i:[False for _ in range(10)] for i in range(N+1)} -DFS(0,[],0) -print(-1) \ No newline at end of file diff --git "a/16434\353\223\234\353\236\230\352\263\244 \354\225\244 \353\215\230\354\240\204.py" "b/16434\353\223\234\353\236\230\352\263\244 \354\225\244 \353\215\230\354\240\204.py" deleted file mode 100644 index 22bdf40..0000000 --- "a/16434\353\223\234\353\236\230\352\263\244 \354\225\244 \353\215\230\354\240\204.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline - -def is_clearDungeon(Max_hp, H_atk): - cur_hp = Max_hp - for room in dungeon: - command,atk,health = room[0],room[1],room[2] - if command==1: - if health%H_atk==0: - cur_hp -= ((health//H_atk)-1)*atk - else: - cur_hp -= (health//H_atk)*atk - if cur_hp <=0: - return False - else: - H_atk += atk - cur_hp = min(Max_hp,cur_hp+health) - return True - - -N, H_atk = map(int,input().split()) -dungeon = [list(map(int, input().split())) for _ in range(N)] - -start = 1 -end = int(2e17) -target=0 -while start <= end: - mid = (start+end)//2 - if is_clearDungeon(mid, H_atk): - end = mid-1 - target = mid - else: - start = mid+1 - -print(target) \ No newline at end of file diff --git "a/16435 \354\212\244\353\204\244\354\235\264\355\201\254\353\262\204\353\223\234.py" "b/16435 \354\212\244\353\204\244\354\235\264\355\201\254\353\262\204\353\223\234.py" deleted file mode 100644 index 4ca5139..0000000 --- "a/16435 \354\212\244\353\204\244\354\235\264\355\201\254\353\262\204\353\223\234.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - - -N, L = map(int, input().split()) -h_arr = list(map(int, input().split())) -h_arr.sort() -for h in h_arr: - if L >= h: - L += 1 - continue - break -print(L) \ No newline at end of file diff --git "a/16440\354\240\234\354\235\264\355\201\254\354\231\200 \354\274\200\354\235\264\355\201\254.py" "b/16440\354\240\234\354\235\264\355\201\254\354\231\200 \354\274\200\354\235\264\355\201\254.py" deleted file mode 100644 index d90b6cf..0000000 --- "a/16440\354\240\234\354\235\264\355\201\254\354\231\200 \354\274\200\354\235\264\355\201\254.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -cakes = input().rstrip() -cnt = 0 -for i in range(n//2): - if cakes[i]=='s': - cnt += 1 -if cnt == n//4: - print(1) - print(n//2) -else: - # 중앙을 기준으로 오른쪽 s면 cnt증가 왼쪽 s면 cnt감소. cnt 맞춰준다(범위를 오른쪽으로 옮기는 과정.) - # 어차피 자르고 남은 곳도 n//4, n//4이므로 기왕이면 뭉쳐있는곳을 찾는게 나음. - # 슬라이딩 윈도우. - for i in range(n//2,n): - if cakes[i]=='s': - cnt += 1 - if cakes[i-n//2]=='s': - cnt -= 1 - if cnt==n//4: - print(2) - print(i-n//2+1,i+1) - break \ No newline at end of file diff --git "a/1644\354\206\214\354\210\230\354\235\230 \354\227\260\354\206\215\355\225\251.py" "b/1644\354\206\214\354\210\230\354\235\230 \354\227\260\354\206\215\355\225\251.py" deleted file mode 100644 index 95f8195..0000000 --- "a/1644\354\206\214\354\210\230\354\235\230 \354\227\260\354\206\215\355\225\251.py" +++ /dev/null @@ -1,27 +0,0 @@ -import math - -N = int(input()) - -a = [False, False] + [True] * (N-1) -prime_num = [] - -for i in range(2, N+1): - if a[i]: - prime_num.append(i) - for j in range(2*i, N+1, i): - a[j] = False - -answer = 0 -start = 0 -end = 0 -while end <= len(prime_num): - temp_sum = sum(prime_num[start:end]) - if temp_sum == N: - answer += 1 - end += 1 - elif temp_sum < N: - end += 1 - else: - start += 1 - -print(answer) \ No newline at end of file diff --git "a/1647\353\217\204\354\213\234\353\266\204\355\225\240\352\263\204\355\232\215.py" "b/1647\353\217\204\354\213\234\353\266\204\355\225\240\352\263\204\355\232\215.py" deleted file mode 100644 index 7e1b980..0000000 --- "a/1647\353\217\204\354\213\234\353\266\204\355\225\240\352\263\204\355\232\215.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -def find(a): - if parents[a] == a: - return a - parents[a] = find(parents[a]) - return parents[a] - -def union(a,b): - a = find(a) - b = find(b) - - if b>a: - parents[b] = a - else: - parents[a] = b - - -# N개의 집 M개의 길(쌍방향) / 마을 분리. -# 나머지 길의 유지비 합 최소 / 마을 2개로 분리,길 최소로. -# 1번은 분리(유니온 파인드에서 마지막 하나만 연결 안하면 됨? ㅇㅇ 됨 ) -# 그냥 크루스칼 돌리고 마지막 가중치 긴거 하나만 연결 안하면 됨ok. -N,M = map(int,input().split()) -parents = [i for i in range(N+1)] -heap = [] -for _ in range(M): - A,B,C = map(int,input().split()) - heappush(heap,[C,A,B]) - -total_cost = 0 -count = 0 -while heap: - cost,a,b = heappop(heap) - if find(a) != find(b): - union(a,b) - total_cost +=cost - count+=1 - if count==N-2: - break -print(total_cost) \ No newline at end of file diff --git "a/1648 \352\262\251\354\236\220\355\214\220 \354\261\204\354\232\260\352\270\260.py" "b/1648 \352\262\251\354\236\220\355\214\220 \354\261\204\354\232\260\352\270\260.py" deleted file mode 100644 index 965126c..0000000 --- "a/1648 \352\262\251\354\236\220\355\214\220 \354\261\204\354\232\260\352\270\260.py" +++ /dev/null @@ -1,123 +0,0 @@ -# 비트마스킹 DP -import sys -input = sys.stdin.readline -N, M = map(int, input().split()) -DP = [[0] * (1 << M) for num in range(N * M + 1)] -DP[N * M][0] = 1 -for num in reversed(range(N * M)): - for state in range(1 << M): - if state & 1: - DP[num][state] = DP[num + 1][state >> 1] % 9901 - else: - if num < (N-1) * M: - DP[num][state] += DP[num + 1][(1 << (M - 1)) | (state >> 1)] % 9901 - if num % M < M-1 and not state % 4: - DP[num][state] += DP[num + 2][state >> 2] % 9901 -print(DP[0][0] % 9901) - - -# 2 -n,m=map(int,input().split()) -d=[[0]*(1<>1] - continue - if i<(n-1)*m: - d[i][j]+=d[i+1][(1<<(m-1))|(j>>1)] - if i%m>2] -print(d[0][0]%9901) - -# https://www.acmicpc.net/problem/1648 -import sys - -read = sys.stdin.readline -n, m = map(int, read().strip().split()) -dp = [[-1 for _ in range(1 << m)] for _ in range(n * m)] - - -def getAnswer(idx, state): - if idx == n * m: - return 0 if state else 1 - - if dp[idx][state] != -1: - return dp[idx][state] - - ret = 0 - if state & 1: - ret += getAnswer(idx + 1, state >> 1) - else: - if idx % m < (m - 1) and not (state & 2): - ret += getAnswer(idx + 2, state >> 2) - ret += getAnswer(idx + 1, state >> 1 | (1 << (m - 1))) - ret %= 9901 - dp[idx][state] = ret - return ret - - -print(getAnswer(0, 0)) - -# 4 -import sys -sys.setrecursionlimit(10**6) -input = sys.stdin.readline - -def getBit(first, flag,cur): - if cur >= n: - result[first] += [flag] - return - - getBit(first,flag,cur+1) - if (3<=0: - return DP[i][n] - r=0 - if n&1==1: - r+=go(i+1,n>>1) - else: - r+=go(i+1,(n>>1)+(1<<(M-1))) - if n&2!=2 and i%M!=M-1: - r+=go(i+2,n>>2) - DP[i][n]=r - return DP[i][n] -print(go(0,0)%9901) \ No newline at end of file diff --git "a/16481\354\233\220\354\240\204\353\254\270\352\260\200\354\247\204\354\232\260.py" "b/16481\354\233\220\354\240\204\353\254\270\352\260\200\354\247\204\354\232\260.py" deleted file mode 100644 index 2d32f6b..0000000 --- "a/16481\354\233\220\354\240\204\353\254\270\352\260\200\354\247\204\354\232\260.py" +++ /dev/null @@ -1,7 +0,0 @@ - - -ra,rb,rc = map(int,input().split()) - -R = 1/ra + 1/rb + 1/rc - -print(1/R) \ No newline at end of file diff --git "a/16507 \354\226\264\353\221\220\354\232\264 \352\261\264 \353\254\264\354\204\234\354\233\214.py" "b/16507 \354\226\264\353\221\220\354\232\264 \352\261\264 \353\254\264\354\204\234\354\233\214.py" deleted file mode 100644 index 3b9d596..0000000 --- "a/16507 \354\226\264\353\221\220\354\232\264 \352\261\264 \353\254\264\354\204\234\354\233\214.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -R, C, Q = map(int, input().split()) -matrix = [list(map(int, input().split())) for _ in range(R)] -dp = [[0 for _ in range(C + 1)] for _ in range(R + 1)] - -for i in range(1, R + 1): - for j in range(1, C + 1): - dp[i][j] = -dp[i-1][j-1] + dp[i-1][j] + dp[i][j-1] + matrix[i-1][j-1] - -for i in range(Q): - r1, c1, r2, c2 = map(int, input().split()) - ans = dp[r2][c2] - dp[r1-1][c2] - dp[r2][c1-1] + dp[r1-1][c1-1] - num = ((r2 - r1) + 1) * ((c2 - c1) + 1) - print(ans // num) diff --git "a/1654\353\236\234\354\204\240\354\236\220\353\245\264\352\270\260.py" "b/1654\353\236\234\354\204\240\354\236\220\353\245\264\352\270\260.py" deleted file mode 100644 index e37a180..0000000 --- "a/1654\353\236\234\354\204\240\354\236\220\353\245\264\352\270\260.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -K,N = map(int,input().split()) -lengths = [] -for _ in range(K): - lengths.append(int(input())) - -start = 1 -end = 2**31-1 -answer = 0 -mid = 0 - -while start <=end: - mid = (start+end)//2 - count=0 - for i in range(K): - count+=lengths[i]//mid - if count>=N: - answer = mid - start = mid+1 - else: - end = mid-1 -print(answer) diff --git "a/1655\352\260\200\354\232\264\353\215\260\353\245\274 \353\247\220\355\225\264\354\232\224.py" "b/1655\352\260\200\354\232\264\353\215\260\353\245\274 \353\247\220\355\225\264\354\232\224.py" deleted file mode 100644 index 289a729..0000000 --- "a/1655\352\260\200\354\232\264\353\215\260\353\245\274 \353\247\220\355\225\264\354\232\224.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline -import heapq - - - -n = int(input()) -max_h, min_h = [], [] -# max_h[0][1]값을 기준으로 큰 값은 min_h, 같거나 작은 값은 max_h에 삽입 -for _ in range(n): - num = int(input()) - if len(max_h) == len(min_h): - heapq.heappush(max_h, (-num, num)) - else: - heapq.heappush(min_h, (num, num)) - # 왼쪽 힙의 큰값이 오른쪽 힙의 작은 값보다 크면 바꿔줌. - if len(max_h) >= 1 and len(min_h) >= 1 and max_h[0][1] > min_h[0][1]: - max_value = heapq.heappop(max_h)[1] - min_value = heapq.heappop(min_h)[1] - heapq.heappush(max_h, (-min_value, min_value)) - heapq.heappush(min_h, (max_value, max_value)) - # 왼쪽 힙 첫 값만 읽어줌. - print(max_h[0][1]) - diff --git "a/1660\354\272\241\355\213\264 \354\235\264\353\213\244\354\206\234.py" "b/1660\354\272\241\355\213\264 \354\235\264\353\213\244\354\206\234.py" deleted file mode 100644 index 4af2db0..0000000 --- "a/1660\354\272\241\355\213\264 \354\235\264\353\213\244\354\206\234.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -nums = [] -num = 0 -idx = 1 -while num < N: - num += (idx * (idx + 1)) // 2 - nums.append(num) - idx += 1 -dp = [float('inf')] * (N + 1) -for i in range(1, N + 1): - for num in nums: - if num == i: - dp[i] = 1 - break - if num > i: break - dp[i] = min(dp[i], 1 + dp[i - num]) -print(dp[N]) \ No newline at end of file diff --git "a/16637 \352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260.py" "b/16637 \352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260.py" deleted file mode 100644 index 1b0bef4..0000000 --- "a/16637 \352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260.py" +++ /dev/null @@ -1,40 +0,0 @@ - - - -def add_parenthesis(idx, cal_ord): - global answer - # 계산 종료 - if idx == N: - for i, j in enumerate(cal_ord): - if len(j) == 3: - cal_ord[i] = str(eval(j)) - result = cal_ord[0] - for _ in range(1, len(cal_ord), 2): - result = eval(str(result)+cal_ord[_]+cal_ord[_+1]) - - if answer < result: - answer = result - return - - # 연산 기호 넣고 - cal_ord.append(equat[idx]) - # 다음 idx로 넘어감. - add_parenthesis(idx + 1, cal_ord) - del cal_ord[-1] - - if cal_ord[-1] in symbol and idx + 3 <= N: - cal_ord.append(equat[idx:idx+3]) - add_parenthesis(idx + 3, cal_ord) - del cal_ord[-1] - -N = int(input()) -equat = input() -answer = -2 ** 31 - -if N == 1: - print(max(answer, int(equat))) - exit() - -symbol = ["+", "-", "*"] -add_parenthesis(1, [equat[0]]) -print(answer) \ No newline at end of file diff --git "a/16637\352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260_dfs.py" "b/16637\352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260_dfs.py" deleted file mode 100644 index 6d43986..0000000 --- "a/16637\352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260_dfs.py" +++ /dev/null @@ -1,36 +0,0 @@ -from math import inf -from sys import stdin - - -def dfs(idx, sub_total): - global answer - - if idx == len(op): - answer = max(answer, int(sub_total)) - return - - # (3 + 8) * 7 - 9 * 2 부터 시작. - first = str(eval(sub_total + op[idx] + nums[idx + 1])) - dfs(idx + 1, first) - - if idx + 1 < len(op): - # 3 + (8 * 7) - 9 * 2 부터 시작 - second = str(eval(nums[idx + 1] + op[idx + 1] + nums[idx + 2])) - second = str(eval(sub_total + op[idx] + second)) - # op를 2개 소모했으므로 idx + 2 - dfs(idx + 2, second) - - -if __name__ == '__main__': - n = int(stdin.readline()) - expression = stdin.readline().rstrip() - nums, op = [], [] - answer = -inf - - for e in expression: - nums.append(e) if e.isdigit() else op.append(e) - - dfs(0, nums[0]) - print(answer) - - diff --git "a/16637\352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260_\354\233\220\353\235\274\354\235\270.py" "b/16637\352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260_\354\233\220\353\235\274\354\235\270.py" deleted file mode 100644 index ef26908..0000000 --- "a/16637\352\264\204\355\230\270\354\266\224\352\260\200\355\225\230\352\270\260_\354\233\220\353\235\274\354\235\270.py" +++ /dev/null @@ -1,24 +0,0 @@ -j=int -def g(x,y,c): - return x+y if c=='+'else x-y if c=='-'else x*y -def f(i,c): - return c if i>=n else max(f(i+2,g(c,j(s[i]),s[i-1])),f(i+4,g(c,g(j(s[i]),j(s[i+2]),s[i+1]),s[i-1]))if i j: - continue - if s[i][0] >= s[j][0] and s[i][1] >= s[j][1] and s[i][2] >= s[j][2]: - can_eat[i][j] = True -result = 0 -for _ in range(2): - for i in range(1, n + 1): - visit = [0 for _ in range(n + 1)] - dfs(i) -print(d[1:].count(0)) \ No newline at end of file diff --git "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2541.py" "b/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2541.py" deleted file mode 100644 index e8b8660..0000000 --- "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2541.py" +++ /dev/null @@ -1,70 +0,0 @@ -import sys - -input = sys.stdin.readline - -n = int(input()) -sharks = [] -for _ in range(n): - # 크기 속도 지능 - sharks.append(list(map(int, input().strip().split()))) -destination = n + n + 1 -one_des = destination + 1 -graph = dict([(i, {}) for i in range(one_des)]) -for i, eat in enumerate(sharks): - eat_index = i + 1 - graph[0][eat_index] = 2 - for j, food in enumerate(sharks): - food_index = n + j + 1 - if i == j: - continue - else: - if eat[0] >= food[0] and eat[1] >= food[1] and eat[2] >= food[2]: - if eat[0] == food[0] and eat[1] == food[1] and eat[2] == food[2]: - if i > j: - graph[eat_index][food_index] = 1 - else: - graph[eat_index][food_index] = 1 -for i in range(n + 1, destination): - graph[i][destination] = 1 - - -def search(current): - visit[current] = 1 - use_graph = graph[current] - - for e in use_graph: - # e - 연결된 그래프의 노드 use_graph[e] - 웨이트 - # 0이 되면 제거하기로 하자 -> 0이 있다면 0이 되는지도 체크 - if visit[destination] == 1: - return 1 - if visit[e] == 1: - continue - else: - parent[e] = current - search(e) - - -# 경로를 찾을 수 없을 때 멈추기 -while True: - visit = [0 for _ in range(one_des)] - parent = [None for _ in range(one_des)] - search(0) - if visit[destination] == 0: - break - end = destination - while True: - pa = parent[end] - if pa == None: - break - - if graph[pa][end] == 1: - del graph[pa][end] - else: - graph[pa][end] -= 1 - if pa != 0: - try: - graph[end][pa] += 1 - except: - graph[end][pa] = 1 - end = pa -print(n - len(graph[destination])) \ No newline at end of file diff --git "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2542.py" "b/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2542.py" deleted file mode 100644 index 1ae580b..0000000 --- "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2542.py" +++ /dev/null @@ -1,49 +0,0 @@ -n=int(input()) -a=[[*map(int,input().split())] for _ in range(n)] -adj=[[] for _ in range(2*n+1)] -for i in range(n-1): - xi,yi,zi=a[i] - for j in range(i+1,n): - xj,yj,zj=a[j] - if xi>=xj and yi>=yj and zi>=zj: - adj[2*i+1].append(j+1) - adj[2*i+2].append(j+1) - elif xi<=xj and yi<=yj and zi<=zj: - adj[2*j+1].append(i+1) - adj[2*j+2].append(i+1) -def bfs(): - Q=[] - dist[0]=-1 - for i in range(1,2*n+1): - if pair_u[i]==0: - dist[i]=0 - Q.append(i) - else: - dist[i]=-1 - while Q and dist[0]==-1: - q=[] - for i in Q: - for j in adj[i]: - if dist[pair_v[j]]==-1: - dist[pair_v[j]]=dist[i]+1 - q.append(pair_v[j]) - Q=q - return dist[0]>-1 -def dfs(i): - if i==0: return 1 - for j in adj[i]: - if dist[pair_v[j]]==dist[i]+1: - if dfs(pair_v[j]): - pair_u[i]=j - pair_v[j]=i - return 1 - return 0 -pair_u,pair_v=[0]*(2*n+1),[0]*(n+1) -dist=[0]*(2*n+1) -c=0 -while bfs(): - for i in range(1,2*n+1): - if pair_u[i]==0: - if dfs(i): - c+=1 -print(n-c) \ No newline at end of file diff --git "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2543.py" "b/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2543.py" deleted file mode 100644 index fec3281..0000000 --- "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2543.py" +++ /dev/null @@ -1,15 +0,0 @@ -def dfs(x, v): - v[x] = 1 - for t in a[x]: - if d[t] < 0 or not v[d[t]] and dfs(d[t], v): - d[t] = x - return 1 - return 0 - - -n = int(input()) -s = sorted([tuple(map(int, input().split())) for _ in range(n)]) -a = [[j for j in range(i) if all(p >= q for p, q in zip(s[i], s[j]))] for i in range(n)] -d = [-1] * 51 - -print(n - sum(dfs(i, [0] * n) for i in range(n) for _ in '..')) \ No newline at end of file diff --git "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2544.py" "b/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2544.py" deleted file mode 100644 index 72967bb..0000000 --- "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2544.py" +++ /dev/null @@ -1,33 +0,0 @@ -def can_eat(i,j): - if shark[i][0]>=shark[j][0] and shark[i][1]>=shark[j][1] and shark[i][2]>=shark[j][2]: return True - return False - -def dfs(i): - global visit,shark_eated - if visit[i]: return 0 - visit[i] = True - for j in shark_eat[i]: - if shark_eated[j] == -1 or dfs(shark_eated[j]): - shark_eated[j]=i - return 1 - return 0 - -n = int(input()) -shark = [list(map(int,input().split())) for _ in range(n)] -shark_eat = [[] for _ in range(n)] -visit = [False]*n -shark_eated = [-1]*n -count_die = 0 - -for i in range(n): - for j in range(n): - if can_eat(i,j): - if shark[i] == shark[j] and i <= j: continue - shark_eat[i].append(j) - -for i in range(2): - for j in range(n): - visit = [False]*n - count_die += dfs(j) - -print(n-count_die) diff --git "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2545.py" "b/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2545.py" deleted file mode 100644 index 4085c64..0000000 --- "a/1671 \354\203\201\354\226\264\354\235\230 \354\240\200\353\205\201\354\213\235\354\202\2545.py" +++ /dev/null @@ -1,69 +0,0 @@ -''' -설명은 -https://blog.naver.com/na_qa/221531904546 -''' -import sys -from collections import deque -input = lambda:sys.stdin.readline().strip() -INF = sys.maxsize - -n = int(input()) -graph = [[]for i in range(n+1)] -size = [INF for i in range(n+1)] -speed = [INF for i in range(n+1)] -intel = [INF for i in range(n+1)] -for i in range(1,n+1): - size[i],speed[i],intel[i] = map(int, input().split()) - -#n개에 대해 전수조사 -for i in range(1,n+1): - for j in range(1,n+1): - size_i, size_j,speed_i,speed_j,intel_i,intel_j = size[i],size[j],speed[i],speed[j],intel[i],intel[j] - #만약 값이 모두 크거나 같다면 - if size_i>=size_j and speed_i>=speed_j and intel_i>=intel_j: - #그런데 모두 같은 경우, i==j일수도 있고, 또한 2번 중복(i->j, j->i)되기때문에 i>j라는 조건을 걸어줌 - if size_i==size_j and speed_i==speed_j and intel_i==intel_j and i>=j: - continue - graph[i].append(j) - - -def bfs(): #그룹A의 Node들의 Level을 매기기 위해서 - que = deque() - for a in range(1,n+1): - if len(groupA[a])<2: #매칭되어있지않으면 level은 0으로 시작 - dist[a] = 0 - que.append(a) - else: - dist[a] = INF - dist[0] = INF - while que: #그룹A의 Node들의 Level을 측정 - a = que.popleft() - if dist[a] < dist[0]: - for b in graph[a]: - if dist[groupB[b]] == INF: - dist[groupB[b]] = dist[a] + 1 - que.append(groupB[b]) - return dist[0] != INF -def dfs(a): - if a: - for b in graph[a]: #그룹A의 a번째 Node와 연결되어있는 그룹B의 b중에서 - #(매칭되어있지않거나, b에 연결된 a'와 a의 Level이 1차이 나거나), (b에 연결되어있는 a'가 (매칭되어있지않거나, level이 1차이 나면)) - if dist[groupB[b]] == dist[a] + 1 and dfs(groupB[b]): - groupA[a].append(b) - groupB[b] = a - return 1 - dist[a] = INF - return 0 - return 1 - -groupA = [[] for i in range(n+1)] -groupB = [0 for i in range(n+1)] -dist = [INF for i in range(n+1)] #그룹A의 Node들의 Level -match = 0 #매칭숫자 -while bfs(): - for a in range(1, n+1): - if len(groupA[a])<2: #매칭이 안되어있고 - match += dfs(a) - if len(groupA[a])<2: - match += dfs(a) -print(n-match) \ No newline at end of file diff --git "a/1676\355\214\251\355\206\240\353\246\254\354\226\27490.py" "b/1676\355\214\251\355\206\240\353\246\254\354\226\27490.py" index dabd7a8..43c44eb 100644 --- "a/1676\355\214\251\355\206\240\353\246\254\354\226\27490.py" +++ "b/1676\355\214\251\355\206\240\353\246\254\354\226\27490.py" @@ -1,2 +1,2 @@ -N = int(input()) +N = int(input()) print(N//5 + N//25 + N//125) \ No newline at end of file diff --git "a/16916\353\266\200\353\266\204\353\254\270\354\236\220\354\227\264.py" "b/16916\353\266\200\353\266\204\353\254\270\354\236\220\354\227\264.py" deleted file mode 100644 index 5f050ef..0000000 --- "a/16916\353\266\200\353\266\204\353\254\270\354\236\220\354\227\264.py" +++ /dev/null @@ -1,43 +0,0 @@ -import sys -input = sys.stdin.readline - -# -def getPI(pattern): - j = 0 - for i in range(1, len(pattern)): - # 일치하지 않으면 그 이전 위치에서의 반복값으로 인덱스를 되돌린다. - # 즉 비교군 j의 인덱스를 이전에 일치했던 곳으로 되돌려 pattern매칭을 해본다. 또 틀리면 그전으로 그전으로. 해서 다시 번호를 적어나간다. - # 결국 일치하는게 없다면 j는 0까지 되돌아간다. - while j > 0 and pattern[i] != pattern[j]: - j = pi[j - 1] - # 일치하면 일치한 곳에 +1해주면서 몇개가 반복되나 체크. - if pattern[i] == pattern[j]: - j += 1 - pi[i] = j - -def KMP(s, pattern): - getPI(pattern) - # 배열이 완성되었다면 s배열과 pattern배열을 비교해야한다. - # s와 pattern이 일치한다면 j를 계속 늘리며 비교해 j의 크기가 pattern배열만큼 커지면 True를 반환. - # 중간에 불일치가 일어난다면 j의 위치를 또 그 이전 불일치가 일어났던 곳으로 한칸씩 당기며 s와 비교한다. - # 없다면 또 j는 0으로 돌아간다. - j = 0 - for i in range(len(s)): - while j > 0 and s[i] != pattern[j]: - j = pi[j - 1] - if s[i] == pattern[j]: - if j == len(pattern) - 1: - return True - else: - j += 1 - return False - -s = input().rstrip() -pattern = input().rstrip() -# pattern안에서 반복되는 pattern이 있는지 검사할 리스트. -pi = [0 for x in range(len(pattern))] - -if KMP(s, pattern): - print('1') -else: - print('0') \ No newline at end of file diff --git "a/16918 \353\264\204\353\262\204\353\247\250.py" "b/16918 \353\264\204\353\262\204\353\247\250.py" deleted file mode 100644 index d8174ee..0000000 --- "a/16918 \353\264\204\353\262\204\353\247\250.py" +++ /dev/null @@ -1,51 +0,0 @@ -# 16918, 봄버맨 -import sys -from collections import deque - - -def loc_bombs(): # 폭탄 위치 찾아 bombs deque에 저장 - for i in range(R): - for j in range(C): - if board[i][j] == 'O': - bombs.append((i, j)) - - -def make_bombs(): # 모든 자리에 폭탄 설치 - for i in range(R): - for j in range(C): - if board[i][j] == '.': - board[i][j] = 'O' - - -def explode(): # bombs deque에 들어있는 좌표로 폭탄 터트림 - while bombs: - r, c = bombs.popleft() - board[r][c] = '.' - if 0 <= r - 1: - board[r - 1][c] = '.' - if r + 1 < R: - board[r + 1][c] = '.' - if 0 <= c - 1: - board[r][c - 1] = '.' - if c + 1 < C: - board[r][c + 1] = '.' - - -R, C, N = map(int, sys.stdin.readline().split()) -board = [list(sys.stdin.readline().rstrip()) for _ in range(R)] - -N -= 1 # 1초 동안 아무것도 하지 않는다 -while N: - bombs = deque() - loc_bombs() - make_bombs() - N -= 1 - if N == 0: - break - explode() - N -= 1 - -for i in range(len(board)): - for j in range(len(board[0])): - print(board[i][j], end='') - print() \ No newline at end of file diff --git "a/16926 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2601.py" "b/16926 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2601.py" deleted file mode 100644 index 5d04dbc..0000000 --- "a/16926 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2601.py" +++ /dev/null @@ -1,38 +0,0 @@ -import sys -input = sys.stdin.readline - -def rotate(start): - - #init_tmp - top = matrix[start][start] - left = matrix[N-start-1][start] - bottom = matrix[N-start-1][M-start-1] - right = matrix[start][M-start-1] - - # top - for i in range(start+1,M-start): - matrix[start][i-1] = matrix[start][i] - # left - for i in range(N-start-1,start,-1): - matrix[i][start] = matrix[i-1][start] - # bottom - for i in range(M-start-1,start+1,-1): - matrix[N-start-1][i] = matrix[N-start-1][i-1] - # right - for i in range(start+1,N-start): - matrix[i-1][M-start-1] = matrix[i][M-start-1] - # finish - matrix[start+1][start] = top - matrix[N-start-1][start+1] = left - matrix[N-start-2][M-start-1] = bottom - matrix[start][M-start-2] = right - -N, M, R = map(int,input().split()) -matrix = [list(map(int, input().split())) for _ in range(N)] -short = N if N <= M else M -for _ in range(R): - for i in range(short//2): - rotate(i) - -for row in matrix: - print(*row) \ No newline at end of file diff --git "a/16927 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2602.py" "b/16927 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2602.py" deleted file mode 100644 index 3ba161b..0000000 --- "a/16927 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2602.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -input = sys.stdin.readline - -def rotate(start): - - #init_tmp - top = matrix[start][start] - left = matrix[N-start-1][start] - bottom = matrix[N-start-1][M-start-1] - right = matrix[start][M-start-1] - - # top - for i in range(start+1,M-start): - matrix[start][i-1] = matrix[start][i] - # left - for i in range(N-start-1,start,-1): - matrix[i][start] = matrix[i-1][start] - # bottom - for i in range(M-start-1,start+1,-1): - matrix[N-start-1][i] = matrix[N-start-1][i-1] - # right - for i in range(start+1,N-start): - matrix[i-1][M-start-1] = matrix[i][M-start-1] - # finish - matrix[start+1][start] = top - matrix[N-start-1][start+1] = left - matrix[N-start-2][M-start-1] = bottom - matrix[start][M-start-2] = right - -N, M, R = map(int,input().split()) -size = 2 * N + 2 * M - 4 -matrix = [list(map(int, input().split())) for _ in range(N)] -short = N if N <= M else M - -for n_th in range(short//2): - for _ in range(R%(size-8*n_th)): - rotate(n_th) - -for row in matrix: - print(*row) \ No newline at end of file diff --git "a/16928 \353\261\200\352\263\274 \354\202\254\353\213\244\353\246\254\352\262\214\354\236\204.py" "b/16928 \353\261\200\352\263\274 \354\202\254\353\213\244\353\246\254\352\262\214\354\236\204.py" deleted file mode 100644 index 806aa2b..0000000 --- "a/16928 \353\261\200\352\263\274 \354\202\254\353\213\244\353\246\254\352\262\214\354\236\204.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(start): - q = deque() - q.append((start,0)) - visited[start] = True - while q: - cur_node, cnt = q.popleft() - for i in range(1,7): - next_node = cur_node+i - if next_node >= 100: - return cnt+1 - if visited[next_node]: - continue - visited[next_node] = True - if next_node in port: - if not visited[port[next_node]]: - visited[port[next_node]] = True - q.append((port[next_node],cnt+1)) - else: - q.append((next_node, cnt+1)) - - -N, M = map(int, input().split()) -visited = {i: False for i in range(1,101)} -port = {} -for _ in range(N+M): - a, b = map(int, input().split()) - port[a] = b - -print(bfs(1)) \ No newline at end of file diff --git a/16929two_Dots.py b/16929two_Dots.py index 3e29969..6176b64 100644 --- a/16929two_Dots.py +++ b/16929two_Dots.py @@ -1,43 +1,43 @@ -import sys -input = sys.stdin.readline - -dx = [-1, 1, 0, 0] # 상하좌우 -dy = [0, 0, -1, 1] - -def DFS(x, y): - global answer - visited[x][y] = 1 # 방문 체크 - for d in range(4): - X = x + dx[d] - Y = y + dy[d] - if 0 <= X < N and 0 <= Y < M: # 다음 타겟이 matrix 안에 있으면 - if matrix[X][Y] == matrix[x][y]: # 값(색깔)이 같으면 - if visited[X][Y] == 0: # 아직 방문한 적이 없다면 - my_snake.append([X, Y]) #방문 순서에 기록한다 - DFS(X, Y) # 방문하러 가기 (재귀) - my_snake.pop() # 방문 순서에서 제외한다 - else: # 방문한 적이 있다면 - if X == my_snake[-2][0] and Y == my_snake[-2][1]: # 바로 전에 방문한 곳이면 - pass - else: # 바로 전은 아닌데 언젠가 방문한 적이 있음 (사이클 형성) - answer = 'Yes' # 답을 바꾸고 바로 빠져나간다 - return - if answer == 'Yes': - return - -N, M = map(int, input().split()) -matrix = [list(input()) for _ in range(N)] -visited = [[0]*M for _ in range(N)] # 방문 체크용 -answer = 'No' # 기본값은 No - -for i in range(N): - for j in range(M): - if visited[i][j] == 0: # 해당 구역을 방문한 적이 없다면 - my_snake = [[i, j]] # 방문 순서 기록용 - DFS(i, j) - if answer == 'Yes': # 답이 바뀌면 바로 빠져나온다. - break - if answer == 'Yes': - break - +import sys +input = sys.stdin.readline + +dx = [-1, 1, 0, 0] # 상하좌우 +dy = [0, 0, -1, 1] + +def DFS(x, y): + global answer + visited[x][y] = 1 # 방문 체크 + for d in range(4): + X = x + dx[d] + Y = y + dy[d] + if 0 <= X < N and 0 <= Y < M: # 다음 타겟이 matrix 안에 있으면 + if matrix[X][Y] == matrix[x][y]: # 값(색깔)이 같으면 + if visited[X][Y] == 0: # 아직 방문한 적이 없다면 + my_snake.append([X, Y]) #방문 순서에 기록한다 + DFS(X, Y) # 방문하러 가기 (재귀) + my_snake.pop() # 방문 순서에서 제외한다 + else: # 방문한 적이 있다면 + if X == my_snake[-2][0] and Y == my_snake[-2][1]: # 바로 전에 방문한 곳이면 + pass + else: # 바로 전은 아닌데 언젠가 방문한 적이 있음 (사이클 형성) + answer = 'Yes' # 답을 바꾸고 바로 빠져나간다 + return + if answer == 'Yes': + return + +N, M = map(int, input().split()) +matrix = [list(input()) for _ in range(N)] +visited = [[0]*M for _ in range(N)] # 방문 체크용 +answer = 'No' # 기본값은 No + +for i in range(N): + for j in range(M): + if visited[i][j] == 0: # 해당 구역을 방문한 적이 없다면 + my_snake = [[i, j]] # 방문 순서 기록용 + DFS(i, j) + if answer == 'Yes': # 답이 바뀌면 바로 빠져나온다. + break + if answer == 'Yes': + break + print(answer) \ No newline at end of file diff --git "a/16929two_Dots_\354\235\264\354\240\204\352\260\222\354\240\200\354\236\245\353\260\251\354\213\235.py" "b/16929two_Dots_\354\235\264\354\240\204\352\260\222\354\240\200\354\236\245\353\260\251\354\213\235.py" index 8167424..4daec27 100644 --- "a/16929two_Dots_\354\235\264\354\240\204\352\260\222\354\240\200\354\236\245\353\260\251\354\213\235.py" +++ "b/16929two_Dots_\354\235\264\354\240\204\352\260\222\354\240\200\354\236\245\353\260\251\354\213\235.py" @@ -1,33 +1,36 @@ -N,M=map(int,input().split()) -arr=[list(map(str,input()))for _ in range(N)] -visited = [[False]*M for _ in range(N)] -dy=[0,0,1,-1] -dx=[1,-1,0,0] -flag=False -def scope(y,x): - if y>=0 and y=0 and x=0 and y=0 and x= n or y >= m: - return False - return True - -solve() \ No newline at end of file diff --git "a/16934\352\262\214\354\236\204\353\213\211\353\204\244\354\236\204.py" "b/16934\352\262\214\354\236\204\353\213\211\353\204\244\354\236\204.py" deleted file mode 100644 index d37661b..0000000 --- "a/16934\352\262\214\354\236\204\353\213\211\353\204\244\354\236\204.py" +++ /dev/null @@ -1,48 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - - -class Node: - def __init__(self): - self.word = False - self.children = {} - - -class Trie: - - def __init__(self): - self.root = Node() - - def insert(self, word): - node = self.root - - for char in word: - if char not in node.children: - node.children[char] = Node() - node = node.children[char] - same_nick[word] += 1 - node.word = True - - def search(self, word): - node = self.root - re_word = '' - for char in word: - re_word += char - if char not in node.children: - return re_word - node = node.children[char] - - if node.word: - re_word += str(same_nick[re_word]+1) - return re_word - - -N = int(input()) -tree = Trie() -same_nick = defaultdict(int) -for _ in range(N): - word = input().rstrip() - print(tree.search(word)) - tree.insert(word) - diff --git "a/16938 \354\272\240\355\224\204\354\244\200\353\271\204.py" "b/16938 \354\272\240\355\224\204\354\244\200\353\271\204.py" deleted file mode 100644 index 2d2e06e..0000000 --- "a/16938 \354\272\240\355\224\204\354\244\200\353\271\204.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -def dfs(idx, s, min_n, max_n): - global cnt - if L <= s <= R and max_n - min_n >= X: - cnt += 1 - if s > R: - return - for next_idx in range(idx+1,N): - dfs(next_idx, s+arr[next_idx], min(min_n, arr[next_idx]), max(max_n, arr[next_idx])) -N, L, R, X = map(int, input().split()) -arr = list(map(int, input().split())) -cnt = 0 -dfs(-1, 0, float('inf'), 0) -print(cnt) \ No newline at end of file diff --git "a/1693\355\212\270\353\246\254 \354\203\211\354\271\240\355\225\230\352\270\260.py" "b/1693\355\212\270\353\246\254 \354\203\211\354\271\240\355\225\230\352\270\260.py" deleted file mode 100644 index 5316b84..0000000 --- "a/1693\355\212\270\353\246\254 \354\203\211\354\271\240\355\225\230\352\270\260.py" +++ /dev/null @@ -1,116 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**6) - - -def dfs(idx): - for i in s[idx]: - if not visit[i]: - visit[i] = True - dfs(i) - for j in range(1, 17): - m_num = 100000000 - for k in range(1, 17): - if j != k: - if m_num > dp[i][k]: - m_num = dp[i][k] - dp[idx][j] += m_num - for i in range(1, 17): - dp[idx][i] += i - return - - -n = int(input()) -s = [[] for i in range(n + 1)] -dp = [[0] * 17 for i in range(n + 1)] -visit = [False for i in range(n + 1)] - -for i in range(n - 1): - a, b = map(int, input().split()) - s[a].append(b) - s[b].append(a) -visit[1] = True -dfs(1) -print(min(dp[1][1:])) - - - -# 진한님 풀이. -from sys import setrecursionlimit as SRL, stdin -input = stdin.readline -#range = xrange - -n = int(input()) -MAXC = 18 -adj = [[] for i in range(n+1)] -tadj = [[] for i in range(n+1)] -for i in range(n-1): - a, b = map(int,input().split()) - adj[a].append(b) - adj[b].append(a) - -from collections import deque -Q = deque(); Q.append(1) -visit = [False]*(n+1); visit[1] = True -order = [] -while len(Q): - p = Q.popleft() - for q in adj[p]: - if visit[q]: continue - visit[q] = True - tadj[p].append(q) - Q.append(q) - order.append(p) - -opt = [[float('inf')]*MAXC for i in range(n+1)] -for p in reversed(order): - if not tadj[p]: - for c in range(1, MAXC): opt[p][c] = c - continue - for c in range(1, MAXC): - res = c - for q in tadj[p]: - res+= min(opt[q][j] for j in range(1, MAXC) if j != c) - opt[p][c] = res -print(min(opt[1])) - - - -# 다른분 풀이 -import collections as c -import math -d=c.defaultdict(set) -n=int(input()) -o=int(math.log2(n)+1) -for i in range(n-1): - x,y=map(int,input().split()) - d[x].add(y) - d[y].add(x) -s=c.deque([(1,0)]) -e={} -def m(l): - a=b=0 - p=q=9**9 - for i,v in enumerate(l): - if v= 0: - cache[cv] = 2 - return result if cv != result else -1 - - return -1 - - -def bfs(): - q = [] - for i in range(n): - if cache[i] == 2: - q.append(i) - dist[i] = 0 - - while q: - tmp = [] - - for cv in q: - for nv in grid[cv]: - if dist[nv] != -1: continue - dist[nv] = dist[cv] + 1 - tmp.append(nv) - - q = tmp - - - -n = int(input()) -grid = [[] for _ in range(n)] -cache = [0]*n -dist = [-1]*n - -for _ in range(n): - a,b = map(int, input().split()) - grid[a-1].append(b-1) - grid[b-1].append(a-1) - -dfs(0,-1) -bfs() -print(*dist) - -""" -0 : 미방문 -1 : 방문 --1 : 사이클 x -2 : 사이클 -""" +import sys +input = sys.stdin.readline +sys.setrecursionlimit(10**9) + + +def dfs(cv,pv): + if cache[cv] == 1: + return cv + cache[cv] = 1 + for nv in grid[cv]: + if nv == pv: continue # 양방향 그래프기 때문 + result = dfs(nv,cv) + if result >= 0: + cache[cv] = 2 + return result if cv != result else -1 + + return -1 + + +def bfs(): + q = [] + for i in range(n): + if cache[i] == 2: + q.append(i) + dist[i] = 0 + + while q: + tmp = [] + + for cv in q: + for nv in grid[cv]: + if dist[nv] != -1: continue + dist[nv] = dist[cv] + 1 + tmp.append(nv) + + q = tmp + + + +n = int(input()) +grid = [[] for _ in range(n)] +cache = [0]*n +dist = [-1]*n + +for _ in range(n): + a,b = map(int, input().split()) + grid[a-1].append(b-1) + grid[b-1].append(a-1) + +dfs(0,-1) +bfs() +print(*dist) + +""" +0 : 미방문 +1 : 방문 +-1 : 사이클 x +2 : 사이클 +""" diff --git "a/16947\354\247\200\355\225\230\354\262\2402.py" "b/16947\354\247\200\355\225\230\354\262\2402.py" index 41d8feb..2bdc29a 100644 --- "a/16947\354\247\200\355\225\230\354\262\2402.py" +++ "b/16947\354\247\200\355\225\230\354\262\2402.py" @@ -1,52 +1,52 @@ -import sys -from collections import deque -sys.setrecursionlimit(10**9) - -# DFS를 통해 사이클 찾기 - -def dfs(x, cnt): - # 이미 방문한 노드인데 거리차가 3 이상일 경우 사이클 - if check[x]: - if cnt - dist[x] >= 3: - return x - else: return -1 - check[x] = 1 - dist[x] = cnt - for y in adj_list[x]: - cycleStartNode = dfs(y, cnt + 1) - if cycleStartNode != -1: - check[x] = 2 - if x == cycleStartNode: return -1 - else: return cycleStartNode - return -1 - -if __name__ == '__main__': - N = int(input()) - adj_list = [[] * (N + 1) for _ in range(N + 1)] - # check[i] = 0 : 방문하지 않은 노드 - # check[i] = 1 : 방문한 노드 - # check[i] = 2 : 사이클에 속하는 노드 - check = [0] * (N + 1) - dist = [0] * (N + 1) - - for _ in range(N): - u, v = map(int, sys.stdin.readline().split()) - adj_list[u].append(v) - adj_list[v].append(u) - # 사이클 찾기 - dfs(1, 0) - # BFS를 통해 사이클까지의 거리 계산하기 - q = deque() - for i in range(1, N + 1): - if check[i] == 2: - q.append(i) - dist[i] = 0 - else: - dist[i] = -1 - while q: - x = q.popleft() - for y in adj_list[x]: - if dist[y] == -1: - q.append(y) - dist[y] = dist[x] + 1 +import sys +from collections import deque +sys.setrecursionlimit(10**9) + +# DFS를 통해 사이클 찾기 + +def dfs(x, cnt): + # 이미 방문한 노드인데 거리차가 3 이상일 경우 사이클 + if check[x]: + if cnt - dist[x] >= 3: + return x + else: return -1 + check[x] = 1 + dist[x] = cnt + for y in adj_list[x]: + cycleStartNode = dfs(y, cnt + 1) + if cycleStartNode != -1: + check[x] = 2 + if x == cycleStartNode: return -1 + else: return cycleStartNode + return -1 + +if __name__ == '__main__': + N = int(input()) + adj_list = [[] * (N + 1) for _ in range(N + 1)] + # check[i] = 0 : 방문하지 않은 노드 + # check[i] = 1 : 방문한 노드 + # check[i] = 2 : 사이클에 속하는 노드 + check = [0] * (N + 1) + dist = [0] * (N + 1) + + for _ in range(N): + u, v = map(int, sys.stdin.readline().split()) + adj_list[u].append(v) + adj_list[v].append(u) + # 사이클 찾기 + dfs(1, 0) + # BFS를 통해 사이클까지의 거리 계산하기 + q = deque() + for i in range(1, N + 1): + if check[i] == 2: + q.append(i) + dist[i] = 0 + else: + dist[i] = -1 + while q: + x = q.popleft() + for y in adj_list[x]: + if dist[y] == -1: + q.append(y) + dist[y] = dist[x] + 1 print(' '.join(map(str, dist[1:]))) \ No newline at end of file diff --git a/14003LIS.py "b/16947\354\247\200\355\225\230\354\262\2403.py" similarity index 100% rename from 14003LIS.py rename to "16947\354\247\200\355\225\230\354\262\2403.py" diff --git "a/16947\354\247\200\355\225\230\354\262\240_\354\202\254\354\235\264\355\201\264 \353\247\214\353\223\234\353\212\224\353\262\225.py" "b/16947\354\247\200\355\225\230\354\262\240_\354\202\254\354\235\264\355\201\264 \353\247\214\353\223\234\353\212\224\353\262\225.py" deleted file mode 100644 index 7489d68..0000000 --- "a/16947\354\247\200\355\225\230\354\262\240_\354\202\254\354\235\264\355\201\264 \353\247\214\353\223\234\353\212\224\353\262\225.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -N=int(input()) -parent=[0]*(N+1) -ans=[0]*(N+1) -graph=[[] for _ in range(N+1)] -graphSize=[0]*(N+1) - -# 그래프 생성 -for _ in range(N): - a,b=map(int,input().split()) - graph[a].append(b) - graph[b].append(a) - graphSize[a]+=1 - graphSize[b]+=1 - # 이사람은 graphSize라는 연결된 간선의 갯수를 측정해 size가 1인 놈.즉 가장 끝부분에 있는넘들을 삭제해가는 식으로 - # 싸이클을 찾음. 애포에 사이클이 없으면 간선이 1인놈이 있을수밖에없음 그런놈들을 삭제.하면 간선이 2인 사이클들밖에 안남음. - # 그래프사이즈 배열안에 1이 없을때까지 반복. - -while 1 in graphSize: - for i in range(1,N+1): - if graphSize[i]==1: - # 없애면서 노드i의 부모 노드를 기록해둠. - parent[i]=graph[i][0] - graphSize[i]=0 - graphSize[parent[i]]-=1 - graph[parent[i]].remove(i) - -# 부모배열 (사이클 내에 있는 노드들)에대해 전부 검사. 한칸씩 -while any(parent): - for i in range(1,N+1): - # 부모노드가 있으면 들어가 - if parent[i]!=0: - # 부모노드의 부모가 0이면 - if parent[parent[i]]==0: - # 거리+1 - ans[i]=ans[parent[i]]+1 - parent[i]=0 - -for i in range(1,N+1): - print(ans[i],end=' ') \ No newline at end of file diff --git "a/16948 \353\215\260\354\212\244\353\202\230\354\235\264\355\212\270.py" "b/16948 \353\215\260\354\212\244\353\202\230\354\235\264\355\212\270.py" deleted file mode 100644 index faab4d9..0000000 --- "a/16948 \353\215\260\354\212\244\353\202\230\354\235\264\355\212\270.py" +++ /dev/null @@ -1,20 +0,0 @@ -from collections import deque - -def bfs(y, x): - q = deque() - q.append((y, x)) - graph[y][x] = 0 - while q: - y, x = q.popleft() - for dy, dx in d: - Y, X = y+dy, x+dx - if (0 <= Y < N) and (0 <= X < N) and graph[Y][X] == -1: - q.append((Y, X)) - graph[Y][X] = graph[y][x]+1 - -N = int(input()) -sr, sc, er, ec = map(int, input().split()) -graph = [[-1]*(N) for _ in range(N)] -d = [(-2, -1), (-2, 1), (0, -2), (0, 2), (2, -1), (2, 1)] -bfs(sr, sc) -print(graph[er][ec]) \ No newline at end of file diff --git "a/16954 \354\233\200\354\247\201\354\235\264\353\212\224 \353\257\270\353\241\234\355\203\210\354\266\234.py" "b/16954 \354\233\200\354\247\201\354\235\264\353\212\224 \353\257\270\353\241\234\355\203\210\354\266\234.py" deleted file mode 100644 index adcb926..0000000 --- "a/16954 \354\233\200\354\247\201\354\235\264\353\212\224 \353\257\270\353\241\234\355\203\210\354\266\234.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def BFS(start_x,start_y,start_time): - queue = deque() - queue.append((start_x,start_y,start_time)) - while queue: - x, y, turn = queue.popleft() - for dx,dy in move: - nx = x + dx - ny = y + dy - if 0<=nx<8 and 0<=ny<8 and not maze[nx-turn][ny]=='#' and not maze[nx-turn-1][ny]=='#': - if nx-turn < 0: - return 1 - queue.append([nx,ny,turn+1]) - return 0 - - -maze=[list(input().rstrip()) for _ in range(8)] -move = [[0,0],[0,-1],[0,1],[-1,0],[1,0],[-1,-1],[1,-1],[1,1],[-1,1]] -print(BFS(7,0,0)) - diff --git "a/1695\355\216\240\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260.py" "b/1695\355\216\240\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260.py" index b6cfb4e..80126f1 100644 --- "a/1695\355\216\240\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260.py" +++ "b/1695\355\216\240\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260.py" @@ -1,22 +1,22 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10000000) - -N = int(input()) -A = list(map(int,input().split())) - -# 앞에서 오는 포인터. - -# 뒤에서 오는 포인터. -# 땡겻을 때 더 작은걸 반환. - -def palindrome(begin,end): - if begin>end: - return 0 - if A[begin] ==A[end]: - result = palindrome(begin +1,end-1) - else: - result = min(1+palindrome(begin+1, end),1+palindrome(begin,end-1)) - return result; - +import sys +input = sys.stdin.readline +sys.setrecursionlimit(10000000) + +N = int(input()) +A = list(map(int,input().split())) + +# 앞에서 오는 포인터. + +# 뒤에서 오는 포인터. +# 땡겻을 때 더 작은걸 반환. + +def palindrome(begin,end): + if begin>end: + return 0 + if A[begin] ==A[end]: + result = palindrome(begin +1,end-1) + else: + result = min(1+palindrome(begin+1, end),1+palindrome(begin,end-1)) + return result; + print(palindrome(0,N-1)) \ No newline at end of file diff --git "a/16971\353\260\260\354\227\264B\354\235\230 \352\260\222.py" "b/16971\353\260\260\354\227\264B\354\235\230 \352\260\222.py" deleted file mode 100644 index 222ef20..0000000 --- "a/16971\353\260\260\354\227\264B\354\235\230 \352\260\222.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -matrix = [list(map(int,input().split())) for _ in range(N)] -# 1~M-2번 인덱스, 1~N-2번 인덱스의 합이 가장 작은 배열과 가생이에 있는 합이 가장 큰 배열과 교환을 해준다. -# 열검사 -> (1~N-2)*2 + 0 + N-1 의 합을 검사. 가장 작은 열과 가생이에 있는 열 2개의 차이중 큰.. -# 행검사 -total_sum = (sum(matrix[0])*2 - (matrix[0][0]+matrix[0][M-1])) + (sum(matrix[N-1])*2 - (matrix[N-1][0]+matrix[N-1][M-1])) -max_row = max((sum(matrix[0])*2 - (matrix[0][0]+matrix[0][M-1])),(sum(matrix[N-1])*2 - (matrix[N-1][0]+matrix[N-1][M-1]))) -min_row = float('inf') -for i in range(1,N-1): - sum_row = sum(matrix[i])*2 - matrix[i][0] - matrix[i][M-1] - total_sum += sum_row*2 - min_row = min(min_row,sum_row) - -row_change_value = max_row - min_row -# 열검사 -matrix = list(map(list,zip(*matrix))) -N,M = M,N -max_col = max((sum(matrix[0])*2 - (matrix[0][0]+matrix[0][M-1])),(sum(matrix[N-1])*2 - (matrix[N-1][0]+matrix[N-1][M-1]))) -min_col = float('inf') -for i in range(1,N-1): - sum_col = sum(matrix[i]) - min_col = min(min_col,sum_col*2 - matrix[i][0] - matrix[i][M-1]) - -col_change_value = max_col - min_col - -answer = max(total_sum,total_sum+max(row_change_value,col_change_value)) -print(answer) \ No newline at end of file diff --git "a/16973 \354\247\201\354\202\254\352\260\201\355\230\225 \355\203\210\354\266\234.py" "b/16973 \354\247\201\354\202\254\352\260\201\355\230\225 \355\203\210\354\266\234.py" deleted file mode 100644 index 0f42894..0000000 --- "a/16973 \354\247\201\354\202\254\352\260\201\355\230\225 \355\203\210\354\266\234.py" +++ /dev/null @@ -1,44 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def move(x,y): - q = deque() - q.append([x,y,0]) - visited[x][y] = True - while q: - x,y,cnt = q.popleft() - if x==Fr-1 and y==Fc-1: - return cnt - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0<=nx and nx+H-1end: - return - if left<=start and end<=right: - tree[node]+=diff - return - mid=(start+end)//2 - plus(start,mid,left,right,2*node,diff) - plus(mid+1,end,left,right,2*node+1,diff) - -def find(node): - global ans - while node>=1: - ans+=tree[node] - node//=2 - - -n=int(input()) -size=2**ceil(log2(n)) -tree=[0]*(2*size) -for i,j in enumerate(list(map(int,input().split()))): - tree[size+i]=j -m=int(input()) -for i in range(m): - query=list(map(int,input().split())) - if query[0]==1: - plus(1,size,query[1],query[2],1,query[3]) - else: - ans=0 - find(size+query[1]-1) - print(ans) \ No newline at end of file diff --git "a/1697\354\210\250\353\260\224\352\274\255\354\247\210_re.py" "b/1697\354\210\250\353\260\224\352\274\255\354\247\210_re.py" deleted file mode 100644 index 27a038e..0000000 --- "a/1697\354\210\250\353\260\224\352\274\255\354\247\210_re.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def BFS(N,K): - queue=deque() - queue.append(N) - while queue: - cur_node = queue.popleft() - if cur_node==K: - return - # 늘 작은 값부터 조사해야함. 큰값부터 하면 최솟값 비교연산까지 들어가야함. - for next_node in (cur_node-1,cur_node+1,cur_node*2): - if 0<=next_node<=100000 and not time[next_node]: - time[next_node] = time[cur_node] + 1 - queue.append(next_node) - -N,K = map(int,input().split()) -time = [0]*100001 -if K>N: - BFS(N,K) - print(time[K]) -else: - print(N-K) diff --git "a/1697\354\210\250\353\260\224\352\274\255\354\247\210_\352\260\210\353\246\274\352\270\270 \355\203\220\354\203\211(\354\202\254\353\260\251\355\203\220\354\203\211)\354\225\204\354\235\264\353\224\224\354\226\264.py" "b/1697\354\210\250\353\260\224\352\274\255\354\247\210_\352\260\210\353\246\274\352\270\270 \355\203\220\354\203\211(\354\202\254\353\260\251\355\203\220\354\203\211)\354\225\204\354\235\264\353\224\224\354\226\264.py" index 6bef11a..c3eaf8c 100644 --- "a/1697\354\210\250\353\260\224\352\274\255\354\247\210_\352\260\210\353\246\274\352\270\270 \355\203\220\354\203\211(\354\202\254\353\260\251\355\203\220\354\203\211)\354\225\204\354\235\264\353\224\224\354\226\264.py" +++ "b/1697\354\210\250\353\260\224\352\274\255\354\247\210_\352\260\210\353\246\274\352\270\270 \355\203\220\354\203\211(\354\202\254\353\260\251\355\203\220\354\203\211)\354\225\204\354\235\264\353\224\224\354\226\264.py" @@ -1,24 +1,24 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -N,K = map(int,input().split()) -queue = deque() -time = [0] * (100001) - -def BFS(): - queue.append(N) - while queue: - v= queue.popleft() - if v == K: - return time[v] - for next_step in (v-1, v+1, v*2): - if 0 <= next_step < 100001 and not time[next_step]: - time[next_step] = time[v] + 1 - queue.append(next_step) - -if N <= K: - print(BFS()) -else: +import sys +input = sys.stdin.readline +from collections import deque + + +N,K = map(int,input().split()) +queue = deque() +time = [0] * (100001) + +def BFS(): + queue.append(N) + while queue: + v= queue.popleft() + if v == K: + return time[v] + for next_step in (v-1, v+1, v*2): + if 0 <= next_step < 100001 and not time[next_step]: + time[next_step] = time[v] + 1 + queue.append(next_step) + +if N <= K: + print(BFS()) +else: print(N-K) \ No newline at end of file diff --git a/16985Maaaaaaaaze.py b/16985Maaaaaaaaze.py deleted file mode 100644 index f50d958..0000000 --- a/16985Maaaaaaaaze.py +++ /dev/null @@ -1,73 +0,0 @@ -import sys -input = sys.stdin.readline - -# 1. 층 섞기(순열로 모든 경우의 수) -# 2. 층 회전 시키기. -# 3. 층을 순서대로 회전시킨 후 (0,0,0)칸과 (4,4,4)칸이 이동 가능한 칸인지 확인하고 BFS를 시작한다. -# 최단거리가 12이면 바로 종료한다. -from itertools import permutations as perm -from collections import deque -from copy import deepcopy - -def bfs(z, y, x): - if maze[z][y][x] == 0: - return -1 - queue = deque() - queue.append((z, y, x)) - dist = [[[-1] * 5 for _ in range(5)] for _ in range(5)] - dist[z][y][x] = 0 - - while queue: - curr_z, curr_y, curr_x = queue.popleft() - for d in direction: - next_z = curr_z + d[0] - next_y = curr_y + d[1] - next_x = curr_x + d[2] - if 0<=next_z<5 and 0<=next_y<5 and 0<=next_x<5: - if maze[next_z][next_y][next_x] == 1 and dist[next_z][next_y][next_x] == -1: - dist[next_z][next_y][next_x] = dist[curr_z][curr_y][curr_x] + 1 - queue.append((next_z, next_y, next_x)) - return dist[4][4][4] - -def clockwise(a): # 회전 - tmp = a[0][:] - a[0][:] = a[4][0], a[3][0], a[2][0], a[1][0], a[0][0] - a[4][0], a[3][0], a[2][0], a[1][0], a[0][0] = a[4][4::-1] - a[4][4::-1] = a[0][4], a[1][4], a[2][4], a[3][4], a[4][4] - a[0][4], a[1][4], a[2][4], a[3][4], a[4][4] = tmp - - tmp = a[1][1:4] - a[1][1:4] = a[3][1], a[2][1], a[1][1] - a[3][1], a[2][1], a[1][1] = a[3][3:0:-1] - a[3][3:0:-1] = a[1][3], a[2][3], a[3][3] - a[1][3], a[2][3], a[3][3] = tmp - -MAZE = [[list(map(int, input().split())) for _ in range(5)] for _ in range(5)] -direction = ((-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)) -block_perm = list(perm(list(range(5)))) # 순열 생성. -answer = -1 - -while block_perm: - bp = block_perm.pop(0) - - maze = [] - for b in bp: - maze.append(deepcopy(MAZE[b])) # 생성한 순열 순서대로 블럭을 쌓아준다. - - # 블럭을 밑에서부터 1번씩 회전시키면서 최단경로 탐색하기 - for _ in range(4): - for _ in range(4): - for _ in range(4): - for _ in range(4): - for _ in range(4): - cnt = bfs(0,0,0) - if cnt != -1: - if answer == -1 or cnt < answer: - answer = cnt - clockwise(maze[4]) - clockwise(maze[3]) - clockwise(maze[2]) - clockwise(maze[1]) - clockwise(maze[0]) - -print(answer) diff --git "a/16986\354\235\270\354\213\270\353\223\244\354\235\230 \352\260\200\354\234\204\353\260\224\354\234\204\353\263\264.py" "b/16986\354\235\270\354\213\270\353\223\244\354\235\230 \352\260\200\354\234\204\353\260\224\354\234\204\353\263\264.py" deleted file mode 100644 index 84f5de8..0000000 --- "a/16986\354\235\270\354\213\270\353\223\244\354\235\230 \352\260\200\354\234\204\353\260\224\354\234\204\353\263\264.py" +++ /dev/null @@ -1,49 +0,0 @@ -import sys -from itertools import permutations - -# 다음엔 꼭 구현하는걸로. - -def DFS(pi1,pi2,index,win,player): - global result - # 지우 승 - if win[0] == K: - result = 1 - return - # 경희 민호 승 - if win[1] == K or win[2] == K: - return - if index[0] == N: - return - #다음 차례 상대방을 구할 경우, 지우, 경희, 민호를 각각 0,1,2라고 했을 때 - #총 합(3)에서 출전 했던 선수의 합을 빼면 다음 차례에 나올 선수의 번호가 나옴 - pi3 = 3 - (pi1+pi2) - # 각 플레이어가 이번에 낼 손동작 - pv1 = player[pi1][index[pi1]] - 1 - pv2 = player[pi2][index[pi2]] - 1 - # 다음번 낼 손동작 idx 하나 늘려줌.(다음 턴) - index[pi1] += 1 - index[pi2] += 1 - if game_rule[pv1][pv2] == 2 or (game_rule[pv1][pv2] == 1 and pi1 > pi2) : #pi1이 이겼을 경우 - win[pi1] += 1 - DFS(pi1, pi3, index, win,player) - elif (game_rule[pv1][pv2] == 1 and pi1 < pi2) or game_rule[pv1][pv2] == 0: #pi2가 이겼을 경우 - win[pi2] += 1 - DFS(pi2, pi3, index, win,player) - -N,K = map(int,sys.stdin.readline().split()) -game_rule = [list(map(int,sys.stdin.readline().split())) for _ in range(N)] -gyung_hee = list(map(int,sys.stdin.readline().split()))#경희 -min_ho = list(map(int,sys.stdin.readline().split()))#민호 -target = [i+1 for i in range(N)] # 지우가 낼 경우의 수. - -for jiwoo in permutations(target,N):#지우가 N개를 뽑는 순열(내는 순서가 바뀌는 모든 경우의 수.) - player = [jiwoo,gyung_hee,min_ho] # 각자 3명이 1회부터 N회까지 내는 가위바위보의 패턴. - index = [0,0,0] #지우, 경희, 민호가 다음 번에 낼 손동작 index - win = [0,0,0] #지우, 경희, 민호 이긴 횟수 - result = 0 - DFS(0,1,index,win,player) - if result == 1: - print(1) - break -else: - print(0) \ No newline at end of file diff --git a/16988Baaaaaaaaduk2.py b/16988Baaaaaaaaduk2.py deleted file mode 100644 index e65ff8b..0000000 --- a/16988Baaaaaaaaduk2.py +++ /dev/null @@ -1,60 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from itertools import combinations - -def BFS(x,y,visited): - queue = deque() - visited[x][y] = True - queue.append([x,y]) - kill_ai_stone = 1 - flag = 0 - while queue: - x,y = queue.popleft() - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0 <= nx < N and 0 <= ny < M and not visited[nx][ny]: - if baduk_board[nx][ny] == 0: - flag = 1 - elif baduk_board[nx][ny] == 2: - visited[nx][ny] = True - kill_ai_stone += 1 - queue.append([nx,ny]) - return kill_ai_stone if not flag else -1 - - -def play_game(put_stone): - visited = [[False]*M for _ in range(N)] - kill_count = 0 - for x,y in put_stone: - baduk_board[x][y] = 1 - for i in range(N): - for j in range(M): - if baduk_board[i][j]==2 and not visited[i][j]: - cnt = BFS(i,j,visited) - if cnt != -1: - kill_count += cnt - for x,y in put_stone: - baduk_board[x][y] = 0 - return kill_count - - -N, M = map(int,input().split()) -baduk_board = [] -dx = [0,0,-1,1] -dy = [-1,1,0,0] - -pos = [] -for i in range(N): - row = list(map(int,input().split())) - baduk_board.append(row) - for j in range(M): - num = row[j] - if not num: - pos.append((i,j)) - -max_kill_cnt = 0 -for my_turn in combinations(pos,2): - max_kill_cnt = max(max_kill_cnt,play_game(my_turn)) -print(max_kill_cnt) \ No newline at end of file diff --git "a/16991\354\231\270\355\214\220\354\233\220\354\210\234\355\232\2143.py" "b/16991\354\231\270\355\214\220\354\233\220\354\210\234\355\232\2143.py" deleted file mode 100644 index aaa1b60..0000000 --- "a/16991\354\231\270\355\214\220\354\233\220\354\210\234\355\232\2143.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline - -def find(now,before): - if dp[now][before]: - return dp[now][before] - if before == (1<0: - return dists[now][0] - else: - return float('inf') - cost = float('inf') - for i in range(1,N): - if not (before>>i)%2 and dists[now][i]: - tmp = find(i,before|(1< i: - break - s.append(dp[i - j]) - dp[i] = min(s) + 1 +n = int(input()) +dp = [0] * (n+1) +square = [i * i for i in range(1, 317)] + +for i in range(1, n + 1): + s = [] + for j in square: + if j > i: + break + s.append(dp[i - j]) + dp[i] = min(s) + 1 print(dp[n]) \ No newline at end of file diff --git a/1700_concent_practice more.py b/1700_concent_practice more.py deleted file mode 100644 index a35512e..0000000 --- a/1700_concent_practice more.py +++ /dev/null @@ -1,11 +0,0 @@ - - -N , K= map(int,input().split()) -number = list(input()) -number = list(map(int,number)) - -for _ in range(K): - number.pop(number.index(min(number))) - -number = list(map(str,number)) -print(''.join(number)) \ No newline at end of file diff --git "a/17069 \355\214\214\354\235\264\355\224\204\354\230\256\352\270\260\352\270\2602.py" "b/17069 \355\214\214\354\235\264\355\224\204\354\230\256\352\270\260\352\270\2602.py" deleted file mode 100644 index 3979358..0000000 --- "a/17069 \355\214\214\354\235\264\355\224\204\354\230\256\352\270\260\352\270\2602.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -house = [list(map(int, input().split())) for _ in range(N)] -# 오른쪽에서 오거나 왼쪽에서 오거나 대각선으로 오는 경우의 dp -dp = [[[0,0,0] for _ in range(N)] for _ in range(N)] -for i in range(N): - if house[0][i]: - break - dp[0][i][0] = 1 -for i in range(1,N): - for j in range(2,N): - if not house[i][j]: - dp[i][j][0] = dp[i][j-1][0] + dp[i][j-1][1] - if not house[i-1][j] and not house[i][j-1]: - dp[i][j][1] = sum(dp[i-1][j-1]) - dp[i][j][2] = dp[i-1][j][1] + dp[i-1][j][2] -print(sum(dp[N-1][N-1])) \ No newline at end of file diff --git "a/17070 \355\214\214\354\235\264\355\224\204 \354\230\256\352\270\260\352\270\2601.py" "b/17070 \355\214\214\354\235\264\355\224\204 \354\230\256\352\270\260\352\270\2601.py" deleted file mode 100644 index 61d3b81..0000000 --- "a/17070 \355\214\214\354\235\264\355\224\204 \354\230\256\352\270\260\352\270\2601.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -house = [list(map(int, input().split())) for _ in range(N)] -# 오른쪽에서 오거나 왼쪽에서 오거나 대각선으로 오는 경우의 dp -dp = [[[0,0,0] for _ in range(N)] for _ in range(N)] -for i in range(N): - if house[0][i]: - break - dp[0][i][0] = 1 -for i in range(1,N): - for j in range(2,N): - if not house[i][j]: - dp[i][j][0] = dp[i][j-1][0] + dp[i][j-1][1] - if not house[i-1][j] and not house[i][j-1]: - dp[i][j][1] = sum(dp[i-1][j-1]) - dp[i][j][2] = dp[i-1][j][1] + dp[i-1][j][2] -print(sum(dp[N-1][N-1])) diff --git "a/17071\354\210\250\353\260\224\352\274\255\354\247\2105.py" "b/17071\354\210\250\353\260\224\352\274\255\354\247\2105.py" deleted file mode 100644 index f1ac949..0000000 --- "a/17071\354\210\250\353\260\224\352\274\255\354\247\2105.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def BFS(N,K): - odd_even_visited = [[False]*500001 for _ in range(2)] - queue = deque() - queue.append([N,K,0,0]) - cur_sister = K - odd_even_visited[0][N] = True - while queue: - cur_node,cur_sister,cur_time,cur_flag = queue.popleft() - if cur_sister > 500000: - print(-1) - exit() - # 중복 체크가 불가능한 BFS(target이 움직여서 방문한곳 또 들러야함)는 순환구간을 찾아 check하면 됨. - # +1, -1 구간에 동생이 오면 걸림. - if odd_even_visited[cur_flag][cur_sister]: - print(cur_time) - exit() - new_flag = cur_flag^ 1 - for next_node in (cur_node-1,cur_node+1,cur_node*2): - if 0<=next_node<=500000 and not odd_even_visited[new_flag][next_node]: - next_time = cur_time + 1 - next_sister = cur_sister + next_time - odd_even_visited[new_flag][next_node] = True - queue.append([next_node,next_sister,next_time,new_flag]) - - -N,K = map(int,input().split()) -BFS(N,K) diff --git "a/17073 \353\202\230\353\254\264 \354\234\204\354\235\230 \353\271\227\353\254\274.py" "b/17073 \353\202\230\353\254\264 \354\234\204\354\235\230 \353\271\227\353\254\274.py" deleted file mode 100644 index 9fd300b..0000000 --- "a/17073 \353\202\230\353\254\264 \354\234\204\354\235\230 \353\271\227\353\254\274.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**6) - -def dfs(cur_node, water): - visited[cur_node] = True - n = len(tree[cur_node])-1 - if not n: - ans.append(water) - return - unit = water/n - for next_node in tree[cur_node]: - if not visited[next_node]: - dfs(next_node,unit) - - -N, W = map(int, input().split()) -tree = {i: [] for i in range(1, N+1)} -visited = {i: False for i in range(1, N+1)} -ans = [] -for _ in range(N-1): - U, V = map(int, input().split()) - tree[U] += [V] - tree[V] += [U] -visited[1] = True -for next_node in tree[1]: - dfs(next_node, W/len(tree[1])) -print(sum(ans)/len(ans)) -# 리프노드들에 고인 물의 평균. 노드수 50만. \ No newline at end of file diff --git "a/1707\354\235\264\353\266\204_\352\267\270\353\236\230\355\224\204.py" "b/1707\354\235\264\353\266\204_\352\267\270\353\236\230\355\224\204.py" index 25e36d2..0f06491 100644 --- "a/1707\354\235\264\353\266\204_\352\267\270\353\236\230\355\224\204.py" +++ "b/1707\354\235\264\353\266\204_\352\267\270\353\236\230\355\224\204.py" @@ -1,46 +1,46 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict -from collections import deque - - -def BFS(v): - queue.append(v) - check[v] = 1 - while queue: - v = queue.popleft() - for i in graph[v]: - if check[i] ==0: - if check[v]==1: - check[i]= -1 - else: - check[i] = 1 - queue.append(i) - - - -for test in range(int(input())): - V,E = map(int,input().split()) - graph = defaultdict(list) - queue = deque() - check = [0]*(V+1) - ans = 0 - - for _ in range(E): - a,b = map(int,input().split()) - graph[a] +=[b] - graph[b] +=[a] - - for i in range(1,V+1): - if check[i] ==0: - BFS(i) - - for i in range(1,V+1): - for adj in graph[i]: - if check[i]==check[adj]: - ans = 1 - - if ans==0: - print("YES") - else: +import sys +input = sys.stdin.readline +from collections import defaultdict +from collections import deque + + +def BFS(v): + queue.append(v) + check[v] = 1 + while queue: + v = queue.popleft() + for i in graph[v]: + if check[i] ==0: + if check[v]==1: + check[i]= -1 + else: + check[i] = 1 + queue.append(i) + + + +for test in range(int(input())): + V,E = map(int,input().split()) + graph = defaultdict(list) + queue = deque() + check = [0]*(V+1) + ans = 0 + + for _ in range(E): + a,b = map(int,input().split()) + graph[a] +=[b] + graph[b] +=[a] + + for i in range(1,V+1): + if check[i] ==0: + BFS(i) + + for i in range(1,V+1): + for adj in graph[i]: + if check[i]==check[adj]: + ans = 1 + + if ans==0: + print("YES") + else: print("NO") \ No newline at end of file diff --git "a/17087\354\210\250\353\260\224\352\274\255\354\247\2106.py" "b/17087\354\210\250\353\260\224\352\274\255\354\247\2106.py" index 1afaa19..829e4ae 100644 --- "a/17087\354\210\250\353\260\224\352\274\255\354\247\2106.py" +++ "b/17087\354\210\250\353\260\224\352\274\255\354\247\2106.py" @@ -1,24 +1,24 @@ -def GCD(i,j): - a, b = i,j - - - while b != 0: - a = a % b - a, b = b, a - return a - -N,S = map(int,input().split()) -A = list(map(int, input().split())) - -for i in range(N): - if A[i]>=S: - A[i] = A[i]-S - else: - A[i] = S-A[i] - -init_GCD = A[0] - -for i in range(1,N): - init_GCD = GCD(init_GCD,A[i]) - +def GCD(i,j): + a, b = i,j + + + while b != 0: + a = a % b + a, b = b, a + return a + +N,S = map(int,input().split()) +A = list(map(int, input().split())) + +for i in range(N): + if A[i]>=S: + A[i] = A[i]-S + else: + A[i] = S-A[i] + +init_GCD = A[0] + +for i in range(1,N): + init_GCD = GCD(init_GCD,A[i]) + print(init_GCD) \ No newline at end of file diff --git "a/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\213\234\352\260\204\354\264\210\352\263\274.py" "b/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\213\234\352\260\204\354\264\210\352\263\274.py" index 2d51d5c..0716b5a 100644 --- "a/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\213\234\352\260\204\354\264\210\352\263\274.py" +++ "b/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\213\234\352\260\204\354\264\210\352\263\274.py" @@ -1,25 +1,20 @@ -import sys -input = sys.stdin.readline - -def isPrime(num): - if num==1: - return False - else: - for i in range(2, int(num**0.5)+1): - if num%i == 0: - return False - return True - -T = int(input()) - -for test in range(T): - N = int(input()) - if N==0: - break - else: - cnt=0 - for i in range(1, int(N/2)+1): - if isPrime(i) and isPrime(N-i): - cnt+=1 - print(cnt) +import sys +input = sys.stdin.readline + +def isPrime(num): + for i in range(2, int(num**0.5)+1): + if num%i == 0: + return False + return True + +T = int(input()) + + +for test in range(T): + N = int(input()) + cnt = 0 + for i in range(2, int(N/2)+1): + if isPrime(i) and isPrime(N-i): + cnt+=1 + print(cnt) \ No newline at end of file diff --git "a/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\260\270\352\263\240\354\275\224\353\223\234.py" "b/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\260\270\352\263\240\354\275\224\353\223\234.py" index 25d7c10..d1fd5a3 100644 --- "a/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\260\270\352\263\240\354\275\224\353\223\234.py" +++ "b/17103\352\263\250\353\223\234\353\260\224\355\235\220\355\214\214\355\213\260\354\205\230_\354\260\270\352\263\240\354\275\224\353\223\234.py" @@ -1,23 +1,23 @@ -prime_arr = [] - -# sieve = 체 -sieve = [False, False] + ([True] * (1000000 - 1)) -for i in range(2, 1000001): - if sieve[i]: - prime_arr.append(i) - for j in range(i * 2, 1000001, i): - sieve[j] = False - -ans = [] -for tc in range(int(input())): - - N = int(input()) - cnt = 0 - for i in range(len(prime_arr)): - if prime_arr[i] > N - prime_arr[i]: - break - if sieve[N - prime_arr[i]]: - cnt += 1 - ans.append(cnt) - +prime_arr = [] + +# sieve = 체 +sieve = [False, False] + ([True] * (1000000 - 1)) +for i in range(2, 1000001): + if sieve[i]: + prime_arr.append(i) + for j in range(i * 2, 1000001, i): + sieve[j] = False + +ans = [] +for tc in range(int(input())): + + N = int(input()) + cnt = 0 + for i in range(len(prime_arr)): + if prime_arr[i] > N - prime_arr[i]: + break + if sieve[N - prime_arr[i]]: + cnt += 1 + ans.append(cnt) + print(*ans, sep='\n') \ No newline at end of file diff --git "a/17123\353\260\260\354\227\264\353\206\200\354\235\264.py" "b/17123\353\260\260\354\227\264\353\206\200\354\235\264.py" index f86e5fb..f145501 100644 --- "a/17123\353\260\260\354\227\264\353\206\200\354\235\264.py" +++ "b/17123\353\260\260\354\227\264\353\206\200\354\235\264.py" @@ -1,23 +1,23 @@ -import sys -input = sys.stdin.readline - -T = int(input()) - -for test in range(T): - N,M = map(int,input().split()) - matrix = [list(map(int,input().split())) for _ in range(N)] - - - for _ in range(M): - r1,c1,r2,c2,v = map(int,input().split()) - for i in range(r1-1,r2): - for j in range(c1-1,c2): - matrix[i][j] +=v - - - for i in range(N): - print(sum(matrix[i]), end=" ") - print() - for j in range(N): - print(sum(matrix[m][j] for m in range(N)), end=" ") +import sys +input = sys.stdin.readline + +T = int(input()) + +for test in range(T): + N,M = map(int,input().split()) + matrix = [list(map(int,input().split())) for _ in range(N)] + + + for _ in range(M): + r1,c1,r2,c2,v = map(int,input().split()) + for i in range(r1-1,r2): + for j in range(c1-1,c2): + matrix[i][j] +=v + + + for i in range(N): + print(sum(matrix[i]), end=" ") + print() + for j in range(N): + print(sum(matrix[m][j] for m in range(N)), end=" ") print() \ No newline at end of file diff --git "a/17123\353\260\260\354\227\264\353\206\200\354\235\264_2\354\260\250\354\213\234.py" "b/17123\353\260\260\354\227\264\353\206\200\354\235\264_2\354\260\250\354\213\234.py" index 389d67e..a7de931 100644 --- "a/17123\353\260\260\354\227\264\353\206\200\354\235\264_2\354\260\250\354\213\234.py" +++ "b/17123\353\260\260\354\227\264\353\206\200\354\235\264_2\354\260\250\354\213\234.py" @@ -1,24 +1,24 @@ -import sys -input = sys.stdin.readline - - - -for test in range(int(input())): - N,M = map(int,input().split()) - matrix = [list(map(int,input().split())) for _ in range(N)] - ans = [[] for _ in range(2)] - for i in range(N): - ans[0].append(sum(matrix[i])) - for i in range(N): - ans[1].append(sum(matrix[m][i] for m in range(N))) - for _ in range(M): - r1,c1,r2,c2,v = map(int,input().split()) - # c1~c2행까지 (r2-r1)*v만큼 증가. - for i in range(r1-1,r2): - ans[0][i] += (c2-c1+1)*v - # r1~r2열까지 (c2-c1)*v만큼 증가. - for i in range(c1-1,c2): - ans[1][i] += (r2-r1+1)*v - - for i in range(2): +import sys +input = sys.stdin.readline + + + +for test in range(int(input())): + N,M = map(int,input().split()) + matrix = [list(map(int,input().split())) for _ in range(N)] + ans = [[] for _ in range(2)] + for i in range(N): + ans[0].append(sum(matrix[i])) + for i in range(N): + ans[1].append(sum(matrix[m][i] for m in range(N))) + for _ in range(M): + r1,c1,r2,c2,v = map(int,input().split()) + # c1~c2행까지 (r2-r1)*v만큼 증가. + for i in range(r1-1,r2): + ans[0][i] += (c2-c1+1)*v + # r1~r2열까지 (c2-c1)*v만큼 증가. + for i in range(c1-1,c2): + ans[1][i] += (r2-r1+1)*v + + for i in range(2): print(*ans[i]) \ No newline at end of file diff --git "a/17128\354\206\214\352\260\200 \354\240\225\353\263\264\354\204\254\354\227\220 \354\230\254\353\235\274\354\230\250\354\235\264\354\234\240.py" "b/17128\354\206\214\352\260\200 \354\240\225\353\263\264\354\204\254\354\227\220 \354\230\254\353\235\274\354\230\250\354\235\264\354\234\240.py" deleted file mode 100644 index 760450b..0000000 --- "a/17128\354\206\214\352\260\200 \354\240\225\353\263\264\354\204\254\354\227\220 \354\230\254\353\235\274\354\230\250\354\235\264\354\234\240.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -# 소 N마리 -N,Q = map(int,input().split()) -A = list(map(int,input().split())) -dp = [0]*N -# 미리계산. -for i in range(N): - dp[i] = A[i]*A[i-1]*A[i-2]*A[i-3] - -Qs = list(map(int,input().split())) -# 미리계산 -ex_sum = sum(dp) -for idx in Qs: - for i in range(4): - new_idx = (idx-1+i)%N - dp[new_idx] = -dp[new_idx] - ex_sum+=2*dp[new_idx] - print(ex_sum) \ No newline at end of file diff --git "a/17129 \354\234\214\353\246\254\354\225\224\354\212\250\354\210\230\354\225\241\353\271\250\354\235\264\353\224\261\353\224\260\352\265\254\353\246\254\352\260\200 \354\240\225\353\263\264\354\204\254\354\227\220 \354\230\254\353\235\274\354\230\250 \354\235\264\354\234\240.py" "b/17129 \354\234\214\353\246\254\354\225\224\354\212\250\354\210\230\354\225\241\353\271\250\354\235\264\353\224\261\353\224\260\352\265\254\353\246\254\352\260\200 \354\240\225\353\263\264\354\204\254\354\227\220 \354\230\254\353\235\274\354\230\250 \354\235\264\354\234\240.py" deleted file mode 100644 index 6e4f387..0000000 --- "a/17129 \354\234\214\353\246\254\354\225\224\354\212\250\354\210\230\354\225\241\353\271\250\354\235\264\353\224\261\353\224\260\352\265\254\353\246\254\352\260\200 \354\240\225\353\263\264\354\204\254\354\227\220 \354\230\254\353\235\274\354\230\250 \354\235\264\354\234\240.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(i,j): - q = deque() - q.append((i,j)) - visited[i][j] = 1 - while q: - x, y = q.popleft() - for d in delta: - nx, ny = x + d[0], y + d[1] - if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny] and not island[nx][ny]=='1': - visited[nx][ny] = visited[x][y] + 1 - q.append((nx,ny)) - if island[nx][ny] in goal: - print('TAK') - print(visited[x][y]) - exit() - print('NIE') - exit() - - -n, m = map(int, input().split()) -island = [list(input().rstrip()) for _ in range(n)] -visited = [[0]*m for _ in range(n)] -delta = ((1,0),(0,1),(-1,0),(0,-1)) -goal = {'3', '4', '5'} -for i in range(n): - for j in range(m): - if island[i][j]=='2': - bfs(i,j) - \ No newline at end of file diff --git "a/17135\354\272\220\354\212\254\353\224\224\355\216\234\354\212\244.py" "b/17135\354\272\220\354\212\254\353\224\224\355\216\234\354\212\244.py" deleted file mode 100644 index 5844244..0000000 --- "a/17135\354\272\220\354\212\254\353\224\224\355\216\234\354\212\244.py" +++ /dev/null @@ -1,59 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from heapq import heappush - - -def search_target(x, y): - if enemies[x][y]: return (x, y) - q = deque() - q.append((x, y)) - visited = [[False] * M for __ in range(N)] - visited[x][y] = True - target_candidate = [] - for __ in range(D - 1): - for __ in range(len(q)): - x, y = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < M and not visited[nx][ny]: - if enemies[nx][ny]: - heappush(target_candidate, (ny, nx)) - visited[nx][ny] = True - q.append((nx, ny)) - if target_candidate: - y, x = target_candidate[0] - return (x, y) - return 0 - - -def start_game(archers): - deaths = set() - for row in range(N - 1, -1, -1): - death = set() - for archer in archers: - kill = search_target(row, archer) - if kill: - deaths.add(kill) - death.add(kill) - for x, y in death: - enemies[x][y] = 0 - for x, y in deaths: - enemies[x][y] = 1 - return len(deaths) - - -N, M, D = map(int, input().split()) -enemies = [list(map(int, input().split())) for __ in range(N)] - -archer_combs = [] -for i in range(M - 2): - for j in range(i + 1, M - 1): - for k in range(j + 1, M): - archer_combs.append((i, j, k)) - -delta = ((0, -1), (-1, 0), (0, 1)) -max_kill_cnt = 0 -for archer_set in archer_combs: - max_kill_cnt = max(max_kill_cnt, start_game(archer_set)) -print(max_kill_cnt) \ No newline at end of file diff --git "a/1713\355\233\204\353\263\264 \354\266\224\354\262\234\355\225\230\352\270\260.py" "b/1713\355\233\204\353\263\264 \354\266\224\354\262\234\355\225\230\352\270\260.py" deleted file mode 100644 index 1f4f120..0000000 --- "a/1713\355\233\204\353\263\264 \354\266\224\354\262\234\355\225\230\352\270\260.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -N = int(input()) -n = int(input()) -nums = list(map(int, input().split())) -count = defaultdict(int) -for i in range(n): - count[nums[i]] += 1 - if len(count) > N: - min_val = float('inf') - for candidate in count: - if candidate == nums[i]: - continue - if count[candidate] < min_val: - min_val = count[candidate] - target = candidate - del count[target] -answer = [] -for candidate in count: - answer.append(candidate) -print(*sorted(answer)) \ No newline at end of file diff --git "a/17140 \354\235\264\354\260\250\354\233\220 \353\260\260\354\227\264\352\263\274 \354\227\260\354\202\260.py" "b/17140 \354\235\264\354\260\250\354\233\220 \353\260\260\354\227\264\352\263\274 \354\227\260\354\202\260.py" deleted file mode 100644 index c96b6c0..0000000 --- "a/17140 \354\235\264\354\260\250\354\233\220 \353\260\260\354\227\264\352\263\274 \354\227\260\354\202\260.py" +++ /dev/null @@ -1,44 +0,0 @@ -from collections import Counter - -def rc(): - max_len = 0 - len_s = len(s) - for j in range(len_s): - a = [i for i in s[j] if i != 0] - a = Counter(a).most_common() - # 갯수기준, 수기준 정렬 - a.sort(key = lambda x : (x[1], x[0])) - # 그 행 비우고 새 원소로 넣어줌. - s[j] = [] - for fi, se in a: - s[j].append(fi) - s[j].append(se) - len_a = len(a) - # 최대 길이 체크(가장 큰 열 기준 모든 열의 크기 변함) - if max_len < len_a * 2: - max_len = len_a * 2 - # 빈칸에 0 채워줌. - for j in range(len_s): - for _ in range(max_len - len(s[j])): - s[j].append(0) - # 100개 넘어가면 그냥 자름. - s[j] = s[j][:100] - - -r, c, k = map(int, input().split()) -s = [list(map(int, input().split())) for i in range(3)] -for i in range(101): - try: - if s[r - 1][c - 1] == k: - print(i) - break - except: - pass - if len(s) < len(s[0]): - s = list(zip(*s)) - rc() - s = list(zip(*s)) - else: - rc() -else: - print(-1) \ No newline at end of file diff --git "a/17141 \354\227\260\352\265\254\354\206\2142.py" "b/17141 \354\227\260\352\265\254\354\206\2142.py" deleted file mode 100644 index 612b0c8..0000000 --- "a/17141 \354\227\260\352\265\254\354\206\2142.py" +++ /dev/null @@ -1,52 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from itertools import combinations - - -def bfs(q): - visited = [[False] * N for _ in range(N)] - for x, y in q: - visited[x][y] = True - time = -1 - cnt = len(q) - while q: - for _ in range(len(q)): - x, y = q.popleft() - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - if 0 <= nx < N and 0 <= ny < N and not visited[nx][ny] and not matrix[nx][ny] == 1: - visited[nx][ny] = True - q.append((nx, ny)) - cnt += 1 - time += 1 - return cnt, time - -dx = [0, 0, -1, 1] -dy = [1, -1, 0, 0] - -N, M = map(int, input().split()) -matrix = [] -# 모든 빈칸에 바이러스가 있게되는 최소 시간. -initial_points = [] -wall = 0 -for i in range(N): - a = list(map(int, input().split())) - for j in range(N): - if a[j] == 2: - initial_points.append((i,j)) - elif a[j] == 1: - wall += 1 - matrix.append(a) - -min_count = float('inf') -for virus_set in combinations(initial_points, M): - q = deque() - for virus in virus_set: - q.append(virus) - cnt, time = bfs(q) - if cnt + wall == N**2: - min_count = min(min_count, time) -if min_count == float('inf'): - min_count = -1 -print(min_count) diff --git "a/17142 \354\227\260\352\265\254\354\206\2143.py" "b/17142 \354\227\260\352\265\254\354\206\2143.py" deleted file mode 100644 index 3a95d4c..0000000 --- "a/17142 \354\227\260\352\265\254\354\206\2143.py" +++ /dev/null @@ -1,58 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from itertools import combinations - - -def bfs(q): - for x, y in q: - visited[x][y] = True - times[x][y] = 0 - cnt = len(q) - while q: - for _ in range(len(q)): - x, y = q.popleft() - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - if 0 <= nx < N and 0 <= ny < N and not visited[nx][ny] and not matrix[nx][ny] == 1: - visited[nx][ny] = True - q.append((nx, ny)) - times[nx][ny] = times[x][y] + 1 - cnt += 1 - return cnt - -dx = [0, 0, -1, 1] -dy = [1, -1, 0, 0] - -N, M = map(int, input().split()) -matrix = [] -# 모든 빈칸에 바이러스가 있게되는 최소 시간. -initial_points = [] -wall = 0 -for i in range(N): - a = list(map(int, input().split())) - for j in range(N): - if a[j] == 2: - initial_points.append((i,j)) - elif a[j] == 1: - wall += 1 - matrix.append(a) - -min_count = float('inf') -for virus_set in combinations(initial_points, M): - q = deque() - visited = [[False] * N for _ in range(N)] - times = [[-1] * N for _ in range(N)] - for virus in virus_set: - q.append(virus) - cnt = bfs(q) - max_time = 0 - for i in range(N): - for j in range(N): - if not matrix[i][j]: - max_time = max(max_time, times[i][j]) - if cnt + wall == N**2: - min_count = min(min_count, max_time) -if min_count == float('inf'): - min_count = -1 -print(min_count) \ No newline at end of file diff --git "a/17144 \353\257\270\354\204\270\353\250\274\354\247\200 \354\225\210\353\205\225.py" "b/17144 \353\257\270\354\204\270\353\250\274\354\247\200 \354\225\210\353\205\225.py" deleted file mode 100644 index 606e760..0000000 --- "a/17144 \353\257\270\354\204\270\353\250\274\354\247\200 \354\225\210\353\205\225.py" +++ /dev/null @@ -1,102 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def rotate_dust(): - up_cycle = deque() - down_cycle = deque() - up_cycle_down, down_cycle_up = air_clear[0][0], air_clear[1][0] - - # 0, 공기청정기 x 작은 좌표, 좌, 우 -> rotate(-1) - for i in range(C): - up_cycle.append(matrix[0][i]) - for i in range(1, up_cycle_down): - up_cycle.append(matrix[i][C-1]) - for i in range(C-1, -1, -1): - up_cycle.append(matrix[up_cycle_down][i]) - for i in range(up_cycle_down-1, 0, -1): - up_cycle.append(matrix[i][0]) - up_cycle.rotate(-1) - for i in range(C): - matrix[0][i] = up_cycle.popleft() - for i in range(1, up_cycle_down): - matrix[i][C-1] = up_cycle.popleft() - for i in range(C-1, -1, -1): - matrix[up_cycle_down][i] = up_cycle.popleft() - for i in range(up_cycle_down-1, 0, -1): - matrix[i][0] = up_cycle.popleft() - matrix[air_clear[0][0]][air_clear[0][1]] = 0 - - # R, 공기청정기 x 큰 좌표, 좌, 우 -> rotate(1) - for i in range(C): - down_cycle.append(matrix[down_cycle_up][i]) - for i in range(down_cycle_up + 1, R): - down_cycle.append(matrix[i][C-1]) - for i in range(C-2, -1, -1): - down_cycle.append(matrix[R-1][i]) - for i in range(R - 2, down_cycle_up, -1): - down_cycle.append(matrix[i][0]) - down_cycle.rotate(1) - for i in range(C): - matrix[down_cycle_up][i] = down_cycle.popleft() - for i in range(down_cycle_up + 1, R): - matrix[i][C-1] = down_cycle.popleft() - for i in range(C-2, -1, -1): - matrix[R-1][i] = down_cycle.popleft() - for i in range(R - 2, down_cycle_up, -1): - matrix[i][0] = down_cycle.popleft() - matrix[air_clear[1][0]][air_clear[1][1]] = 0 - - - -def spread_dust(dusts): - new_dusts = [] - - for dust in dusts: - x, y = dust - init_dust = matrix[x][y] - cnt = 0 - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < R and 0 <= ny < C and not (nx, ny) in air_clear: - new_dusts.append((nx, ny, init_dust//5)) - cnt += 1 - new_dusts.append((x, y, init_dust - cnt * (init_dust//5))) - matrix[x][y] = 0 - - for dust in new_dusts: - x, y, a = dust - matrix[x][y] += a - - -delta = ((0, -1), (1, 0), (-1, 0), (0, 1)) - -R, C, T = map(int, input().split()) -matrix = [] -air_clear = [] -dusts = [] -for i in range(R): - row = list(map(int, input().split())) - for j in range(C): - if row[j] == -1: - air_clear.append((i,j)) - row[j] = 0 - elif row[j]: - dusts.append((i,j)) - matrix.append(row) - -for __ in range(T): - # 1. 미세먼지 확산. - spread_dust(dusts) - # 2. 공기청정기 작동. 원 2개 순환. - rotate_dust() - - answer = 0 - dusts = [] - for i in range(R): - for j in range(C): - if matrix[i][j]: - dusts.append((i,j)) - answer += matrix[i][j] -print(answer) \ No newline at end of file diff --git "a/17179\354\274\200\354\235\264\355\201\254 \354\236\220\353\245\264\352\270\260.py" "b/17179\354\274\200\354\235\264\355\201\254 \354\236\220\353\245\264\352\270\260.py" deleted file mode 100644 index a10608c..0000000 --- "a/17179\354\274\200\354\235\264\355\201\254 \354\236\220\353\245\264\352\270\260.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def is_minimum(mini): - left = 0 - cnt = 0 - for right in cut_points: - if right - left >= mini: - left = right - cnt += 1 - if cnt > k: - return True - return False - - -N, M, L = map(int, input().split()) -cut_points = [int(input()) for _ in range(M)] + [L] - -for _ in range(N): - k = int(input()) - # M개의 지점 중 k개 선택. 사잇값의 최솟값이 가장 큰. - left = 1 - right = 4000000 - answer = 0 - while left <= right: - mid = (left + right) // 2 - if is_minimum(mid): - left = mid + 1 - answer = max(mid,answer) - else: - right = mid - 1 - print(answer) \ No newline at end of file diff --git "a/1717\354\247\221\355\225\251\354\235\230\355\221\234\355\230\204.py" "b/1717\354\247\221\355\225\251\354\235\230\355\221\234\355\230\204.py" index ede97e8..d234e9b 100644 --- "a/1717\354\247\221\355\225\251\354\235\230\355\221\234\355\230\204.py" +++ "b/1717\354\247\221\355\225\251\354\235\230\355\221\234\355\230\204.py" @@ -1,35 +1,35 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(100000) - -n,m = map(int,input().split()) -parent = [i for i in range(n+1)] - -def Union(a,b): - a = Find(a) - b = Find(b) - - if a>b: - parent[a] = b - else: - parent[b] = a - -def Find(u): - if parent[u]==u: - return u - parent[u] = Find(parent[u]) - return parent[u] - - - -for _ in range(m): - flag, x, y = map(int,input().split()) - - if flag: - if Find(x) == Find(y): - print("YES") - else: - print("NO") - else: - Union(x,y) +import sys +input = sys.stdin.readline +sys.setrecursionlimit(100000) + +n,m = map(int,input().split()) +parent = [i for i in range(n+1)] + +def Union(a,b): + a = Find(a) + b = Find(b) + + if a>b: + parent[a] = b + else: + parent[b] = a + +def Find(u): + if parent[u]==u: + return u + parent[u] = Find(parent[u]) + return parent[u] + + + +for _ in range(m): + flag, x, y = map(int,input().split()) + + if flag: + if Find(x) == Find(y): + print("YES") + else: + print("NO") + else: + Union(x,y) \ No newline at end of file diff --git "a/1719\355\203\235\353\260\260.py" "b/1719\355\203\235\353\260\260.py" deleted file mode 100644 index 543acf7..0000000 --- "a/1719\355\203\235\353\260\260.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline - -n, m = map(int, input().split()) -dists = [[float('inf') for _ in range(n)] for _ in range(n)] -pre_node = [[0 for _ in range(n)] for _ in range(n)] -for _ in range(m): - a, b, c = map(int, input().split()) - dists[a-1][b-1] = min(dists[a-1][b-1],c) - dists[b-1][a-1] = min(dists[b-1][a-1],c) - pre_node[a-1][b-1] = b - pre_node[b-1][a-1] = a - - -for k in range(n): - for i in range(n): - for j in range(n): - if dists[i][j] > dists[i][k] + dists[k][j]: - dists[i][j] = dists[i][k] + dists[k][j] - pre_node[i][j] = pre_node[i][k] - -for i in range(n): - pre_node[i][i] = '-' -for row in pre_node: - print(*row) \ No newline at end of file diff --git "a/17208 \354\271\264\354\232\260\353\262\204\352\261\260 \354\225\214\353\260\224\354\203\235.py" "b/17208 \354\271\264\354\232\260\353\262\204\352\261\260 \354\225\214\353\260\224\354\203\235.py" deleted file mode 100644 index eaf5819..0000000 --- "a/17208 \354\271\264\354\232\260\353\262\204\352\261\260 \354\225\214\353\260\224\354\203\235.py" +++ /dev/null @@ -1,36 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M, K = map(int, input().split()) -orders = [[0, 0]] + [list(map(int, input().split())) for _ in range(N)] -dp = [[[0 for _ in range(K + 1)] for _ in range(M + 1)] for _ in range(N + 1)] - -for order_cnt in range(1, len(orders)): - cur_b, cur_f = orders[order_cnt] - for max_burger in range(1, M + 1): - for max_fries in range(1, K + 1): - # 가져올 수 있으면 가져오거나 가져오지 않거나. 둘중 큰거. - if cur_b <= max_burger and cur_f <= max_fries: - dp[order_cnt][max_burger][max_fries] = max( - 1 + dp[order_cnt - 1][max_burger - cur_b][max_fries - cur_f], - dp[order_cnt - 1][max_burger][max_fries]) - else: - dp[order_cnt][max_burger][max_fries] = dp[order_cnt - 1][max_burger][max_fries] - -print(dp[N][M][K]) - - - -# 1등풀이. -MIS = lambda: map(int,input().split()) - -n, cheese, potato = MIS() -dp = [[-999]*(potato+1) for i in range(cheese+1)] -dp[cheese][potato] = 0 - -for ORDER in range(n): - c, p = MIS() - for i in range(cheese+1-c): - for j in range(potato+1-p): - dp[i][j] = max(dp[i][j], dp[i+c][j+p]+1) -print(max(map(max,dp))) \ No newline at end of file diff --git "a/17219 \353\271\204\353\260\200\353\262\210\355\230\270 \354\260\276\352\270\260.py" "b/17219 \353\271\204\353\260\200\353\262\210\355\230\270 \354\260\276\352\270\260.py" deleted file mode 100644 index b64efdc..0000000 --- "a/17219 \353\271\204\353\260\200\353\262\210\355\230\270 \354\260\276\352\270\260.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -dic = {} -for _ in range(N): - address, pw = input().split() - dic[address] = pw -for _ in range(M): - print(dic[input().rstrip()]) \ No newline at end of file diff --git "a/17255 N\354\234\274\353\241\234 \353\247\214\353\223\244\352\270\260.py" "b/17255 N\354\234\274\353\241\234 \353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 6c25908..0000000 --- "a/17255 N\354\234\274\353\241\234 \353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - -def dfs(left, right, string): - if len(string) == target: - answers.add(string) - return - if left > 0: - dfs(left - 1, right, string + N[left - 1:right + 1]) - if right < n: - dfs(left, right + 1, string + N[left: right + 2]) - -N = input().rstrip() -n = len(N) -target = n * (n + 1) // 2 -answers = set() -for i in range(n): - dfs(i, i, N[i]) -print(len(answers)) - - - - -def dfs(string): - global cnt - if len(n) == 1: - cnt +=1 - return - L = set(list(string)) - if len(L) == 1: - cnt +=1 - return - dfs(string[1:]) - dfs(string[:-1]) - -n = input() -cnt = 0 -dfs(n) -print(cnt) \ No newline at end of file diff --git "a/1725\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250.py" "b/1725\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250.py" deleted file mode 100644 index 74a91e0..0000000 --- "a/1725\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input=sys.stdin.readline - - -n=int(input()) -graph=[] -result=0 -left=0 -a=0 -for _ in range(n): - graph.append(int(input())) -graph.append(0) -stack=[(0,graph[0])] -# cursor는 오른쪽으로 탐색할수록 커짐. stack에 cursor위치와 그곳의 높이를 집어넣음. -# stack의 제일 위층 의 높이(전층의 높이)가 이번 층의 높이보다 크면 즉 이번 층이 작으면 -# stack에서 한칸씩 왼쪽으로 돌아가면서 면적 측정. 면적 = 빠진사각형 높이*(내위치-그 사각형 위치) -# 나보다 낮은 곳까지 stack을 pop하면서 계산한 후 다시 내위치부터 append하며 오른쪽으로 진행. -# stack에 남아있는 애들은 후에 걔들보다 낮은 위치의 사각형이 나오면 그때 pop하며 마저 계산해줌. -for now in range(1,n+1): - left=now - while stack and stack[-1][1]>graph[now]: - left,temp=stack.pop() - result=max(result,temp*(now-left)) - stack.append((left,graph[now])) - -print(result) \ No newline at end of file diff --git "a/17265 \353\202\230\354\235\230 \354\235\270\354\203\235\354\227\220\353\212\224 \354\210\230\355\225\231\352\263\274 \355\225\250\352\273\230.py" "b/17265 \353\202\230\354\235\230 \354\235\270\354\203\235\354\227\220\353\212\224 \354\210\230\355\225\231\352\263\274 \355\225\250\352\273\230.py" deleted file mode 100644 index f87babd..0000000 --- "a/17265 \353\202\230\354\235\230 \354\235\270\354\203\235\354\227\220\353\212\224 \354\210\230\355\225\231\352\263\274 \355\225\250\352\273\230.py" +++ /dev/null @@ -1,5 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -matrix = [list(input().split()) for __ in range(N)] \ No newline at end of file diff --git "a/17266\354\226\264\353\221\220\354\232\264 \352\265\264\353\213\244\353\246\254.py" "b/17266\354\226\264\353\221\220\354\232\264 \352\265\264\353\213\244\353\246\254.py" deleted file mode 100644 index a52bea6..0000000 --- "a/17266\354\226\264\353\221\220\354\232\264 \352\265\264\353\213\244\353\246\254.py" +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -M = int(input()) -arr = list(map(int, input().split())) - -max_size = 0 -for i in range(1,M): - max_size = max(max_size, arr[i] - arr[i-1]) - -print(max((max_size+1)//2,arr[0] - 0, N - arr[-1])) \ No newline at end of file diff --git "a/1727 \354\273\244\355\224\214 \353\247\214\353\223\244\352\270\260.py" "b/1727 \354\273\244\355\224\214 \353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 34bf021..0000000 --- "a/1727 \354\273\244\355\224\214 \353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -n, m = map(int, input().split()) -boys = list(map(int, input().split())) -girls = list(map(int, input().split())) -if n > m: - boys, girls = girls, boys - n, m = m, n -dp = [[0] * m for __ in range(n)] -boys.sort(); girls.sort() - -dp[0][0] = abs(boys[0] - girls[0]) -for j in range(1, m - (n - 1)): - dp[0][j] = min(abs(boys[0] - girls[j]), dp[0][j - 1]) - -for i in range(1, n): - for j in range(i, m - (n - i - 1)): - if i == j: - dp[i][j] = dp[i - 1][j - 1] + abs(boys[i] - girls[j]) - else: - dp[i][j] = min(dp[i - 1][j - 1] + abs(boys[i] - girls[j]), dp[i][j - 1]) -print(dp[n - 1][m - 1]) \ No newline at end of file diff --git a/17298.py b/17298.py index 7fe74b0..2518400 100644 --- a/17298.py +++ b/17298.py @@ -1,36 +1,44 @@ -import sys -input = sys.stdin.readline - - - -A = int(input()) -An = list(map(int,input().split())) - -stack = [] -result = [-1]*A - -stack.append(0) -i = 1 - -while stack and i < A: - while stack and An[stack[-1]] < An[i]: - result[stack[-1]] = An[i] - stack.pop() - - stack.append(i) - i+=1 - -for i in result: - print(i, end = " ") -# answer = "" -# for i in range(A): -# if i==A-1: -# answer += "-1" -# break -# for j in range(i+1,A): -# if(An[i]=An[j]): -# answer += "-1 " +import sys +input = sys.stdin.readline + + + +A = int(input()) +An = list(map(int,input().split())) + +stack = [] +result = [-1]*A + +stack.append(0) +i = 1 + +# i 즉 인덱스가 A-1때까지 돌린다. +while stack and i < A: + # 큰걸찾으면 stack에서 빠지면서 result에 저장해. + # stack에 차있던것들(오큰수 못찾았던 것들) 쭉 비우면서 진행 + # An[i]보다 크거나 작은수 나오면 스탑하고 다시 stack채우기 진행. + # 결국 끝까지stack에 남으면 -1 + while stack and An[stack[-1]] < An[i]: + result[stack[-1]] = An[i] + print(stack, result) + stack.pop() + + stack.append(i) + i+=1 + print(stack, result) + +for i in result: + print(i, end = " ") + +# answer = "" +# for i in range(A): +# if i==A-1: +# answer += "-1" +# break +# for j in range(i+1,A): +# if(An[i]=An[j]): +# answer += "-1 " # print(answer) \ No newline at end of file diff --git a/17299.py b/17299.py index d92bb85..92a6113 100644 --- a/17299.py +++ b/17299.py @@ -1,26 +1,8 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -A = list(map(int,input().split())) -#1000000이 아닌 1000001... -F = [0]*1000001 -stack=[0] -NGF = [-1]*N - -# F(Ai) 등장횟수 -for number in A: - F[number] += 1 - - -# NGF 오등큰수 -for i in range(N): - while stack and F[A[stack[-1]]] < F[A[i]]: - NGF[stack[-1]] = A[i] - stack.pop() - stack.append(i) - i+=1 - - -for ans in NGF: - print(ans, end=" ") +import sys +input = sys.stdin.readline + +N = int(input()) +A = list(map(int,input().split())) +num=[] +for i in range(N): + num.append(int(input())) \ No newline at end of file diff --git "a/17352 \354\227\254\353\237\254\353\266\204\354\235\230 \353\213\244\353\246\254\352\260\200 \353\220\230\354\226\264 \353\223\234\353\246\254\352\262\240\354\212\265\353\213\210\353\213\244.py" "b/17352 \354\227\254\353\237\254\353\266\204\354\235\230 \353\213\244\353\246\254\352\260\200 \353\220\230\354\226\264 \353\223\234\353\246\254\352\262\240\354\212\265\353\213\210\353\213\244.py" deleted file mode 100644 index 624df54..0000000 --- "a/17352 \354\227\254\353\237\254\353\266\204\354\235\230 \353\213\244\353\246\254\352\260\200 \353\220\230\354\226\264 \353\223\234\353\246\254\352\262\240\354\212\265\353\213\210\353\213\244.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline - - -def find(x): - if parent[x] == x: - return x - parent[x] = find(parent[x]) - return parent[x] - - -def union(a, b): - a = find(a) - b = find(b) - - if a < b: - a, b = b, a - parent[b] = a - - -N = int(input()) -parent = {i: i for i in range(1, N+1)} -for _ in range(N-2): - a, b = map(int, input().split()) - union(a, b) - -pivot = find(1) -for i in range(2, N+1): - if pivot != find(i): - print(pivot, i) - exit() \ No newline at end of file diff --git "a/17386\354\204\240\353\266\204\352\265\220\354\260\2502.py" "b/17386\354\204\240\353\266\204\352\265\220\354\260\2502.py" deleted file mode 100644 index 92cf1fd..0000000 --- "a/17386\354\204\240\353\266\204\352\265\220\354\260\2502.py" +++ /dev/null @@ -1,21 +0,0 @@ -x1, y1, x2, y2=map(int, input().split()) -x3, y3, x4, y4=map(int, input().split()) - -answer=0 -didanswer=False -def ccw(x1,y1,x2,y2,x3,y3): - tmp= (x2-x1)*(y3-y1)- (x3-x1)*(y2-y1) - if tmp> 0: - return 1 - elif tmp < 0: - return -1 - else: - return 0 -if ccw(x1,y1,x2,y2,x3,y3) * ccw(x1,y1,x2,y2,x4,y4)==0 and ccw(x3,y3,x4,y4,x1,y1) * ccw(x3,y3,x4,y4,x2,y2)==0: - didanswer=True - if min(x1,x2)<=max(x3,x4) and min(x3,x4)<=max(x1,x2) and min(y1,y2)<=max(y3,y4) and min(y3,y4)<=max(y1,y2): - answer=1 -if ccw(x1,y1,x2,y2,x3,y3) * ccw(x1,y1,x2,y2,x4,y4)<=0 and ccw(x3,y3,x4,y4,x1,y1) * ccw(x3,y3,x4,y4,x2,y2)<=0: - if not didanswer: - answer=1 -print(answer) \ No newline at end of file diff --git "a/17387\354\204\240\353\266\204\352\265\220\354\260\2502.py" "b/17387\354\204\240\353\266\204\352\265\220\354\260\2502.py" deleted file mode 100644 index 92cf1fd..0000000 --- "a/17387\354\204\240\353\266\204\352\265\220\354\260\2502.py" +++ /dev/null @@ -1,21 +0,0 @@ -x1, y1, x2, y2=map(int, input().split()) -x3, y3, x4, y4=map(int, input().split()) - -answer=0 -didanswer=False -def ccw(x1,y1,x2,y2,x3,y3): - tmp= (x2-x1)*(y3-y1)- (x3-x1)*(y2-y1) - if tmp> 0: - return 1 - elif tmp < 0: - return -1 - else: - return 0 -if ccw(x1,y1,x2,y2,x3,y3) * ccw(x1,y1,x2,y2,x4,y4)==0 and ccw(x3,y3,x4,y4,x1,y1) * ccw(x3,y3,x4,y4,x2,y2)==0: - didanswer=True - if min(x1,x2)<=max(x3,x4) and min(x3,x4)<=max(x1,x2) and min(y1,y2)<=max(y3,y4) and min(y3,y4)<=max(y1,y2): - answer=1 -if ccw(x1,y1,x2,y2,x3,y3) * ccw(x1,y1,x2,y2,x4,y4)<=0 and ccw(x3,y3,x4,y4,x1,y1) * ccw(x3,y3,x4,y4,x2,y2)<=0: - if not didanswer: - answer=1 -print(answer) \ No newline at end of file diff --git "a/17396 \353\260\261\353\217\204\354\226\264.py" "b/17396 \353\260\261\353\217\204\354\226\264.py" deleted file mode 100644 index b546eda..0000000 --- "a/17396 \353\260\261\353\217\204\354\226\264.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappush, heappop - - -def dijkstra(start): - visited[start] = 0 - heap = [] - heappush(heap,[visited[start], start]) - while heap: - time, cur_node = heappop(heap) - if visited[cur_node] < time: - continue - for next_time, next_node in edges[cur_node]: - if visited[next_node] > time + next_time: - visited[next_node] = time + next_time - heappush(heap, [visited[next_node], next_node]) - - -N, M = map(int, input().split()) -# arr가 1이면 못지나감. -arr = list(map(int, input().split())) -edges = {i: [] for i in range(N)} -visited = {i: float('inf') for i in range(N)} -for __ in range(M): - a, b, t = map(int, input().split()) - if a != N-1 and b != N-1 and (arr[a] or arr[b]): - continue - edges[a].append((t, b)) - edges[b].append((t, a)) -dijkstra(0) -print(visited[N-1] if visited[N-1] != float('inf') else -1) \ No newline at end of file diff --git "a/17404RGB\352\261\260\353\246\2542.py" "b/17404RGB\352\261\260\353\246\2542.py" index cc40980..49dab55 100644 --- "a/17404RGB\352\261\260\353\246\2542.py" +++ "b/17404RGB\352\261\260\353\246\2542.py" @@ -1,23 +1,22 @@ -import sys -input = sys.stdin.readline - -# 삘 초 파로 칠하는 모든 경우의 수를 계산. -N = int(input()) -price = [list(map(int,input().split())) for _ in range(N)] -dp = [[1001,1001,1001] for _ in range(N+1)] -ans = [] - -for init in range(3): - dp[1][init] = price[0][init] - dp[1][(init+1)%3] = 3001 - dp[1][(init+2)%3] = 3001 - - for i in range(2,N+1): - dp[i][0] = min(dp[i-1][1]+price[i-1][0],dp[i-1][2]+price[i-1][0]) - dp[i][1] = min(dp[i-1][0]+price[i-1][1],dp[i-1][2]+price[i-1][1]) - dp[i][2] = min(dp[i-1][0]+price[i-1][2],dp[i-1][1]+price[i-1][2]) - - dp[N][init] = 1000001 - ans.append(min(dp[N])) - +import sys +input = sys.stdin.readline + +N = int(input()) +price = [list(map(int,input().split())) for _ in range(N)] +dp = [[1001,1001,1001] for _ in range(N+1)] +ans = [] + +for init in range(3): + dp[1][init] = price[0][init] + dp[1][(init+1)%3] = 3001 + dp[1][(init+2)%3] = 3001 + + for i in range(2,N+1): + dp[i][0] = min(dp[i-1][1]+price[i-1][0],dp[i-1][2]+price[i-1][0]) + dp[i][1] = min(dp[i-1][0]+price[i-1][1],dp[i-1][2]+price[i-1][1]) + dp[i][2] = min(dp[i-1][0]+price[i-1][2],dp[i-1][1]+price[i-1][2]) + + dp[N][init] = 1000001 + ans.append(min(dp[N])) + print(min(ans)) \ No newline at end of file diff --git "a/17406 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2604.py" "b/17406 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2604.py" deleted file mode 100644 index 16968bd..0000000 --- "a/17406 \353\260\260\354\227\264\353\217\214\353\246\254\352\270\2604.py" +++ /dev/null @@ -1,61 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def rotate_each(x,y,d,m): - q = deque() - for i in range(y-d,y+d+1): - q.append(m[x-d][i]) - for i in range(x-d+1,x+d+1): - q.append(m[i][y+d]) - for i in range(y+d-1,y-d-1,-1): - q.append(m[x+d][i]) - for i in range(x+d-1,x-d,-1): - q.append(m[i][y-d]) - q.rotate(1) - for i in range(y-d,y+d+1): - m[x-d][i] = q.popleft() - for i in range(x-d+1,x+d+1): - m[i][y+d] = q.popleft() - for i in range(y+d-1,y-d-1,-1): - m[x+d][i] = q.popleft() - for i in range(x+d-1,x-d,-1): - m[i][y-d] = q.popleft() - return m - - -def rotate_matrix(command_set): - global min_value - new_matrix = [row[:] for row in matrix] - for command in command_set: - r, c, s = command - for i in range(1,s+1): - new_matrix = rotate_each(r-1,c-1,i,new_matrix) - for row in new_matrix: - min_value = min(min_value,sum(row)) - - -def dfs(arr): - if len(arr) == K: - rotate_matrix(arr) - for i in range(K): - if not visited[i]: - visited[i] = True - dfs(arr + [rotate_data[i]]) - visited[i] = False - - -N, M, K = map(int, input().split()) -matrix = [list(map(int, input().split())) for _ in range(N)] -visited = {i: False for i in range(K)} -rotate_data = [] -min_value = float('inf') -for _ in range(K): - r, c, s = map(int, input().split()) - rotate_data.append((r,c,s)) -for i in range(K): - visited[i] = True - dfs([rotate_data[i]]) - visited[i] = False -print(min_value) \ No newline at end of file diff --git a/17413.py b/17413.py index b30ab2a..5148cd8 100644 --- a/17413.py +++ b/17413.py @@ -1,25 +1,25 @@ -S = list(input()) -main = '' -check = 0 -stack = [] -for i in range(len(S)): - if check == 0: - if S[i] == "<": - check = 1 - while stack: - main += stack.pop() - main += S[i] - elif S[i] == " ": - while stack: - main += stack.pop() - main += S[i] - else: - stack.append(S[i]) - else: - main += S[i] - if S[i] ==">": - check=0 -while stack: - main += stack.pop() - +S = list(input()) +main = '' +check = 0 +stack = [] +for i in range(len(S)): + if check == 0: + if S[i] == "<": + check = 1 + while stack: + main += stack.pop() + main += S[i] + elif S[i] == " ": + while stack: + main += stack.pop() + main += S[i] + else: + stack.append(S[i]) + else: + main += S[i] + if S[i] ==">": + check=0 +while stack: + main += stack.pop() + print(main) \ No newline at end of file diff --git "a/17413_\355\203\234\352\267\270\353\222\244\354\247\221\352\270\260.py" "b/17413_\355\203\234\352\267\270\353\222\244\354\247\221\352\270\260.py" deleted file mode 100644 index 7907a07..0000000 --- "a/17413_\355\203\234\352\267\270\353\222\244\354\247\221\352\270\260.py" +++ /dev/null @@ -1,21 +0,0 @@ -arr = list(input()) -board = 0 -answer = 0 -for i in range(len(arr)): - if arr[i]=='(': - if arr[i+1]==')': - answer+=board - print(f'board:{board}answer:{answer}') - else: - board+=1 - print(f'board:{board}answer:{answer}') - - if arr[i]==')': - if arr[i-1]=='(': - continue - print(f'board:{board}answer:{answer}') - else: - board-=1 - answer+=1 - print(f'board:{board}answer:{answer}') -print(f'board:{board}answer:{answer}') \ No newline at end of file diff --git "a/17451 \355\217\211\355\226\211\354\232\260\354\243\274.py" "b/17451 \355\217\211\355\226\211\354\232\260\354\243\274.py" deleted file mode 100644 index 100585d..0000000 --- "a/17451 \355\217\211\355\226\211\354\232\260\354\243\274.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -v = list(map(int, input().split())) -answer = 0 -for i in range(n-1, -1, -1): - if answer <= v[i]: - answer = v[i] - else: - if answer % v[i]: - answer = (answer // v[i] + 1) * v[i] -print(answer) \ No newline at end of file diff --git "a/17472 \353\213\244\353\246\254\353\247\214\353\223\244\352\270\2602.py" "b/17472 \353\213\244\353\246\254\353\247\214\353\223\244\352\270\2602.py" deleted file mode 100644 index f707a82..0000000 --- "a/17472 \353\213\244\353\246\254\353\247\214\353\223\244\352\270\2602.py" +++ /dev/null @@ -1,92 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from heapq import heappop, heappush - - -def find(x): - if parents[x] == x: - return x - parents[x] = find(parents[x]) - return parents[x] - - -def union(x, y): - x = find(x) - y = find(y) - - if x > y: - x, y = y, x - parents[y] = x - - -def grouping_continent(x, y): - q = deque() - q.append((x, y)) - maps[x][y] = group_num - while q: - x, y = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < M and maps[nx][ny] == 1: - maps[nx][ny] = group_num - q.append((nx, ny)) - - -def get_dists(row, col): - for i in range(row): - left = -1 - for j in range(1, col): - if maps[i][j - 1] and not maps[i][j]: - left = j - 1 - left_continent = maps[i][j - 1] - elif not maps[i][j - 1] and maps[i][j] and not left == -1: - right_continent = maps[i][j] - if left_continent != right_continent and not j - 1 - left == 1: - if left_continent > right_continent: - left_continent, right_continent = right_continent, left_continent - if (left_continent, right_continent) not in dists: - dists[(left_continent, right_continent)] = j - left - 1 - else: - dists[(left_continent, right_continent)] = min(dists[(left_continent, right_continent)], - j - left - 1) - - -N, M = map(int, input().split()) -maps = [list(map(int, input().split())) for _ in range(N)] -delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) -# grouping -group_num = 2 -for i in range(N): - for j in range(M): - if maps[i][j] == 1: - grouping_continent(i, j) - group_num += 1 - -n = group_num - 2 -parents = {i: i for i in range(2, group_num)} -# 거라계산 후 간선정보 갱신 -dists = {} -get_dists(N, M) -maps = [row[::-1] for row in zip(*maps)] -get_dists(M, N) - -edges = [] -for a, b in dists: - heappush(edges, (dists[(a, b)], a, b)) - -# kruskal -answer = 0 -cnt = 0 -while edges: - dist, a, b = heappop(edges) - if find(a) != find(b): - union(a, b) - answer += dist - cnt += 1 - if cnt == n - 1: - break - -if cnt != n - 1: - answer = -1 -print(answer) \ No newline at end of file diff --git "a/1747\354\206\214\354\210\230&\355\216\240\353\246\260\353\223\234\353\241\254.py" "b/1747\354\206\214\354\210\230&\355\216\240\353\246\260\353\223\234\353\241\254.py" deleted file mode 100644 index b6e4156..0000000 --- "a/1747\354\206\214\354\210\230&\355\216\240\353\246\260\353\223\234\353\241\254.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - - -N = int(input()) -primes = [True] * 2000000 -primes[0] = primes[1] = False -for i in range(2,1001): - if primes[i]: - for j in range(i+i,2000000,i): - primes[j] = False -for i in range(N,2000000): - if primes[i]: - c_i = str(i) - if c_i == c_i[::-1]: - print(i) - break \ No newline at end of file diff --git "a/17484\354\247\204\354\232\260\354\235\230 \353\213\254 \354\227\254\355\226\211.PY" "b/17484\354\247\204\354\232\260\354\235\230 \353\213\254 \354\227\254\355\226\211.PY" deleted file mode 100644 index 26720a9..0000000 --- "a/17484\354\247\204\354\232\260\354\235\230 \353\213\254 \354\227\254\355\226\211.PY" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -matrix = [list(map(int, input().split())) for _ in range(N)] -dp = [[[0,0,0] for _ in range(M)]] + [[[float('inf'),float('inf'),float('inf')] for _ in range(M)] for _ in range(N)] - -for i in range(1,N+1): - for j in range(M): - if j < M-1: - dp[i][j][0] = min(dp[i-1][j+1][1],dp[i-1][j+1][2]) + matrix[i-1][j] - if 0 < j: - dp[i][j][2] = min(dp[i-1][j-1][1],dp[i-1][j-1][0]) + matrix[i-1][j] - dp[i][j][1] = min(dp[i-1][j][0],dp[i-1][j][2]) + matrix[i-1][j] - -min_value = float('inf') -for row in dp[i]: - for each in row: - min_value = min(min_value,each) -print(min_value) \ No newline at end of file diff --git "a/1748\354\210\230\354\235\264\354\226\264\354\223\260\352\270\260.py" "b/1748\354\210\230\354\235\264\354\226\264\354\223\260\352\270\260.py" index 9d68fbe..798aa36 100644 --- "a/1748\354\210\230\354\235\264\354\226\264\354\223\260\352\270\260.py" +++ "b/1748\354\210\230\354\235\264\354\226\264\354\223\260\352\270\260.py" @@ -1,26 +1,26 @@ -import sys -input = sys.stdin.readline - -N = int(input()) - -if N//1000000000 != 0: - ans = 10 + 9*900000000 + 8*90000000 + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 -elif N//100000000 != 0: - ans = 9*(N-99999999) + 8*90000000 + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 -elif N//10000000 != 0: - ans = 8*(N-9999999) + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 -elif N//1000000 !=0: - ans = 7*(N-999999) + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 -elif N//100000 !=0: - ans = 6*(N-99999) + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 -elif N//10000 !=0: - ans = 5*(N-9999) + 4*9000 + 3*900 + 2*90 + 1*9 -elif N//1000 !=0: - ans = 4*(N-999) + 3*900 + 2*90 + 1*9 -elif N//100 !=0: - ans = 3*(N-99) + 2*90 + 1*9 -elif N//10 !=0: - ans = 2*(N-9) + 1*9 -else: - ans = 1*N -print(ans) +import sys +input = sys.stdin.readline + +N = int(input()) + +if N//1000000000 != 0: + ans = 10 + 9*900000000 + 8*90000000 + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//100000000 != 0: + ans = 9*(N-99999999) + 8*90000000 + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//10000000 != 0: + ans = 8*(N-9999999) + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//1000000 !=0: + ans = 7*(N-999999) + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//100000 !=0: + ans = 6*(N-99999) + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//10000 !=0: + ans = 5*(N-9999) + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//1000 !=0: + ans = 4*(N-999) + 3*900 + 2*90 + 1*9 +elif N//100 !=0: + ans = 3*(N-99) + 2*90 + 1*9 +elif N//10 !=0: + ans = 2*(N-9) + 1*9 +else: + ans = 1*N +print(ans) diff --git "a/17503\353\247\245\354\243\274\354\266\225\354\240\234.py" "b/17503\353\247\245\354\243\274\354\266\225\354\240\234.py" deleted file mode 100644 index ad7d528..0000000 --- "a/17503\353\247\245\354\243\274\354\266\225\354\240\234.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -from heapq import heappop,heappush -input = sys.stdin.readline - -# N일 K종류 맥주 무료 제공 -# 하루 맥주 1병 전에 받은 종류 못받음. -# 맥주 N개의 선호도 합 M이상. -# 조합 K 종류 맥주 중 N개 추출 합이 M이상되는. -# 도수 낮은거 순으로 먹음. -N, M, K = map(int, input().split()) -beers = [list(map(int, input().split())) for _ in range(K)] -beers2 = sorted(beers,key=lambda x: (x[1],x[0])) -heap = [] -flav_p = 0 -cnt =0 -left = 0 -for beer in beers2: - flav_p += beer[0] - heappush(heap,beer[0]) - if len(heap) == N: - if flav_p >=M: - answer = beer[1] - break - else: - flav_p -= heappop(heap) -else: - print(-1) - exit() -print(answer) \ No newline at end of file diff --git a/17521 Byte Coin.py b/17521 Byte Coin.py deleted file mode 100644 index 8a254c0..0000000 --- a/17521 Byte Coin.py +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N, W = map(int, input().split( )) -costs = [int(input()) for __ in range(N)] -coin = 0 -for i in range(1, N): - if not coin: - if costs[i - 1] < costs[i]: - coin = W // costs[i - 1] - W -= coin * costs[i - 1] - else: - if costs[i - 1] > costs[i]: - W += coin * costs[i - 1] - coin = 0 -if coin: W += coin * costs[N - 1] -print(W) - diff --git "a/1753\354\265\234\353\213\250\352\262\275\353\241\234.py" "b/1753\354\265\234\353\213\250\352\262\275\353\241\234.py" index 7c29ed3..8f3e795 100644 --- "a/1753\354\265\234\353\213\250\352\262\275\353\241\234.py" +++ "b/1753\354\265\234\353\213\250\352\262\275\353\241\234.py" @@ -1,34 +1,34 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict -from heapq import heappush,heappop - -def dijkstra(start): - global min_dists - heap = [] - min_dists = [float('INF')]*(V+1) - min_dists[start] = 0 - heappush(heap,[min_dists[start],start]) - while heap: - cur_dists,cur_node = heappop(heap) - if cur_dists > min_dists[cur_node]: - continue - for next_dists,next_node in graph[cur_node]: - dists = cur_dists + next_dists - if dists < min_dists[next_node]: - min_dists[next_node] = dists - heappush(heap,[min_dists[next_node],next_node]) - return min_dists - -V,E = map(int,input().split()) -K = int(input()) -graph = defaultdict(list) - -for _ in range(E): - u,v,w = map(int,input().split()) - graph[u].append([w,v]) - -dijkstra(K) - -for i in range(1,V+1): +import sys +input = sys.stdin.readline +from collections import defaultdict +from heapq import heappush,heappop + +def dijkstra(start): + global min_dists + heap = [] + min_dists = [float('INF')]*(V+1) + min_dists[start] = 0 + heappush(heap,[min_dists[start],start]) + while heap: + cur_dists,cur_node = heappop(heap) + if cur_dists > min_dists[cur_node]: + continue + for next_dists,next_node in graph[cur_node]: + dists = cur_dists + next_dists + if dists < min_dists[next_node]: + min_dists[next_node] = dists + heappush(heap,[min_dists[next_node],next_node]) + return min_dists + +V,E = map(int,input().split()) +K = int(input()) +graph = defaultdict(list) + +for _ in range(E): + u,v,w = map(int,input().split()) + graph[u].append([w,v]) + +dijkstra(K) + +for i in range(1,V+1): print(min_dists[i] if not min_dists[i] == float('inf') else 'INF') \ No newline at end of file diff --git "a/1758 \354\225\214\353\260\224\354\203\235\352\260\225\355\230\270.py" "b/1758 \354\225\214\353\260\224\354\203\235\352\260\225\355\230\270.py" deleted file mode 100644 index b7f6f40..0000000 --- "a/1758 \354\225\214\353\260\224\354\203\235\352\260\225\355\230\270.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -arr = [int(input()) for _ in range(n)] -arr.sort(reverse=True) - -sum = 0 -for i in range(n): - if arr[i] - i < 0: - continue - sum += (arr[i] - i) -print(sum) \ No newline at end of file diff --git "a/1759\354\225\224\355\230\270\353\247\214\353\223\244\352\270\260.py" "b/1759\354\225\224\355\230\270\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index edf0275..0000000 --- "a/1759\354\225\224\355\230\270\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline -from itertools import combinations - -L,C = map(int,input().split()) -secret = list(input().split()) - -# 암호는 사전순 sorted되어있다. -secret.sort() - -# 최소한개모음 두개자음 -mom_char = ['a','e','i','o','u'] - -combs = list(combinations(secret,L)) -ans = [] - -for chars in combs: - mom_cnt=0 - child_cnt=0 - for char in chars: - if char in mom_char: - mom_cnt+=1 - else: - child_cnt +=1 - if mom_cnt>=1 and child_cnt>=2: - ans.append(chars) - - -for chars in ans: - print(''.join(chars)) \ No newline at end of file diff --git "a/17616\353\223\261\354\210\230\354\260\276\352\270\260.py" "b/17616\353\223\261\354\210\230\354\260\276\352\270\260.py" deleted file mode 100644 index ee8d525..0000000 --- "a/17616\353\223\261\354\210\230\354\260\276\352\270\260.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(x, adj): - rtn = 0 - q = deque() - q.append(x) - visited[x] = True - while q: - v = q.popleft() - for n in adj[v]: - if not visited[n]: - q.append(n) - visited[n] = True - rtn += 1 - return rtn - -N, M, X = map(int, input().split()) -higher = [[] for _ in range(N+1)] -lower = [[] for _ in range(N+1)] -visited = [False] * (N+1) - -for _ in range(M): - A, B = map(int, input().split()) - - # A보다 큰 학생들 - higher[A].append(B) - # B보다 작은 학생들 - lower[B].append(A) - -print(1+bfs(X, lower), N-bfs(X, higher)) \ No newline at end of file diff --git "a/1761\354\240\225\354\240\220\353\223\244\354\235\230 \352\261\260\353\246\254.py" "b/1761\354\240\225\354\240\220\353\223\244\354\235\230 \352\261\260\353\246\254.py" deleted file mode 100644 index 742c7ad..0000000 --- "a/1761\354\240\225\354\240\220\353\223\244\354\235\230 \352\261\260\353\246\254.py" +++ /dev/null @@ -1,73 +0,0 @@ - -# 정점들 사이의 최단거리는 dist[a] - dist[lca] + dist[b] - dist[lca] -# LCA를 지나는 거리가 최단거리이다. -import sys -sys.setrecursionlimit(int(1e5)) -input = sys.stdin.readline -LOG = 21 # (1000000의 log2를 취한 값의 올림값)(2의 i승 단위의 부모값을 저장하기 위한 크기.) - -# 각 노드의 depth를 찾아 기록하기 위한 dfs -def find_depth(cur_node, parent_node,value): - depth[cur_node] = depth[parent_node] + 1 - check[cur_node] = True - if cur_node != 1: - dp_dists[cur_node] += dp_dists[parent_node] + value - for next_node,dist in graph[cur_node]: - if not check[next_node]: - parent[next_node][0] = cur_node - find_depth(next_node, cur_node,dist) - - -# 공통조상 찾는 함수 -def LCA(a,b): - - # b가 더 깊도록 설정 - if depth[a] > depth[b]: - a,b = b,a - # 더 깊은 b에 대해 동일해질때까지 올린다. - for i in range(LOG-1,-1,-1): - if depth[b] - depth[a] >= (1< tree[i][k] + tree[k][j]: - tree[i][j] = tree[i][k] + tree[k][j] - -M = int(input()) - -for _ in range(M): - a,b = map(int,input().split()) - print(tree[a][b]) \ No newline at end of file diff --git a/17626 Four Squares.py b/17626 Four Squares.py deleted file mode 100644 index 110edd9..0000000 --- a/17626 Four Squares.py +++ /dev/null @@ -1,51 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(n): - q = deque() - q.append((n,0)) - visited[n] = True - while q: - r, cnt = q.popleft() - flag = 1 - for square in squares: - next_r = r-square - if next_r > 0 and not visited[next_r]: - if flag: - first = next_r - flag = 0 - if first > square and next_r>=4: - break - visited[next_r] = True - q.append((next_r,cnt+1)) - elif next_r == 0: - return cnt + 1 - -n = int(input()) -squares = [] -m = int(50000*0.5) -for i in range(m,0,-1): - squares.append(i**2) -visited = {i: False for i in range(n+1)} -print(bfs(n)) - - - -###1등코드: -# class Solution: -# def sq(self, n): -# x = int(n**0.5) -# return x*x == n -# def Nsq(self, n): -# if n < 4: return n -# if self.sq(n): return 1 -# while n & 3 == 0: -# n >>= 2 -# if n & 7 == 7: return 4 -# x = int(n**0.5) -# for i in range(1, x+1): -# if self.sq(n - i*i): return 2 -# return 3 -# X = Solution(); N = int(input()) -# print(X.Nsq(N)) \ No newline at end of file diff --git "a/1764\353\223\243\353\263\264\354\236\241.py" "b/1764\353\223\243\353\263\264\354\236\241.py" deleted file mode 100644 index 5387a9e..0000000 --- "a/1764\353\223\243\353\263\264\354\236\241.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M = map(int,input().split()) -not_hear_list = {input().rstrip():1 for _ in range(N)} -not_human=[] -for _ in range(M): - not_see = input().rstrip() - try: - if not_hear_list[not_see]: - not_human.append(not_see) - except: - continue -# 사전순 출력을 위한 정렬 -not_human.sort() -print(len(not_human)) -for human in not_human: - print(human) \ No newline at end of file diff --git "a/1766\353\254\270\354\240\234\354\247\221.py" "b/1766\353\254\270\354\240\234\354\247\221.py" deleted file mode 100644 index d4691e9..0000000 --- "a/1766\353\254\270\354\240\234\354\247\221.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -def topological_sort(): - heap=[] - for i in range(1,N+1): - if not level[i]: - heappush(heap,i) - while heap: - cur_solve = heappop(heap) - answer.append(cur_solve) - for next_solve in ordered[cur_solve]: - level[next_solve] -=1 - if not level[next_solve]: - heappush(heap,next_solve) - -# 문제는 모두 풀어야한다. 먼저푸는게 좋은 문제는 먼저 푼느걸 반드시 먼저 ㅍ루어야한다. -# 가능하면 쉬운문제부터 풀어야한다.(앞번호부터) - -N,M = map(int,input().split()) -ordered = {i:[] for i in range(1,N+1)} -level = {i:0 for i in range(1,N+1)} -answer = [] -for _ in range(M): - first,second = map(int,input().split()) - ordered[first] += [second] - level[second] +=1 - -topological_sort() - -print(*answer) \ No newline at end of file diff --git "a/1780 \354\242\205\354\235\264\354\235\230 \352\260\234\354\210\230.py" "b/1780 \354\242\205\354\235\264\354\235\230 \352\260\234\354\210\230.py" deleted file mode 100644 index 0ea248c..0000000 --- "a/1780 \354\242\205\354\235\264\354\235\230 \352\260\234\354\210\230.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - - -def check(n,s_x,s_y): - pivot = matrix[s_x][s_y] - for i in range(s_x,s_x+n): - for j in range(s_y,s_y+n): - if matrix[i][j] != pivot: - return False - return True - - -def divide_paper(n,s_x,s_y): - global papers - pivot = n//3 - if n==1: - papers[matrix[s_x][s_y]] += 1 - return - if check(n,s_x,s_y): - papers[matrix[s_x][s_y]] += 1 - return - for i in range(3): - for j in range(3): - divide_paper(pivot,s_x+(pivot*i),s_y+(pivot*j)) - - -N = int(input()) -matrix = [list(map(int,input().split())) for _ in range(N)] -papers = {-1: 0, 0: 0, 1: 0} - -divide_paper(N,0,0) -for paper in papers: - print(papers[paper]) \ No newline at end of file diff --git "a/17829_222-\355\222\200\353\247\201.py" "b/17829_222-\355\222\200\353\247\201.py" deleted file mode 100644 index 93fec6a..0000000 --- "a/17829_222-\355\222\200\353\247\201.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -def polling(n,start_x,start_y): - half = n//2 - if n==2: - arr = [matrix[start_x][start_y], matrix[start_x+1][start_y], matrix[start_x][start_y+1], matrix[start_x+1][start_y+1]] - arr.sort() - return arr[-2] - left_top = polling(half,start_x,start_y) - right_top = polling(half,start_x+half,start_y) - left_bottom = polling(half,start_x,start_y+half) - right_bottom = polling(half,start_x+half,start_y+half) - arr = [left_top, right_top, left_bottom, right_bottom] - arr.sort() - return arr[-2] - -N = int(input()) -matrix = [list(map(int, input().split())) for _ in range(N)] -print(polling(N,0,0)) diff --git "a/17845\354\210\230\352\260\225\352\263\274\353\252\251.py" "b/17845\354\210\230\352\260\225\352\263\274\353\252\251.py" deleted file mode 100644 index b470076..0000000 --- "a/17845\354\210\230\352\260\225\352\263\274\353\252\251.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -N,K = map(int,input().split()) -dp =[[0]*(N+1) for _ in range(K+1)] -times=[] -grades=[] -for _ in range(K): - I,T = map(int,input().split()) - times.append(T) - grades.append(I) - -for class_no in range(1,K+1): - for now_time in range(1,N+1): - if times[class_no-1] > now_time: - dp[class_no][now_time] = dp[class_no-1][now_time] - else: - # 지금시간에서 추가하는 과목의 소요시간만큼 뺐을때의 누적가치+그 과목의 점수, 그냥 추가 안했을때 점수 중 높은값. - dp[class_no][now_time] = max(grades[class_no-1]+dp[class_no-1][now_time-times[class_no-1]],dp[class_no-1][now_time]) -print(dp[K][N]) diff --git "a/1786\354\260\276\352\270\260.py" "b/1786\354\260\276\352\270\260.py" deleted file mode 100644 index 4e3f8da..0000000 --- "a/1786\354\260\276\352\270\260.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - - -def MakeTable(P,KMPTable): - j = 0 - for i in range(1,len(P)): - while j > 0 and P[i]!=P[j]: # 같지 않을 때 - j = KMPTable[j-1] # 이전의 맞은부분까지 돌아가서 다시 비교 - if P[i]==P[j]: # 같을 시 - j += 1 # j증가시키고 - KMPTable[i] = j # table 갱신 - -def KMP(T,P,KMPTable): - MakeTable(P,KMPTable) - j = 0 - count = 0 - result = [] - P_size = len(P) - for i in range(len(T)): - while j > 0 and T[i]!=P[j]: # 같지 않을 때 - j = KMPTable[j-1] # 이전의 맞은 부분까지 돌아가서 다시 비교 - if T[i]==P[j]: # 같으면 - if j ==P_size-1: - count += 1 # 갯수 추가 - result.append(i-P_size+2) # 위치 추가 - j = KMPTable[j] # 위치 옮겨주고 다시 탐색 - else: # j늘려준다. - j += 1 - return count, result - -T = input().rstrip() -P = input().rstrip() - -KMPTable = [0 for _ in range(len(P))] - -cnt, answer = KMP(T,P,KMPTable) -print(cnt) -print(*answer) \ No newline at end of file diff --git "a/1789\354\210\230\353\223\244\354\235\230\355\225\251.py" "b/1789\354\210\230\353\223\244\354\235\230\355\225\251.py" deleted file mode 100644 index 41c22c5..0000000 --- "a/1789\354\210\230\353\223\244\354\235\230\355\225\251.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -cnt=0 -sum_num=0 -i=1 - -while N >= sum_num: - sum_num += i - cnt += 1 - i += 1 -print(cnt-1) \ No newline at end of file diff --git "a/17951\355\235\251\353\202\240\353\246\254\353\212\224 \354\213\234\355\227\230\354\247\200\354\206\215\354\227\220\354\204\234 \353\202\264 \355\217\211\354\240\220\354\235\264 \353\212\220\352\273\264\354\247\204\352\261\260\354\225\274.py" "b/17951\355\235\251\353\202\240\353\246\254\353\212\224 \354\213\234\355\227\230\354\247\200\354\206\215\354\227\220\354\204\234 \353\202\264 \355\217\211\354\240\220\354\235\264 \353\212\220\352\273\264\354\247\204\352\261\260\354\225\274.py" deleted file mode 100644 index 7c20d6a..0000000 --- "a/17951\355\235\251\353\202\240\353\246\254\353\212\224 \354\213\234\355\227\230\354\247\200\354\206\215\354\227\220\354\204\234 \353\202\264 \355\217\211\354\240\220\354\235\264 \353\212\220\352\273\264\354\247\204\352\261\260\354\225\274.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline - -def is_possible(target): - cnt = 0 - sum_n = 0 - for score in scores: - sum_n += score - if sum_n >= target: - cnt += 1 - sum_n = 0 - if cnt >= K: - return True - return False - -N, K = map(int, input().split()) -scores = list(map(int, input().split())) - -left, right = 0, int(2e6) -max_score = 0 -while left <= right: - mid = (left + right)//2 - if is_possible(mid): - left = mid + 1 - max_score = mid - else: - right = mid - 1 -print(max_score) \ No newline at end of file diff --git "a/1806\353\266\200\353\266\204\355\225\251.py" "b/1806\353\266\200\353\266\204\355\225\251.py" deleted file mode 100644 index d20681b..0000000 --- "a/1806\353\266\200\353\266\204\355\225\251.py" +++ /dev/null @@ -1,31 +0,0 @@ -N, S = map(int, input().split()) -A = list(map(int, input().split())) - -#먼저 0~n까지의 합을 구해줌 -sum_A = [0] * (N + 1) -for i in range(1, N + 1): - sum_A[i] = sum_A[i-1] + A[i-1] - -#투포인터 설정 -answer = 1000001 -start = 0 -end = 1 - -#알고리즘 실행 -while start != N: - if sum_A[end] - sum_A[start] >= S: - if end - start< answer: - answer = end - start - start += 1 - - else: - if end != N: - end += 1 - else: - start += 1 - -#답이 없을 경우 & 있을 경우 -if answer != 1000001: - print(answer) -else: - print(0) \ No newline at end of file diff --git "a/18115 \354\271\264\353\223\234 \353\206\223\352\270\260.py" "b/18115 \354\271\264\353\223\234 \353\206\223\352\270\260.py" deleted file mode 100644 index 01821e0..0000000 --- "a/18115 \354\271\264\353\223\234 \353\206\223\352\270\260.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -N = int(input()) -a = list(map(int, input().split()))[::-1] -floor = [i for i in range(N, 1, -1)] -front = [1] -q = deque() -for command in a[1:]: - if command == 1: - q.appendleft(front.pop()) - front.append(floor.pop()) - elif command == 2: - q.appendleft(floor.pop()) - else: - q.append(floor.pop()) -answer = front + list(q) -print(*answer) \ No newline at end of file diff --git "a/1817 \354\247\220 \354\261\231\352\270\260\353\212\224 \354\210\214.py" "b/1817 \354\247\220 \354\261\231\352\270\260\353\212\224 \354\210\214.py" deleted file mode 100644 index ab0974d..0000000 --- "a/1817 \354\247\220 \354\261\231\352\270\260\353\212\224 \354\210\214.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -weights = list(map(int, input().split())) -box, cnt = M, 1 -for weight in weights: - if box - weight >= 0: - box -= weight - else: - cnt += 1 - box = M - weight -if not N: cnt = 0 -print(cnt) \ No newline at end of file diff --git "a/18185 \353\235\274\353\251\264 \354\202\254\352\270\260.py" "b/18185 \353\235\274\353\251\264 \354\202\254\352\270\260.py" deleted file mode 100644 index c866a45..0000000 --- "a/18185 \353\235\274\353\251\264 \354\202\254\352\270\260.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline - -def buy_triple(idx): - global cost - k = min(arr[idx: idx + 3]) - arr[idx] -= k - arr[idx + 1] -= k - arr[idx + 2] -= k - cost += 7 * k - - -def buy_double(idx): - global cost - k = min(arr[idx: idx + 2]) - arr[idx] -= k - arr[idx + 1] -= k - cost += 5 * k - - -def buy_each(idx): - global cost - cost += 3 * arr[idx] - - -N = int(input()) -arr = list(map(int, input().split())) + [0, 0] -cost = 0 -for i in range(N): - if arr[i + 1] > arr[i + 2]: - k = min(arr[i], arr[i + 1] - arr[i + 2]) - arr[i] -= k - arr[i + 1] -= k - cost += 5 * k - - buy_triple(i) - else: - buy_triple(i) - buy_double(i) - buy_each(i) -print(cost) diff --git "a/18186 \353\235\274\353\251\264 \354\202\254\352\270\260(Large).py" "b/18186 \353\235\274\353\251\264 \354\202\254\352\270\260(Large).py" deleted file mode 100644 index 24a291e..0000000 --- "a/18186 \353\235\274\353\251\264 \354\202\254\352\270\260(Large).py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - -def buy_triple(idx): - global cost - k = min(arr[idx: idx + 3]) - arr[idx] -= k - arr[idx + 1] -= k - arr[idx + 2] -= k - cost += (B + 2 * C) * k - - -def buy_double(idx): - global cost - k = min(arr[idx: idx + 2]) - arr[idx] -= k - arr[idx + 1] -= k - cost += (B + C) * k - - -def buy_each(idx): - global cost - cost += B * arr[idx] - - -N, B, C = map(int, input().split()) -if B < C: C = B -arr = list(map(int, input().split())) + [0, 0] -cost = 0 -for i in range(N): - if arr[i + 1] > arr[i + 2]: - k = min(arr[i], arr[i + 1] - arr[i + 2]) - arr[i] -= k - arr[i + 1] -= k - cost += (B + C) * k - - buy_triple(i) - else: - buy_triple(i) - buy_double(i) - buy_each(i) -print(cost) diff --git "a/18223\353\257\274\354\244\200\354\235\264\354\231\200 \353\247\210\354\202\260 \352\267\270\353\246\254\352\263\240 \352\261\264\354\232\260.py" "b/18223\353\257\274\354\244\200\354\235\264\354\231\200 \353\247\210\354\202\260 \352\267\270\353\246\254\352\263\240 \352\261\264\354\232\260.py" deleted file mode 100644 index 92cc5f8..0000000 --- "a/18223\353\257\274\354\244\200\354\235\264\354\231\200 \353\247\210\354\202\260 \352\267\270\353\246\254\352\263\240 \352\261\264\354\232\260.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - - -def go_masan(start): - dp_visited = {i: float('inf') for i in range(1,V+1)} - dp_visited[start] = 0 - heap = [] - heappush(heap,[dp_visited[start],start]) - while heap: - cur_dist, cur_node = heappop(heap) - if cur_node == V: - return dp_visited[P],dp_visited[V] - for next_dist, next_node in graph[cur_node]: - if dp_visited[next_node] > cur_dist + next_dist: - dp_visited[next_node] = cur_dist + next_dist - heappush(heap,[dp_visited[next_node],next_node]) - -V, E, P = map(int, input().split()) -graph = {i: [] for i in range(1,V+1)} -for _ in range(E): - a, b, c = map(int, input().split()) - graph[a].append((c,b)) - graph[b].append((c,a)) - -p_dist, masan_dist = go_masan(1) -zero, p_to_masan = go_masan(P) -if p_dist + p_to_masan == masan_dist: - print('SAVE HIM') -else: - print('GOOD BYE') \ No newline at end of file diff --git "a/1823 \354\210\230\355\231\225.py" "b/1823 \354\210\230\355\231\225.py" deleted file mode 100644 index d874949..0000000 --- "a/1823 \354\210\230\355\231\225.py" +++ /dev/null @@ -1,58 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**5) - - -def dynamic_programming(left, right, left): - if left > right: - return 0 - - if dp[left][right]: - return dp[left][right] - - dp[left][right] = max(dynamic_programming(left + 1, right, left + 1) + v[left] * left, - dynamic_programming(left, right - 1, left + 1) + v[right] * left) - return dp[left][right] - - -N = int(input()) -v = [0] + [int(input()) for __ in range(N)] -dp = [[0] * (N + 1) for __ in range(N + 1)] -print(dynamic_programming(1, N, 1)) - - -# 2 -import sys - -n = int(input()) -arr = [int(sys.stdin.readline()) for __ in range(n)] -dp = [[0 for __ in range(n+1)]for __ in range(n+1)] - -dp[1][0] = arr[-1] -dp[1][1] = arr[0] - -for i in range(2,n+1): - for j in range(i+1): - if i == j: - dp[i][j] = dp[i-1][j-1] + i*arr[j-1] - elif j != 0: - dp[i][j] = max(dp[i-1][j] + i*arr[-(i-j)], dp[i-1][j-1] + i*arr[j-1]) - else: - dp[i][j] = dp[i-1][j] + i*arr[-i] - -print(max(dp[-1])) - - -# 3 -import sys -input = sys.stdin.readline - -N = int(input()) -v = [0]+[int(input()) for _ in range(N)] -dp = [[v[i] * N if i == j else 0 for i in range(N + 1)] for j in range(N + 1)] - -for left in range(1, N + 1): - for right in range(left - 1, 0, -1): - dp[right][left] = max(dp[right + 1][left] + v[right] * (N - left + right), dp[right][left - 1] + v[left]*(N - left + right)) - -print(dp[1][N]) \ No newline at end of file diff --git "a/18234\353\213\271\352\267\274\355\233\224\354\263\220\353\250\271\352\270\260.py" "b/18234\353\213\271\352\267\274\355\233\224\354\263\220\353\250\271\352\270\260.py" deleted file mode 100644 index 14f2c4b..0000000 --- "a/18234\353\213\271\352\267\274\355\233\224\354\263\220\353\250\271\352\270\260.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -N, T = map(int, input().split()) -w_ps = [list(map(int, input().split())) for _ in range(N)] -w_ps.sort(key = lambda x: x[1],reverse=True) - -answer = 0 -for w, p in w_ps: - answer += (w + p*(T-1)) - T -= 1 -print(answer) - diff --git a/18243smallworldnetwork.py b/18243smallworldnetwork.py deleted file mode 100644 index ce0e44d..0000000 --- a/18243smallworldnetwork.py +++ /dev/null @@ -1,28 +0,0 @@ -from collections import deque - -def bfs(node): - q = deque() - q.append(node) - check[node] = 0 - while q: - node = q.popleft() - for n in graph[node]: - if check[n] == -1: - q.append(n) - check[n] = check[node]+1 - -N, K = map(int, input().split()) -graph = [[] for _ in range(N+1)] -check = [-1]*(N+1) -for _ in range(K): - u, v = map(int, input().split()) - graph[u].append(v) - graph[v].append(u) -ok = 1 -for i in range(1, N+1): - check = [-1]*(N+1) - bfs(i) - if (max(check) > 6) or (-1 in check[1:]): - ok = 0 - break -print("Small World!" if ok else "Big World!") \ No newline at end of file diff --git "a/18290 NM\352\263\274 K(1).py" "b/18290 NM\352\263\274 K(1).py" deleted file mode 100644 index e4260cb..0000000 --- "a/18290 NM\352\263\274 K(1).py" +++ /dev/null @@ -1,95 +0,0 @@ -def dfs(now_i, now_j, level, now_sum): - if level == K: - global res - res = max(res, now_sum) - return - - for near_i, near_j in near_idx: - temp_i, temp_j = now_i+near_i, now_j+near_j - if temp_i0 and bit&(1 | (1<<(m-1))): continue - if j==0 and bit&(1<<(m-1)): continue - nval = dp[ch][bit] + grid[i][j] - new[ch+1][nbit|1] = max(new[ch+1][nbit|1], nval) - dp = new -print(max(dp[k])) diff --git "a/18291\353\271\204\354\232\224\353\234\250\354\235\230 \354\247\225\352\262\200\353\213\244\353\246\254 \352\261\264\353\204\210\352\270\260.py" "b/18291\353\271\204\354\232\224\353\234\250\354\235\230 \354\247\225\352\262\200\353\213\244\353\246\254 \352\261\264\353\204\210\352\270\260.py" deleted file mode 100644 index b98d7d7..0000000 --- "a/18291\353\271\204\354\232\224\353\234\250\354\235\230 \354\247\225\352\262\200\353\213\244\353\246\254 \352\261\264\353\204\210\352\270\260.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**6) - -def pow(n): - if n<=0: - return 1 - p_n = pow(n//2) - if n&1: - return p_n*p_n*2%MOD - return p_n*p_n%MOD - - -MOD = int(1e9)+7 -for _ in range(int(input())): - N = int(input()) - # 2~N-1 번의 징검다리를 선택하거나 선택하지 않는 모든 경우의 수. - print((pow(N-2))%MOD) \ No newline at end of file diff --git "a/18311\354\231\225\353\263\265.py" "b/18311\354\231\225\353\263\265.py" deleted file mode 100644 index f2f7016..0000000 --- "a/18311\354\231\225\353\263\265.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int,input().split()) -cources = list(map(int,input().split())) -dp = [0]*(2*N) -dp[0] = cources[0] -if K < dp[0]: - print(1) - exit() - -for i in range(1,2*N): - if i K: - print(i+1) - exit() - if i>=N: - dp[i] = dp[i-1] + cources[N-i%N-1] - if dp[i] > K: - print(N-i%N) - exit() \ No newline at end of file diff --git "a/18352\355\212\271\354\240\225\352\261\260\353\246\254\354\235\230\353\217\204\354\213\234\354\260\276\352\270\260.py" "b/18352\355\212\271\354\240\225\352\261\260\353\246\254\354\235\230\353\217\204\354\213\234\354\260\276\352\270\260.py" deleted file mode 100644 index 5af0047..0000000 --- "a/18352\355\212\271\354\240\225\352\261\260\353\246\254\354\235\230\353\217\204\354\213\234\354\260\276\352\270\260.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def dijkstra(start): - queue = deque() - queue.append([0,start]) - visited = {i: float('inf') for i in range(1,N+1)} - visited[start] = 0 - while queue: - cur_dist,cur_node = queue.popleft() - for next in graph[cur_node]: - if visited[next] > cur_dist+1: - visited[next] = cur_dist+1 - queue.append([visited[next], next]) - return visited -N, M, K, X = map(int, input().split()) -graph = {i: [] for i in range(1,N+1)} -for _ in range(M): - a, b = map(int, input().split()) - graph[a] += [b] - -dists_table = dijkstra(X) -flag=0 -for i in range(1,N+1): - if dists_table[i]==K: - print(i) - flag=1 -if not flag: - print(-1) \ No newline at end of file diff --git "a/18353\353\263\221\354\202\254\353\260\260\354\271\230\355\225\230\352\270\260.py" "b/18353\353\263\221\354\202\254\353\260\260\354\271\230\355\225\230\352\270\260.py" deleted file mode 100644 index d3d665b..0000000 --- "a/18353\353\263\221\354\202\254\353\260\260\354\271\230\355\225\230\352\270\260.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -N = int(input()) -arr = list(map(int, input().split())) -q = [] -q.append(-arr[0]) -for i in range(1,N): - if -arr[i] > q[-1]: - q.append(-arr[i]) - else: - q[bisect_left(q,-arr[i])] = -arr[i] -print(N-len(q)) diff --git "a/18427 \355\225\250\352\273\230 \353\270\224\353\241\235 \354\214\223\352\270\260.py" "b/18427 \355\225\250\352\273\230 \353\270\224\353\241\235 \354\214\223\352\270\260.py" deleted file mode 100644 index ab687b5..0000000 --- "a/18427 \355\225\250\352\273\230 \353\270\224\353\241\235 \354\214\223\352\270\260.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M, H = map(int, input().split()) -boxes = [list(map(int, input().split())) for _ in range(N) ] -dp = [0]*(H+1) - -for box in boxes: - for idx in range(H,0,-1): - if not dp[idx]: continue - for num in box: - if idx + num > H: continue - dp[idx+num] += dp[idx] - for num in box: - dp[num] += 1 -print(dp[H]%10007) \ No newline at end of file diff --git "a/18429\352\267\274\354\206\220\354\213\244.py" "b/18429\352\267\274\354\206\220\354\213\244.py" deleted file mode 100644 index c67a7b4..0000000 --- "a/18429\352\267\274\354\206\220\354\213\244.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - - -def dfs(depth, weight): - if depth == N: - return 1 - ret = 0 - for i in range(N): - next_weight = weight - K + a[i] - if not check[i] and next_weight >= 500: - check[i] = True - ret += dfs(depth + 1, next_weight) - check[i] = False - return ret - -N, K = map(int, input().split()) -a = list(map(int, input().split())) -check = {i: False for i in range(N)} - -print(dfs(0, 500)) \ No newline at end of file diff --git "a/18430 \353\254\264\352\270\260\352\263\265\355\225\231.py" "b/18430 \353\254\264\352\270\260\352\263\265\355\225\231.py" deleted file mode 100644 index 7ca6d13..0000000 --- "a/18430 \353\254\264\352\270\260\352\263\265\355\225\231.py" +++ /dev/null @@ -1,154 +0,0 @@ -import sys -input = sys.stdin.readline - - -def dfs(x, y): - - # 아래 끝까지 내려 온 경우 0을 반환 - if x == n: - return 0 - - # 오른쪽 끝까지 이동한 경우 아래로 한 칸 내려가기 - if y == m: - return dfs(x + 1, 0) - result = 0 - - # (x, y)를 기준으로 1번째 모양 - if x + 1 < n and y + 1 < m and v[x][y] + v[x][y + 1] + v[x + 1][y + 1] == 0: - v[x][y] = v[x][y + 1] = v[x + 1][y + 1] = True - result = max(result, dfs(x, y + 1) + - (board[x][y] + 2 * board[x][y + 1] + board[x + 1][y + 1])) - v[x][y] = v[x][y + 1] = v[x + 1][y + 1] = False - - # (x, y)를 기준으로 2번째 모양 - if x + 1 < n and y + 1 < m and v[x][y + 1] + v[x + 1][y] + v[x + 1][y + 1] == 0: - v[x][y + 1] = v[x + 1][y] = v[x + 1][y + 1] = True - result = max(result, dfs( - x, y + 1) + (board[x][y + 1] + board[x + 1][y] + 2 * board[x + 1][y + 1])) - v[x][y + 1] = v[x + 1][y] = v[x + 1][y + 1] = False - - # (x, y)를 기준으로 3번째 모양 - if x + 1 < n and y + 1 < m and v[x][y] + v[x + 1][y] + v[x + 1][y + 1] == 0: - v[x][y] = v[x + 1][y] = v[x + 1][y + 1] = True - result = max(result, dfs(x, y + 1) + - (board[x][y] + 2 * board[x + 1][y] + board[x + 1][y + 1])) - v[x][y] = v[x + 1][y] = v[x + 1][y + 1] = False - - # (x, y)를 기준으로 4번째 모양 - if x + 1 < n and y + 1 < m and v[x][y] + v[x][y + 1] + v[x + 1][y] == 0: - v[x][y] = v[x][y + 1] = v[x + 1][y] = True - result = max(result, dfs(x, y + 1) + - (2 * board[x][y] + board[x][y + 1] + board[x + 1][y])) - v[x][y] = v[x][y + 1] = v[x + 1][y] = False - - # 현재 위치를 기준으로 부메랑을 만들지 않는 경우 - result = max(result, dfs(x, y + 1)) - return result - - -n, m = map(int, input().split()) -board = [list(map(int, input().split())) for _ in range(n)] -v = [[False] * m for _ in range(n)] - -print(dfs(0, 0)) - - - -# 2 -N, M = map(int, input().strip().split()) -board = [list(map(int, input().strip().split())) for _ in range(N)] -used = [[0 for _ in range(M)] for _ in range(N)] -dy = [[0, 1], [0, -1], [-1, 0], [0, 1]] -dx = [[-1, 0], [-1, 0], [0, 1], [1, 0]] -answer = 0 - - -def traverse(power, cy, cx): - global answer - - for y in range(cy, N): - for x in range(cx if y == cy else 0, M): - if used[y][x] == 1: - continue - for i in range(4): - flag = True - for j in range(2): - ny, nx = y + dy[i][j], x + dx[i][j] - - if 0 > ny or ny >= N or nx < 0 or nx >= M or used[ny][nx] == 1: - flag = False - break - if flag is True: - total = 0 - used[y][x] = 1 - for j in range(2): - ny, nx = y + dy[i][j], x + dx[i][j] - used[ny][nx] = 1 - total += board[ny][nx] - traverse(power + total + board[y][x] * 2, y if x + 1 < M else y + 1, x + 1 if x + 1 < M else 0) - for j in range(2): - ny, nx = y + dy[i][j], x + dx[i][j] - used[ny][nx] = 0 - used[y][x] = 0 - answer = max(answer, power) - -traverse(0, 0, 0) -print(answer) - - - -# 3 -import sys, copy - -input = sys.stdin.readline - - -def dfs(dx, dy, sum_pre): - global max_value - if dy >= M - 1: - dx += 1 - dy = 0 - if dx >= N - 1: - max_value = max(max_value, sum_pre) - return - - for Next in [s0, s1, s2, s3, s4]: - if Next == 0: - dfs(dx, dy + 1, sum_pre) - else: - flag = True - total_sum = 0 - for k in range(2): - for l in range(2): - if Next[k][l] != 0: - if flag and Next[k][l] * dp[dx + k][dy + l] != 0: - total_sum += Next[k][l] * dp[dx + k][dy + l] - else: - flag = False - total_sum = 0 - if flag: - for k in range(2): - for l in range(2): - if Next[k][l] != 0: - dp[dx + k][dy + l] = 0 - dfs(dx, dy + 1, sum_pre + total_sum) - for k in range(2): - for l in range(2): - if Next[k][l] != 0: - dp[dx + k][dy + l] = board[dx + k][dy + l] - - -N, M = map(int, input().split()) -board = [list(map(int, input().split())) for _ in range(N)] - -s0 = 0 -s1 = [[1, 2], [0, 1]] -s2 = [[0, 1], [1, 2]] -s3 = [[1, 0], [2, 1]] -s4 = [[2, 1], [1, 0]] - -max_value = 0 -dp = [row[:] for row in board] -dfs(0, 0, 0) - -print(max_value) \ No newline at end of file diff --git "a/1849\354\210\234\354\227\264.py" "b/1849\354\210\234\354\227\264.py" deleted file mode 100644 index 1505fcc..0000000 --- "a/1849\354\210\234\354\227\264.py" +++ /dev/null @@ -1,47 +0,0 @@ -import sys -input = sys.stdin.readline -import math - -def init(node,start,end): - if start==end: - tree[node]=1 - return 1 - - mid=(start+end)//2 - tree[node]=init(node*2,start,mid)+init(node*2+1,mid+1,end) - return tree[node] - -def query(node,start,end,val): - tree[node]-=1 - - if start==end: - return start - mid = (start + end) // 2 - if tree[node*2]>=val: - return query(node*2,start,mid,val) - return query(node*2+1,mid+1,end,val-tree[node*2]) - -def update(node,start,end,indx): - if not start<=indx<=end: - return - - tree[node] -= 1 - if start==end: - return - - mid=(start+end)//2 - update(node*2,start,mid,indx) - update(node*2+1,mid+1,end,indx) - -N=int(input()) -size=2**(math.ceil(math.log(N,2))+1) -tree=[0 for i in range(size)] -L=[0 for i in range(N+1)] -init(1,1,N) - -for i in range(1,N+1): - indx=query(1,1,N,int(input().rstrip())+1) - L[indx]=i - -for i in range(1,N+1): - print(L[i]) diff --git "a/18500\353\257\270\353\204\244\353\236\2042.py" "b/18500\353\257\270\353\204\244\353\236\2042.py" deleted file mode 100644 index 2b96e46..0000000 --- "a/18500\353\257\270\353\204\244\353\236\2042.py" +++ /dev/null @@ -1,93 +0,0 @@ -import sys -from collections import deque -input = sys.stdin.readline - -dx = [1, -1, 0, 0] -dy = [0, 0, 1, -1] - -def destroy(i, left): - i, j = r - i, 0 - if left == 1: - for k in range(c): - if a[i][k] == 'x': - a[i][k] = '.' - j = k - break - else: - for k in range(c-1, -1, -1): - if a[i][k] == 'x': - a[i][k] = '.' - j = k - break - - for k in range(4): - ni = i + dx[k] - nj = j + dy[k] - if 0 <= ni < r and 0 <= nj < c: - if a[ni][nj] == 'x': - dq.append([ni, nj]) - -def bfs(x, y): - q = deque() - check = [[0]*c for _ in range(r)] - fall_list = [] - q.append([x, y]) - check[x][y] = 1 - while q: - x, y = q.popleft() - if x == r-1: - return - if a[x+1][y] == '.': - fall_list.append([x, y]) - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0 <= nx < r and 0 <= ny < c: - if a[nx][ny] == 'x' and not check[nx][ny]: - check[nx][ny] = 1 - q.append([nx, ny]) - - fall(check, fall_list) - -def fall(check, fall_list): - k, flag = 1, 0 - while True: - for i, j in fall_list: - if i + k == r-1: - flag = 1 - break - if a[i+k+1][j] == 'x' and not check[i+k+1][j]: - flag = 1 - break - if flag: - break - k += 1 - - for i in range(r-2, -1, -1): - for j in range(c): - if a[i][j] == 'x' and check[i][j]: - a[i][j] = '.' - a[i+k][j] = 'x' - -r, c = map(int, input().split()) -a = [list(input().strip()) for _ in range(r)] -n = int(input()) -s = list(map(int, input().split())) -dq = deque() - -left = 1 -while n: - index = s.pop(0) - destroy(index, left) - - while dq: - x, y = dq.popleft() - bfs(x, y) - - left *= -1 - n -= 1 - -for i in range(r): - for j in range(c): - print(a[i][j], end='') - print() \ No newline at end of file diff --git "a/1865\354\233\234\355\231\200.py" "b/1865\354\233\234\355\231\200.py" deleted file mode 100644 index 77a65e5..0000000 --- "a/1865\354\233\234\355\231\200.py" +++ /dev/null @@ -1,35 +0,0 @@ -INF = 123_456_789 - -tc = int(input()) -for _ in range(tc): - n, m, w = map(int, input().split()) - connect = [] - for _ in range(m): - a, b, k = map(int, input().split()) - connect.append((a, b, k)) - connect.append((b, a, k)) - for _ in range(w): - a, b, k = map(int, input().split()) - connect.append((a, b, -k)) - - def bellman_ford(start_node): - global n - dist = {node: INF for node in range(1, n + 1)} - dist[start_node] = 0 - - for _ in range(n - 1): - for src_node, tgt_node, connect_time in connect: - if dist[src_node] + connect_time < dist[tgt_node]: - dist[tgt_node] = dist[src_node] + connect_time - - for src_node, tgt_node, connect_time in connect: - # occur renewel dist again. - if dist[src_node] + connect_time < dist[tgt_node]: - return True - return False - - if bellman_ford(1): - print("YES") - else: - print("NO") - \ No newline at end of file diff --git "a/18808\354\212\244\355\213\260\354\273\244 \353\266\231\354\235\264\352\270\260.py" "b/18808\354\212\244\355\213\260\354\273\244 \353\266\231\354\235\264\352\270\260.py" deleted file mode 100644 index 3c93855..0000000 --- "a/18808\354\212\244\355\213\260\354\273\244 \353\266\231\354\235\264\352\270\260.py" +++ /dev/null @@ -1,51 +0,0 @@ -import sys -input = sys.stdin.readline - - -# 검사하기 -def is_matching(x, y, sticker, R, C): - for i in range(x, x+R): - for j in range(y, y+C): - if notebook[i][j] and sticker[i-x][j-y]: - return False - for i in range(x, x+R): - for j in range(y, y+C): - if sticker[i-x][j-y]: - notebook[i][j]=1 - return True - - -# 검사 시작지점 찾기. -def find_sticker_start(sticker, R, C): - for i in range(N-R+1): - for j in range(M-C+1): - if is_matching(i, j, sticker, R, C): - return True - return False - - -def turn_sticker(sticker): - sticker = [k[::-1] for k in zip(*sticker)] - return sticker - - -N, M, K = map(int, input().split()) -notebook = [[0 for _ in range(M)] for _ in range(N)] -for _ in range(K): - R, C = map(int, input().split()) - sticker = [list(map(int, input().split())) for _ in range(R)] - - # 스티커를 노트북에 붙일수 있는가 검사. - for _ in range(4): - if find_sticker_start(sticker, R, C): - break # 가능? 붙히고 회전 종료. - else: # 불가능? 90도 회전 - sticker = turn_sticker(sticker) - R, C = C, R - -# 모든 스티커 부착이 끝나면 칸수 세어보기. -sum_sticker = 0 -for i in range(N): - sum_sticker += sum(notebook[i]) -print(sum_sticker) - diff --git "a/18870\354\242\214\355\221\234\354\225\225\354\266\225.py" "b/18870\354\242\214\355\221\234\354\225\225\354\266\225.py" deleted file mode 100644 index d4e8486..0000000 --- "a/18870\354\242\214\355\221\234\354\225\225\354\266\225.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -N = int(input()) -arr = list(map(int, input().split())) -arr2 = sorted(list(set(arr))) -for num in arr: - print(bisect_left(arr2,num),end=' ') - diff --git "a/1890 \354\240\220\355\224\204.py" "b/1890 \354\240\220\355\224\204.py" deleted file mode 100644 index fdde010..0000000 --- "a/1890 \354\240\220\355\224\204.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -board = [list(map(int, input().split())) for _ in range(N)] -dp = [[0] * N for _ in range(N)] -dp[0][0] = 1 - -for row in range(N): - for col in range(N): - if not board[row][col]: - continue - jump = board[row][col] - if col + jump < N: - dp[row][col + jump] += dp[row][col] - if row + jump < N: - dp[row + jump][col] += dp[row][col] -print(dp[N - 1][N - 1]) \ No newline at end of file diff --git "a/1895\355\225\204\355\204\260.py" "b/1895\355\225\204\355\204\260.py" deleted file mode 100644 index caa2a57..0000000 --- "a/1895\355\225\204\355\204\260.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline - - -def check_mid(x, y): - tmp = [] - for i in range(x, x + 3): - for j in range(y, y + 3): - if tmp: - if tmp[-1] <= filters[i][j]: - tmp.append(filters[i][j]) - else: - for k in range(len(tmp)): - if filters[i][j] < tmp[k]: - tmp.insert(k, filters[i][j]) - break - else: - tmp.append(filters[i][j]) - if tmp[4] >= T: - return True - return False - - -R, C = map(int, input().split()) -filters = [list(map(int, input().split())) for __ in range(R)] -T = int(input()) - -cnt = 0 -for i in range(R - 2): - for j in range(C - 2): - if check_mid(i, j): - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/1913\353\213\254\355\214\275\354\235\264.py" "b/1913\353\213\254\355\214\275\354\235\264.py" deleted file mode 100644 index 8fd81e1..0000000 --- "a/1913\353\213\254\355\214\275\354\235\264.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -sys.stdin.readline - - -def make_snail(n): - global t_x,t_y - dx = [1, 0, -1, 0] - dy = [0, 1, 0, -1] - complete_snail = [[0 for _ in range(n)] for _ in range(n)] - - # 0,0 에서 초기화 - cnt = n**2 - direction = 0 - x, y = 0, 0 - complete_snail[x][y] = cnt - cnt -= 1 - # cnt 가 모든 칸에 기록될때까지 - while cnt > 0: - - nx = x + dx[direction] - ny = y + dy[direction] - - if 0 <= nx < n and 0 <= ny < n and not complete_snail[nx][ny]: - complete_snail[nx][ny] = cnt - if cnt==target: - t_x,t_y = nx,ny - x, y = nx, ny - cnt -= 1 - else: # 진입 못하면 방향 시계방향 전환 - direction = (direction+1) % 4 - return complete_snail - - -N = int(input()) -target = int(input()) -t_x,t_y = 0,0 -snail = make_snail(N) -for row in snail: - print(*row) -print(t_x+1,t_y+1) diff --git "a/1915\352\260\200\354\236\245\355\201\260\354\240\225\354\202\254\352\260\201\355\230\225.py" "b/1915\352\260\200\354\236\245\355\201\260\354\240\225\354\202\254\352\260\201\355\230\225.py" deleted file mode 100644 index ba0e4aa..0000000 --- "a/1915\352\260\200\354\236\245\355\201\260\354\240\225\354\202\254\352\260\201\355\230\225.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M = map(int,input().split()) -square = [list(map(int,list(input().rstrip()))) for _ in range(N)] -dp = [[0]*(M+1) for _ in range(N+1)] -# 위 왼 대각 왼쪽 위가 0이면 1부터 다시 시작함. -# 어디 하나라도 짧으면 그 길이가 최대길이로 저장됨.(정사각형을 만들수있는 최대길이.) -max_length = 0 -for i in range(1,N+1): - for j in range(1,M+1): - if square[i-1][j-1]: - dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1 - if dp[i][j] > max_length: - max_length = dp[i][j] - -print(max_length**2) \ No newline at end of file diff --git "a/1918_\355\233\204\354\234\204\355\221\234\352\270\260.py" "b/1918_\355\233\204\354\234\204\355\221\234\352\270\260.py" index 040407e..ebc68c6 100644 --- "a/1918_\355\233\204\354\234\204\355\221\234\352\270\260.py" +++ "b/1918_\355\233\204\354\234\204\355\221\234\352\270\260.py" @@ -1,28 +1,28 @@ - -a = input() -stack = [] #스택 -res='' #출력 - -for x in a: - if x.isalpha(): #피연산자인지 아닌지 확인 - res+=x - else: - if x == '(': - stack.append(x) - elif x == '*' or x =='/': - while stack and (stack[-1]=='*' or stack[-1]=='/'): - res+=stack.pop() - stack.append(x) - elif x == '+' or x == '-': - while stack and stack[-1] != '(': - res += stack.pop() - stack.append(x) - elif x == ')': - while stack and stack[-1] != '(': - res+=stack.pop() - stack.pop() - -#스택안에 남아있는 값들 pop -while stack: - res += stack.pop() + +a = input() +stack = [] #스택 +res='' #출력 + +for x in a: + if x.isalpha(): #피연산자인지 아닌지 확인 + res+=x + else: + if x == '(': + stack.append(x) + elif x == '*' or x =='/': + while stack and (stack[-1]=='*' or stack[-1]=='/'): + res+=stack.pop() + stack.append(x) + elif x == '+' or x == '-': + while stack and stack[-1] != '(': + res += stack.pop() + stack.append(x) + elif x == ')': + while stack and stack[-1] != '(': + res+=stack.pop() + stack.pop() + +#스택안에 남아있는 값들 pop +while stack: + res += stack.pop() print(res) \ No newline at end of file diff --git "a/1918\355\233\204\354\234\204\355\221\234\352\270\260\354\213\235.py" "b/1918\355\233\204\354\234\204\355\221\234\352\270\260\354\213\235.py" deleted file mode 100644 index 47cca70..0000000 --- "a/1918\355\233\204\354\234\204\355\221\234\352\270\260\354\213\235.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline - -string = input() -stack = [] #스택 -res='' #출력 - -for ch in string: - if ch.isalpha(): #피연산자인지 아닌지 확인 - res+=ch - else: - if ch == '(': - stack.append(ch) - elif ch == '*' or ch =='/': #안에꺼 다 빼고 넣음(그 자리에서 연산하기 위해서) -> 연산 우선순위가 있기 때문에 안에있는애들을 다빼야 제자리에 들어갈 수 있음. - while stack and (stack[-1]=='*' or stack[-1]=='/'): - res+=stack.pop() - stack.append(ch) - elif ch == '+' or ch == '-': #괄호 닫힐때 연산 - while stack and stack[-1] != '(': - res += stack.pop() - stack.append(ch) - elif ch == ')': #닫히면 괄호 없어질때까지 출력(연산) - while stack and stack[-1] != '(': - res+=stack.pop() - stack.pop() - -#스택안에 남아있는 값들 pop -while stack: - res += stack.pop() -print(res) \ No newline at end of file diff --git "a/1920 \354\210\230 \354\260\276\352\270\260.py" "b/1920 \354\210\230 \354\260\276\352\270\260.py" deleted file mode 100644 index 6bef413..0000000 --- "a/1920 \354\210\230 \354\260\276\352\270\260.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -num_set = {} -N = int(input()) -A = list(map(int, input().split())) -for num in A: - num_set[num] = True -M = int(input()) -Q = list(map(int, input().split())) -for num in Q: - if num in num_set: - print(1) - else: - print(0) \ No newline at end of file diff --git "a/1922\353\204\244\355\212\270\354\233\214\355\201\254\354\227\260\352\262\260.py" "b/1922\353\204\244\355\212\270\354\233\214\355\201\254\354\227\260\352\262\260.py" index 7cd94ca..fbc1539 100644 --- "a/1922\353\204\244\355\212\270\354\233\214\355\201\254\354\227\260\352\262\260.py" +++ "b/1922\353\204\244\355\212\270\354\233\214\355\201\254\354\227\260\352\262\260.py" @@ -1,34 +1,34 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -M = int(input()) - -# 간선정보 정렬 완료. -edge = [list(map(int,input().split())) for _ in range(M)] -edge.sort(key = lambda x : x[2]) - -parent = [i for i in range(N+2)] - -def find(x): - if x == parent[x]: - return x - parent[x] = find(parent[x]) - return parent[x] - -def union(x,y): - x = find(x) - y = find(y) - - parent[x] = y - - - -# MST그리기. -cost = 0 -for a,b,c in edge: - if find(a) != find(b): - union(a,b) - cost += c - +import sys +input = sys.stdin.readline + +N = int(input()) +M = int(input()) + +# 간선정보 정렬 완료. +edge = [list(map(int,input().split())) for _ in range(M)] +edge.sort(key = lambda x : x[2]) + +parent = [i for i in range(N+2)] + +def find(x): + if x == parent[x]: + return x + parent[x] = find(parent[x]) + return parent[x] + +def union(x,y): + x = find(x) + y = find(y) + + parent[x] = y + + + +# MST그리기. +cost = 0 +for a,b,c in edge: + if find(a) != find(b): + union(a,b) + cost += c + print(cost) \ No newline at end of file diff --git "a/19237\354\226\264\353\245\270\354\203\201\354\226\264.py" "b/19237\354\226\264\353\245\270\354\203\201\354\226\264.py" deleted file mode 100644 index 4f4046b..0000000 --- "a/19237\354\226\264\353\245\270\354\203\201\354\226\264.py" +++ /dev/null @@ -1,72 +0,0 @@ -import sys -input = sys.stdin.readline - -# 상어 1~M까지 번호 -# 상어들은 냄새를 뿌린다 / 1초마다 사방중 하나로 이동한다. / 냄새는 상어가 k번 이동하고 사라진다. -# 이동방향은 인접한 칸 중 아무 냄새가 없는 칸의 방향으로 잡고 그런 칸이 없으면 자신의 냄새가 있는 칸의 방향으로 잡는다. -# 자신의 냄새가 여러개일 경우 특정 우선순위를 기준으로 방향을 잡는다. -# 상어가 이동한 후 한칸에 여러마리 상어가 있으면 가장 작은 번호 상어만 살아남고 나머지는 사라진다. -N,M,K = map(int,input().split()) -maps = [list(map(int,input().split())) for _ in range(N)] -init_dir = list(map(int,input().split())) -priority_dir = {i:[list(map(int,input().split())) for _ in range(4)] for i in range(1,M+1)} -status_map = [[[0,0] for _ in range(N)] for _ in range(N)] -# 상어의 초기 상태값 -shark_status = {} -for i in range(N): - for j in range(N): - if maps[i][j]: - shark_status[maps[i][j]] = [i,j,init_dir[maps[i][j]-1]] - status_map[i][j][0] = maps[i][j] - status_map[i][j][1] = K - -dx = [0,-1,1,0] -dy = [1,0,0,-1] -# 상어를 1번부터 순서대로 움직여야하고 이미 그 위치에 다른 상어가 있다면 사망. -shark_cnt = M -time=1 -while shark_cnt !=1: # 상어 한마리 될때까지 조사. - if time>1000: - print(-1) - exit() - for shark in range(1,M+1): - x,y,dir = shark_status[shark] - if maps[x][y] == shark: # 상어 살아있으면 조사. - dir_set = priority_dir[shark][dir-1] - for next_dir in dir_set: - next_x = x + dx[next_dir%4] - next_y = y + dy[next_dir%4] - if 0<=next_x 0: - y, x, dir = shark_self_smell.pop(0) - current_shark_loc[shark_num] = [y, x, shark_num] - current_dir[shark_num] = dir - if [y, x] not in shark_location_hist: - shark_location_hist.append([y, x]) - -def smell_timer(): - tmp_shark_location_hist = [] - for i, j in shark_location_hist: - if smell_time[i][j] > 0: - smell_time[i][j] -= 1 - if smell_time[i][j] == 0: - smell_shark[i][j] = -1 - smell_time[i][j] = 0 - else: - tmp_shark_location_hist.append([i, j]) - return tmp_shark_location_hist - -N, M, K = map(int, sys.stdin.readline().split()) -# N : 가로세로 , M : 상어 수, K : 최대 이동 수 -maps = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] -current_dir = list(map(int, sys.stdin.readline().split())) -time_cnt = 0 -shark_prior_dir = [list(map(int, sys.stdin.readline().split())) for _ in range(M * 4)] -current_shark_loc = [[] for _ in range(M)] -smell_shark = [[-1] * N for _ in range(N)] -smell_time = [[0] * N for _ in range(N)] - -shark_location_hist = [] -shark_list = [i for i in range(M)] -dy = [-1, 1, 0, 0] -dx = [0, 0, -1, 1] - -for i in range(N): - for j in range(N): - if maps[i][j] > 0: - current_shark_loc[maps[i][j] - 1] = [i, j, maps[i][j] - 1] - smell_shark[i][j] = maps[i][j] - 1 - smell_time[i][j] = K - shark_location_hist.append([i, j]) - -while 1: - if time_cnt >= 1000: - print(-1) - sys.exit() - break - - delete_list = [] - for i in range(len(shark_list) - 1, -1, -1): - # 살아있는 shark들만 move - move(shark_list[i]) - shark_location_hist = smell_timer() - for i in range(len(shark_list) - 1, -1, -1): - y, x, shark_num = current_shark_loc[shark_list[i]] - if smell_shark[y][x] > 0 and smell_shark[y][x] != shark_num: - target_num = smell_shark[y][x] - for i in range(len(shark_list) - 1, -1, -1): - if shark_list[i] == target_num: - shark_list.pop(i) - break - smell_shark[y][x] = shark_num - smell_time[y][x] = K - - if [y, x] not in shark_location_hist: - shark_location_hist.append([y, x]) - time_cnt += 1 - - if len(shark_list) == 1: break -print(time_cnt) \ No newline at end of file diff --git "a/19237\354\226\264\353\245\270\354\203\201\354\226\264_\353\202\250\354\235\230\354\275\224\353\223\2342.py" "b/19237\354\226\264\353\245\270\354\203\201\354\226\264_\353\202\250\354\235\230\354\275\224\353\223\2342.py" deleted file mode 100644 index e1c1fe4..0000000 --- "a/19237\354\226\264\353\245\270\354\203\201\354\226\264_\353\202\250\354\235\230\354\275\224\353\223\2342.py" +++ /dev/null @@ -1,81 +0,0 @@ -import sys - -input = sys.stdin.readline -dx = [0, -1, 1, 0, 0] -dy = [0, 0, 0, -1, 1] - -n, m, k = map(int, input().split()) - -maps, shark = [], [[] for _ in range(m)] -for i in range(n): - maps.append(list(map(int, input().split()))) - for j in range(n): - if maps[i][j]: - shark[maps[i][j]-1].extend([i, j]) - maps[i][j] = [maps[i][j], k] - -cur_dir = list(map(int, input().split())) -for i in range(m): - shark[i].append(cur_dir[i]) - -priority_dir = [[] for _ in range(m)] -idx = -1 -for i in range(4*m): - if i % 4 == 0: - idx += 1 - priority_dir[idx].append(list(map(int, input().split()))) - -ans = 0 -while True: - ans += 1 - if ans == 1001: - print(-1) - break - - check = [[0 for _ in range(n)] for _ in range(n)] - for i in range(m): - # 상어가 살아있을 떄 - if shark[i] != 0: - x, y, cur_dir, flag = shark[i][0], shark[i][1], shark[i][2], 0 - for j in range(4): - next_dir = priority_dir[i][cur_dir-1][j] - nx, ny = x + dx[next_dir], y + dy[next_dir] - if 0 <= nx < n and 0 <= ny < n: - # 이동 가능하면 이동 - if maps[nx][ny] == 0: - flag = 1 - break - # 이동 불가능하면 기록한 상어 번호가 나랑 같은 놈한테로 이동. - if flag == 0: - for j in range(4): - next_dir = priority_dir[i][cur_dir-1][j] - nx, ny = x + dx[next_dir], y + dy[next_dir] - if 0 <= nx < n and 0 <= ny < n: - if maps[nx][ny][0] == i+1: - break - # 그 자리에 있는 상어가 나보다 작은넘이면 죽인다. - if check[nx][ny]: - if check[nx][ny] < i+1: - shark[i] = 0 - else: - shark[check[nx][ny]-1] = 0 - else: - check[nx][ny] = i+1 - shark[i] = [nx, ny, next_dir] - - # 한바퀴 돌면서 냄새 -1시켜주고 0이면 자리 비워줌. - for i in range(n): - for j in range(n): - if maps[i][j]: - maps[i][j][1] -= 1 - if maps[i][j][1] == 0: - maps[i][j] = 0 - # 상어가 이동한 위치에 최신화 시켜줌. - for i in range(m): - if shark[i]: - x, y = shark[i][0], shark[i][1] - maps[x][y] = [i+1, k] - # 상어가 죽은 마리수가 m-1마리면 종료 - if shark.count(0) == m-1: - print(ans) - break \ No newline at end of file diff --git "a/19238 \354\212\244\355\203\200\355\212\270\355\203\235\354\213\234.py" "b/19238 \354\212\244\355\203\200\355\212\270\355\203\235\354\213\234.py" deleted file mode 100644 index 80959b9..0000000 --- "a/19238 \354\212\244\355\203\200\355\212\270\355\203\235\354\213\234.py" +++ /dev/null @@ -1,71 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from heapq import heappush - - -def go_target(start_x, start_y, start_oil): - q = deque() - q.append((start_x, start_y, start_oil)) - visited = [[False] * N for __ in range(N)] - visited[start_x][start_y] = True - while q: - for __ in range(len(q)): - x, y, rest = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N and not maps[nx][ny] and not visited[nx][ny] and rest: - if (nx, ny) == passengers[(start_x, start_y)]: - del passengers[(start_x, start_y)] - rest -= 1 - new_oil = rest + 2 * (start_oil - rest) - return (nx, ny), new_oil - visited[nx][ny] = True - q.append((nx, ny, rest - 1)) - return 0, rest - - -def take_passenger(start_oil): - q = deque() - x, y = taxi - if taxi in passengers: - return go_target(x, y, start_oil) - q.append((x, y, start_oil)) - visited = [[False] * N for __ in range(N)] - visited[x][y] = True - sets = [] - while q: - for __ in range(len(q)): - x, y, rest = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N and not maps[nx][ny] and not visited[nx][ny] and rest: - if (nx, ny) in passengers: - heappush(sets, (nx, ny, rest - 1)) - visited[nx][ny] = True - q.append((nx, ny, rest - 1)) - if sets: - start_x, start_y, rest_oil = sets[0] - return go_target(start_x, start_y, rest_oil) - return 0, rest - - -N, M, oil = map(int, input().split()) -maps = [list(map(int, input().split())) for __ in range(N)] -taxi = tuple(map(lambda x: int(x)-1, input().split())) -passengers = {} -for _ in range(M): - a, b, c, d = map(int, input().split()) - if (a, b) == (c, d): - continue - passengers[(a-1, b-1)] = (c-1, d-1) - -delta = ((0, -1), (0, 1), (1, 0), (-1, 0)) - -while len(passengers): - if not taxi or not oil: - print(-1) - break - taxi, oil = take_passenger(oil) -else: - print(oil) \ No newline at end of file diff --git "a/1927\354\265\234\354\206\214\355\236\231.py" "b/1927\354\265\234\354\206\214\355\236\231.py" deleted file mode 100644 index eb70aea..0000000 --- "a/1927\354\265\234\354\206\214\355\236\231.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -N = int(input()) -heap=[] -for _ in range(N): - a = int(input()) - if a: - heappush(heap,a) - else: - if heap: - print(heappop(heap)) - else: - print(0) \ No newline at end of file diff --git "a/1929\354\206\214\354\210\230\354\260\276\352\270\260.py" "b/1929\354\206\214\354\210\230\354\260\276\352\270\260.py" index 0eea414..7161761 100644 --- "a/1929\354\206\214\354\210\230\354\260\276\352\270\260.py" +++ "b/1929\354\206\214\354\210\230\354\260\276\352\270\260.py" @@ -1,14 +1,14 @@ -def isPrime(num): - if num==1: - return False - else: - for i in range(2, int(num**0.5)+1): - if num%i == 0: - return False - return True - -M, N = map(int, input().split()) - -for i in range(M, N+1): - if isPrime(i): +def isPrime(num): + if num==1: + return False + else: + for i in range(2, int(num**0.5)+1): + if num%i == 0: + return False + return True + +M, N = map(int, input().split()) + +for i in range(M, N+1): + if isPrime(i): print(i) \ No newline at end of file diff --git "a/1931\355\232\214\354\235\230\354\213\244\353\260\260\354\240\225.py" "b/1931\355\232\214\354\235\230\354\213\244\353\260\260\354\240\225.py" deleted file mode 100644 index f7afc14..0000000 --- "a/1931\355\232\214\354\235\230\354\213\244\353\260\260\354\240\225.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -meet_table = [] -for _ in range(N): - start,end = map(int,input().split()) - meet_table.append([start,end]) -# end time이 빠르고 satrt time이 빠른 순서대로 정렬. -meet_table.sort(key=lambda x: (x[1],x[0])) -cnt=0 -end=0 -for i in range(N): - # 끝나는 시간보다 시작시간이 느리면 갱신. - if end <= meet_table[i][0]: - end = meet_table[i][1] - cnt+=1 -print(cnt) \ No newline at end of file diff --git "a/1934 \354\234\240\355\201\264\353\246\254\353\223\234\355\230\270\354\240\234\353\262\225.py" "b/1934 \354\234\240\355\201\264\353\246\254\353\223\234\355\230\270\354\240\234\353\262\225.py" index eee7528..2748e01 100644 --- "a/1934 \354\234\240\355\201\264\353\246\254\353\223\234\355\230\270\354\240\234\353\262\225.py" +++ "b/1934 \354\234\240\355\201\264\353\246\254\353\223\234\355\230\270\354\240\234\353\262\225.py" @@ -1,11 +1,12 @@ -import sys - -T = int(input()) -for test in range(T): - A, B = map(int, sys.stdin.readline().split()) - a, b = A, B - while b != 0: - a = a % b - a, b = b, a - #lcm - print(A*B//a) + +N = int(input()) +num = list(map(int,input().split())) +cnt = 0 + +for i in range(N): + for j in range(2,i): + if num[i]%j==0: + break + cnt+=1 + +print(cnt) \ No newline at end of file diff --git "a/1934\354\265\234\354\206\214\352\263\265\353\260\260\354\210\230.py" "b/1934\354\265\234\354\206\214\352\263\265\353\260\260\354\210\230.py" deleted file mode 100644 index 7928837..0000000 --- "a/1934\354\265\234\354\206\214\352\263\265\353\260\260\354\210\230.py" +++ /dev/null @@ -1,6 +0,0 @@ -from math import gcd - -for i in range(int(input())): - a,b = map(int,input().split()) - g = gcd(a,b) - print(a*b//g) \ No newline at end of file diff --git "a/1935_\355\233\204\354\234\204\355\221\234\352\270\260\354\213\235.py" "b/1935_\355\233\204\354\234\204\355\221\234\352\270\260\354\213\235.py" index e739d9e..b3f1895 100644 --- "a/1935_\355\233\204\354\234\204\355\221\234\352\270\260\354\213\235.py" +++ "b/1935_\355\233\204\354\234\204\355\221\234\352\270\260\354\213\235.py" @@ -1,33 +1,33 @@ - - -import sys -input = sys.stdin.readline - -n=int(input()) -str=input().rstrip() -nums=[0]*n -for i in range(n): - nums[i]=int(input().rstrip()) -stack=[] - -for ch in str: - #문자이면 - if ch.isupper(): - #nums[해당 문자의 아스키코드에 해당하는 index] - stack.append(nums[ord(ch)-ord('A')]) - #연산자이면 - else: - #뒤에 추가된 숫자먼저 빼오고 - #이전에 추가된 숫자빼오기 - num2=stack.pop() - num1=stack.pop() - if ch=='+': - stack.append(num1+num2) - elif ch=='-': - stack.append(num1-num2) - elif ch=='/': - stack.append(num1/num2) - elif ch=='*': - stack.append(num1*num2) -#소수점 두자리까지 출력하는 방법 + + +import sys +input = sys.stdin.readline + +n=int(input()) +str=input().rstrip() +nums=[0]*n +for i in range(n): + nums[i]=int(input().rstrip()) +stack=[] + +for ch in str: + #문자이면 + if ch.isupper(): + #nums[해당 문자의 아스키코드에 해당하는 index] + stack.append(nums[ord(ch)-ord('A')]) + #연산자이면 + else: + #뒤에 추가된 숫자먼저 빼오고 + #이전에 추가된 숫자빼오기 + num2=stack.pop() + num1=stack.pop() + if ch=='+': + stack.append(num1+num2) + elif ch=='-': + stack.append(num1-num2) + elif ch=='/': + stack.append(num1/num2) + elif ch=='*': + stack.append(num1*num2) +#소수점 두자리까지 출력하는 방법 print(f"{stack[0]:.2f}") \ No newline at end of file diff --git "a/1937 \354\232\225\354\213\254\354\237\201\354\235\264 \355\214\220\353\213\244.py" "b/1937 \354\232\225\354\213\254\354\237\201\354\235\264 \355\214\220\353\213\244.py" deleted file mode 100644 index fb3ea19..0000000 --- "a/1937 \354\232\225\354\213\254\354\237\201\354\235\264 \355\214\220\353\213\244.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**6) - - -def dfs(x, y): - # 이미 다른 조사에서 완료된 지점이면 패스 - if dp_dist[x][y]: - return dp_dist[x][y] - # 조사 안됐으면 1부터 시작. - dp_dist[x][y] = 1 - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0 <= nx < n and 0 <= ny < n: - # 거리가 작으면 들어간다. 약간 다익스트라를 쓰는 느낌. - if forest[x][y] < forest[nx][ny]: - dp_dist[x][y] = max(dp_dist[x][y], dfs(nx, ny) + 1) - return dp_dist[x][y] - - -n = int(input()) -forest = [list(map(int, input().split())) for i in range(n)] -dp_dist = [[0] * n for _ in range(n)] - -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] - -# 모든 점에서 조사. -max_move = 0 -for i in range(n): - for j in range(n): - max_move = max(max_move, dfs(i, j)) -print(max_move) \ No newline at end of file diff --git "a/1940 \354\243\274\353\252\275.py" "b/1940 \354\243\274\353\252\275.py" deleted file mode 100644 index 80929bf..0000000 --- "a/1940 \354\243\274\353\252\275.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -M = int(input()) -arr = sorted(map(int, input().split())) -left = 0 -right = N - 1 -answer = 0 -while left < right: - num = arr[left] + arr[right] - if num == M: - answer += 1 - left += 1 - right -= 1 - elif num > M: - right -= 1 - else: - left += 1 -print(answer) \ No newline at end of file diff --git "a/1941 \354\206\214\353\254\270\353\202\234\354\271\240\352\263\265\354\243\274.py" "b/1941 \354\206\214\353\254\270\353\202\234\354\271\240\352\263\265\354\243\274.py" deleted file mode 100644 index eba0e98..0000000 --- "a/1941 \354\206\214\353\254\270\353\202\234\354\271\240\352\263\265\354\243\274.py" +++ /dev/null @@ -1,56 +0,0 @@ -import sys -from collections import deque -input = sys.stdin.readline - -dx = [0,1,0,-1] -dy = [1,0,-1,0] -princess = deque() -ans = set() -A = [[] for _ in range(5)] -visit = [[False] * 5 for _ in range(5)] - -def go(n, cnt): - if (cnt + (7 - n) < 4): - return - - if n == 7: - if cnt >= 4: - temp = list(princess) - temp.sort() - temp = tuple(temp) - ans.add(temp) - return - - possible = set() - for node in princess: - for i in range(4): - nx = node[0] + dx[i] - ny = node[1] + dy[i] - if nx < 0 or ny < 0 or nx == 5 or ny == 5 or visit[nx][ny]: - continue - - possible.add((nx,ny)) - - for node in possible: - - visit[node[0]][node[1]] = True - princess.append(node) - if A[node[0]][node[1]] == 'S': - go(n+1, cnt+1) - else: - go(n+1, cnt) - princess.pop(); - visit[node[0]][node[1]] = False - -for i in range(5): - A[i] = list(input().rstrip()) - -for i in range(5): - for j in range(5): - if A[i][j] == 'S': - visit[i][j] = True - princess.append((i,j)) - go(1,1) - princess.popleft() - -print(len(ans)) \ No newline at end of file diff --git "a/1943 \353\217\231\354\240\204 \353\266\204\353\260\260.py" "b/1943 \353\217\231\354\240\204 \353\266\204\353\260\260.py" deleted file mode 100644 index 63b86bf..0000000 --- "a/1943 \353\217\231\354\240\204 \353\266\204\353\260\260.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(3): - N = int(input()) - coins = {} - target = 0 - for _ in range(N): - a, b = map(int, input().split()) - coins[a] = b - target += a*b - if target&1: - print(0) - continue - target //= 2 - dp = [1] + [0] * (target) - for coin in coins: - for money in range(target,coin-1,-1): - if dp[money-coin]: - for j in range(coins[coin]): - if money + coin*j <= target: - dp[money + coin*j] = 1 - print(dp[target]) \ No newline at end of file diff --git "a/1944\353\263\265\354\240\234\353\241\234\353\264\207_Kruskal.py" "b/1944\353\263\265\354\240\234\353\241\234\353\264\207_Kruskal.py" index a3e0e9a..17262d4 100644 --- "a/1944\353\263\265\354\240\234\353\241\234\353\264\207_Kruskal.py" +++ "b/1944\353\263\265\354\240\234\353\241\234\353\264\207_Kruskal.py" @@ -1,87 +1,87 @@ -from collections import deque - - -def is_found(y, x, edges, start, key): - visited = [[0 for i in range(N)] for j in range(N)] - q = deque([(y, x)]) - visited[y][x] = 1 - dy = [0, 1, 0, -1] - dx = [1, 0, -1, 0] - - reps = 1 - while q: - for _ in range(len(q)): - vy, vx = q.popleft() - for i in range(4): - ny = vy + dy[i] - nx = vx + dx[i] - if 0 <= ny < N and 0 <= nx < N and not visited[ny][nx]: - if field[ny][nx] >= 2: - edges.append((reps, start, field[ny][nx])) - q.append((ny, nx)) - key -= 1 - elif field[ny][nx] == 0: - q.append((ny, nx)) - visited[ny][nx] = 1 - reps += 1 - - if key: return False - else: return True - -def find(x, parents): - if parents[x] == x: - return x - parents[x] = find(parents[x], parents) - return parents[x] - -def union(x, y, parents, ranks): - xroot = find(x, parents) - yroot = find(y, parents) - if ranks[xroot] >= ranks[yroot]: - parents[yroot] = xroot - else: - parents[xroot] = yroot - if ranks[xroot] == ranks[yroot]: - ranks[xroot] += 1 - -def kruskal(edges): - parents = [i for i in range(M+3)] - ranks = [0 for i in range(M+3)] - edges.sort() - mst_val = 0 - - for val, s, e in edges: - if find(s, parents) != find(e, parents): - union(s, e, parents, ranks) - mst_val += val - - return mst_val - -def solution(N, M, field): - nodes = [] - idx = 2 - start = 0 - for i in range(N): - for j in range(N): - if field[i][j] == 'S' or field[i][j] == 'K': - if field[i][j] == 'S': start = idx - field[i][j] = idx - idx += 1 - nodes.append((i, j)) - else: - field[i][j] = int(field[i][j]) - - edges = [] - for i in range(N): - for j in range(N): - if field[i][j] >= 2: - if not is_found(i, j, edges, field[i][j], M): - print(-1) - return - - print(kruskal(edges)) - -if __name__ == '__main__': - N, M = map(int, input().split()) - field = [list(input()) for i in range(N)] +from collections import deque + + +def is_found(y, x, edges, start, key): + visited = [[0 for i in range(N)] for j in range(N)] + q = deque([(y, x)]) + visited[y][x] = 1 + dy = [0, 1, 0, -1] + dx = [1, 0, -1, 0] + + reps = 1 + while q: + for _ in range(len(q)): + vy, vx = q.popleft() + for i in range(4): + ny = vy + dy[i] + nx = vx + dx[i] + if 0 <= ny < N and 0 <= nx < N and not visited[ny][nx]: + if field[ny][nx] >= 2: + edges.append((reps, start, field[ny][nx])) + q.append((ny, nx)) + key -= 1 + elif field[ny][nx] == 0: + q.append((ny, nx)) + visited[ny][nx] = 1 + reps += 1 + + if key: return False + else: return True + +def find(x, parents): + if parents[x] == x: + return x + parents[x] = find(parents[x], parents) + return parents[x] + +def union(x, y, parents, ranks): + xroot = find(x, parents) + yroot = find(y, parents) + if ranks[xroot] >= ranks[yroot]: + parents[yroot] = xroot + else: + parents[xroot] = yroot + if ranks[xroot] == ranks[yroot]: + ranks[xroot] += 1 + +def kruskal(edges): + parents = [i for i in range(M+3)] + ranks = [0 for i in range(M+3)] + edges.sort() + mst_val = 0 + + for val, s, e in edges: + if find(s, parents) != find(e, parents): + union(s, e, parents, ranks) + mst_val += val + + return mst_val + +def solution(N, M, field): + nodes = [] + idx = 2 + start = 0 + for i in range(N): + for j in range(N): + if field[i][j] == 'S' or field[i][j] == 'K': + if field[i][j] == 'S': start = idx + field[i][j] = idx + idx += 1 + nodes.append((i, j)) + else: + field[i][j] = int(field[i][j]) + + edges = [] + for i in range(N): + for j in range(N): + if field[i][j] >= 2: + if not is_found(i, j, edges, field[i][j], M): + print(-1) + return + + print(kruskal(edges)) + +if __name__ == '__main__': + N, M = map(int, input().split()) + field = [list(input()) for i in range(N)] solution(N, M, field) \ No newline at end of file diff --git "a/1944\353\263\265\354\240\234\353\241\234\353\264\207_Prim.py" "b/1944\353\263\265\354\240\234\353\241\234\353\264\207_Prim.py" index e0e80c0..fe7f4ff 100644 --- "a/1944\353\263\265\354\240\234\353\241\234\353\264\207_Prim.py" +++ "b/1944\353\263\265\354\240\234\353\241\234\353\264\207_Prim.py" @@ -1,95 +1,94 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -# S부터 각 K까지 거리, K에서 각 K까지 거리 탐색을 위한 BFS, 각 K자리에 cnt값 기록. -def BFS(x,y,graph,start,key): - dx = [0,0,1,-1] - dy = [1,-1,0,0] - check = [[False]*N for _ in range(N)] - queue = deque() - queue.append([x,y]) - check[x][y] = True - - # reps는 바퀴수(거리) - # 즉 graph에 node번호 e와 가중치 reps를 넣어줌. - reps = 1 - while queue: - for _ in range(len(queue)): - vx,vy = queue.popleft() - for i in range(4): - nx = vx+dx[i] - ny = vy+dy[i] - if 0<=nx= 2: - e = maze[nx][ny] - if graph.get(start): # graph에 start시작점 정점번호, 가중치 있으면 가져와서 하나 더 넣어줌. - graph.get(start).append((e,reps)) # 즉 start라는 key에 정점정보가 계속 담김. - else: - graph[start] = [(e,reps)] # graph에 start시작점 정점번호, 가중치 없으면 선언해줌. - queue.append((nx,ny)) - key -= 1 # key찾을때마다 하나씩 -해서 다 끝났을 떄 key가 남아있으면 false - elif maze[nx][ny] ==0: - queue.append((nx,ny)) - check[nx][ny]=True - reps +=1 - if key: - return False - else: - return True - - - -def prim(graph,start,M): - minWeight = [float('inf')] * (M+3) # 최초 가중치 전부 무한대로 key갯수+시작지점 (idx 2부터 시작했으므로 2칸 더 더해줌.) - visited = [0] * (M+3) - minWeight[0] = minWeight[1] = minWeight[start] = 0 # 그냥 준 0,1 idx 요소 0으로 초기화, start요소 0으로 시작. - - for _ in range(2,M+3): # 2번 노드부터 M+2번 노드까지 key+S의 갯수만큼 반복 - minidx, minval = 0,float('inf') - for j in range(2,M+3): - if not visited[j] and minWeight[j] < minval: # j노드에 방문 안했고, j의 최소 가중치가 최소값(연결된 모든 가중치 중의 촤솟값)보다 작으면 (즉 최초 0과 이어져 있는 노드들만) - minval = minWeight[j] # j의 minWeight는 minval(가중치의 값이 가장 작은 것(최솟값을 찾기위함)) - minidx = j # j는 최솟값을 가진 연결된 노드임을 표시 - visited[minidx] = 1 # 최소 가중치를 가진 minidx로 방문. - for e,val in graph.get(minidx): # graph에서 가장 작은 idx의 node번호, 가중치 값을 가져온다. - if not visited[e] and minWeight[e] > val: # 방문안했고 가중치값보다 minWeight에 기록된 가중치가 더 크면 - minWeight[e] = val # 최소가중치값에 가중치값을 저장해준다. - # 위과정을 M+1번 반복한다.(M+1개의 노드를 잇기위해서.) - - return sum(minWeight) # MST의 가중치값 합을 리턴한다. - - - -N,M = map(int,input().split()) -maze = [list(map(str,input().rstrip())) for _ in range(N)] - - -# maze에서 S,K찾기 / S,K는 0,1로부터 구분하기 위해 2부터 시작. -points = [] -idx = 2 -start = 0 -for i in range(N): - for j in range(N): - if maze[i][j] == 'S' or maze[i][j] == 'K': - if maze[i][j] == 'S': - start = idx # start에서 시작하기 위해 'S'를 찾으면 그 idx를 start에 저장함. - maze[i][j] = idx - idx += 1 - points.append([i,j]) - else: - maze[i][j] = int(maze[i][j]) - -graph = dict() -for i in range(N): - for j in range(N): - if maze[i][j] >=2: - if not BFS(i,j,graph,maze[i][j],M): # 모든 열쇠 탐색 불가능 하면 -1출력. - print(-1) - exit() - -print(prim(graph, start,M)) - - - +import sys +input = sys.stdin.readline +from collections import deque + + +# S부터 각 K까지 거리, K에서 각 K까지 거리 탐색을 위한 BFS, 각 K자리에 cnt값 기록. +def BFS(x,y,graph,start,key): + dx = [0,0,1,-1] + dy = [1,-1,0,0] + check = [[False]*N for _ in range(N)] + queue = deque() + queue.append([x,y]) + check[x][y] = True + + # reps는 바퀴수(거리) + # 즉 graph에 node번호 e와 가중치 reps를 넣어줌. + reps = 1 + while queue: + for _ in range(len(queue)): + vx,vy = queue.popleft() + for i in range(4): + nx = vx+dx[i] + ny = vy+dy[i] + if 0<=nx= 2: + e = maze[nx][ny] + if graph.get(start): # graph에 start시작점 정점번호, 가중치 있으면 가져와서 하나 더 넣어줌. + graph.get(start).append((e,reps)) # 즉 start라는 key에 정점정보가 계속 담김. + else: + graph[start] = [(e,reps)] # graph에 start시작점 정점번호, 가중치 없으면 선언해줌. + queue.append((nx,ny)) + key -= 1 # key찾을때마다 하나씩 -해서 다 끝났을 떄 key가 남아있으면 false + elif maze[nx][ny] ==0: + queue.append((nx,ny)) + check[nx][ny]=True + reps +=1 + if key: + return False + else: + return True + + +def prim(graph,start,M): + minWeight = [float('inf')] * (M+3) # 최초 가중치 전부 무한대로 key갯수+시작지점 (idx 2부터 시작했으므로 2칸 더 더해줌.) + visited = [0] * (M+3) + minWeight[0] = minWeight[1] = minWeight[start] = 0 # 그냥 준 0,1 idx 요소 0으로 초기화, start요소 0으로 시작. + + for _ in range(2,M+3): # 2번 노드부터 M+2번 노드까지 key+S의 갯수만큼 반복 + minidx, minval = 0,float('inf') + for j in range(2,M+3): + if not visited[j] and minWeight[j] < minval: # j노드에 방문 안했고, j의 최소 가중치가 최소값(연결된 모든 가중치 중의 촤솟값)보다 작으면 (즉 최초 0과 이어져 있는 노드들만) + minval = minWeight[j] # j의 minWeight는 minval(가중치의 값이 가장 작은 것(최솟값을 찾기위함)) + minidx = j # j는 최솟값을 가진 연결된 노드임을 표시 + visited[minidx] = 1 # 최소 가중치를 가진 minidx로 방문. + for e,val in graph.get(minidx): # graph에서 가장 작은 idx의 node번호, 가중치 값을 가져온다. + if not visited[e] and minWeight[e] > val: # 방문안했고 가중치값보다 minWeight에 기록된 가중치가 더 크면 + minWeight[e] = val # 최소가중치값에 가중치값을 저장해준다. + # 위과정을 M+1번 반복한다.(M+1개의 노드를 잇기위해서.) + + return sum(minWeight) # MST의 가중치값 합을 리턴한다. + + + +N,M = map(int,input().split()) +maze = [list(map(str,input().rstrip())) for _ in range(N)] + + +# maze에서 S,K찾기 / S,K는 0,1로부터 구분하기 위해 2부터 시작. +points = [] +idx = 2 +start = 0 +for i in range(N): + for j in range(N): + if maze[i][j] == 'S' or maze[i][j] == 'K': + if maze[i][j] == 'S': + start = idx # start에서 시작하기 위해 'S'를 찾으면 그 idx를 start에 저장함. + maze[i][j] = idx + idx += 1 + points.append([i,j]) + else: + maze[i][j] = int(maze[i][j]) + +graph = dict() +for i in range(N): + for j in range(N): + if maze[i][j] >=2: + if not BFS(i,j,graph,maze[i][j],M): # 모든 열쇠 탐색 불가능 하면 -1출력. + print(-1) + exit() + +print(prim(graph, start,M)) + + + diff --git "a/1949\354\232\260\354\210\230\353\247\210\354\235\204.py" "b/1949\354\232\260\354\210\230\353\247\210\354\235\204.py" deleted file mode 100644 index fdd3096..0000000 --- "a/1949\354\232\260\354\210\230\353\247\210\354\235\204.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**5) - -def dfs(v): - visited[v] = True - dp[v][1] = citizen[v-1] - for u in graph[v]: - if not visited[u]: - dfs(u) - - dp[v][0] += max(dp[u][0],dp[u][1]) - dp[v][1] += dp[u][0] - - -N = int(input()) -citizen = list(map(int, input().split())) -graph = {i: [] for i in range(1,N+1)} -visited = {i: False for i in range(1,N+1)} -for _ in range(N-1): - a, b = map(int, input().split()) - graph[a].append(b) - graph[b].append(a) - -dp = [[0,0] for _ in range(N+1)] -dfs(1) -print(max(dp[1][0],dp[1][1])) \ No newline at end of file diff --git "a/19535\343\204\267\343\204\267\343\204\267\343\205\210.py" "b/19535\343\204\267\343\204\267\343\204\267\343\205\210.py" deleted file mode 100644 index 147718d..0000000 --- "a/19535\343\204\267\343\204\267\343\204\267\343\205\210.py" +++ /dev/null @@ -1,43 +0,0 @@ -import sys -read = sys.stdin.readline - -# 조합을 팩토리얼로 구함(a~(a-b+1))까지 곱한값 분자 1~b까지 곱한값 분모. -def set_combination_cnt(a, b): - com_cnt = 1 - if a-b < b: - b = a-b - for i in range(a-b+1, a+1): - com_cnt *= i - for j in range(1, b+1): - com_cnt //=j - return com_cnt - -N = int(read()) -edge = [] -edge_cnt = [0 for _ in range(N+1)] - -for _ in range(N-1): - a, b = map(int, read().split()) - edge.append([a, b]) - edge_cnt[a] += 1 - edge_cnt[b] += 1 - -du_tree_cnt = 0 -ga_tree_cnt = 0 -# 각 간선양쪽에서 이어진 선분 수만큼 ㄷ Tree가 있음(가운데선분 고정 양쪽 선분 선택.) -for start,end in edge: - temp = (edge_cnt[start]-1) * (edge_cnt[end]-1) - du_tree_cnt += temp -# ㅈ 트리는 간선이 3개 이상일때 그 중에서 3개를 뽑느 조합의 수만큼 나옴. -for idx in range(1, N+1): - if edge_cnt[idx] >= 3: - ga_tree_cnt += set_combination_cnt(edge_cnt[idx], 3) - -#print(du_tree_cnt, ga_tree_cnt) - -if du_tree_cnt > 3 * ga_tree_cnt: - print('D') -elif du_tree_cnt < 3 * ga_tree_cnt: - print('G') -else: - print('DUDUDUNGA') \ No newline at end of file diff --git "a/19539\354\202\254\352\263\274\353\202\230\353\254\264.py" "b/19539\354\202\254\352\263\274\353\202\230\353\254\264.py" deleted file mode 100644 index cb0e1d4..0000000 --- "a/19539\354\202\254\352\263\274\353\202\230\353\254\264.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -h = list(map(int,input().split())) - -two = 0 -one = 0 -for wood in h: - two += wood//2 - one += wood%2 - -if not (two-one)%3 and two >= one: - print('YES') -else: - print('NO') \ No newline at end of file diff --git "a/19542 \354\240\204\353\213\250\354\247\200 \353\217\214\353\246\254\352\270\260.py" "b/19542 \354\240\204\353\213\250\354\247\200 \353\217\214\353\246\254\352\270\260.py" deleted file mode 100644 index 35692fd..0000000 --- "a/19542 \354\240\204\353\213\250\354\247\200 \353\217\214\353\246\254\352\270\260.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**5) - -def dfs(cur_node, pre_node): - global ans - max_d = 0 - for next_node in graph[cur_node]: - if next_node != pre_node: - max_d = max(max_d,dfs(next_node, cur_node)) - if max_d >= D: - ans += 1 - return max_d + 1 - - -N, S, D = map(int, input().split()) -graph = {i: [] for i in range(1,N+1)} -visited = [0] * (N+1) -ans = 0 -for _ in range(N-1): - x, y = map(int, input().split()) - graph[x] += [y] - graph[y] += [x] -dfs(S, 0) -print(2*(ans-1) if ans else 0) diff --git a/1958 LCS3.py b/1958 LCS3.py deleted file mode 100644 index 11e8450..0000000 --- a/1958 LCS3.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -s1, s2, s3 = (input().rstrip() for _ in range(3)) -n1, n2, n3 = len(s1), len(s2), len(s3) -dp = [[[0 for _ in range(n1+1)] for _ in range(n2+1)] for _ in range(n3+1)] - -for i in range(n1): - for j in range(n2): - for k in range(n3): - if s1[i] == s2[j] == s3[k]: - dp[k+1][j+1][i+1] = dp[k][j][i] + 1 - else: - dp[k+1][j+1][i+1] = max(dp[k][j+1][i+1], dp[k+1][j][i+1], dp[k+1][j+1][i]) - -print(dp[n3][n2][n1]) \ No newline at end of file diff --git a/1958.py b/1958.py deleted file mode 100644 index 022db68..0000000 --- a/1958.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys - -S = sys.stdin.readline() -P = sys.stdin.readline() - -if P in S: - print(1) -else: - print(S,P) \ No newline at end of file diff --git "a/19585\354\240\204\354\204\244.py" "b/19585\354\240\204\354\204\244.py" deleted file mode 100644 index 24cc836..0000000 --- "a/19585\354\240\204\354\204\244.py" +++ /dev/null @@ -1,46 +0,0 @@ -import sys -input = sys.stdin.readline - -class Node: - def __init__(self): - self.child = {} - self.word = False - -class Trie: - def __init__(self): - self.root = Node() - - def insert(self,word): - node = self.root - - for char in word: - if char not in node.child: - node.child[char] = Node() - node = node.child[char] - node.word = True - - def search(self,word,n): - node = self.root - - for i in range(n): - if word[i] not in node.child: - return i if node.word else 0 - node = node.child[word[i]] - -C, N = map(int, input().split()) -c_trie = Trie() -n_trie = Trie() -for _ in range(C): - c_trie.insert(input().rstrip()) -for _ in range(N): - n_trie.insert(input().rstrip()[::-1]) - -for _ in range(int(input())): - query = input().rstrip() - n = len(query) - idx1 = c_trie.search(query,n) - if not idx1: - print('No') - continue - idx2 = n_trie.search(query[::-1], n) - print('Yes'if idx1+idx2==n else 'No') diff --git "a/19598\354\265\234\354\206\214\355\232\214\354\235\230\354\213\244\352\260\234\354\210\230.py" "b/19598\354\265\234\354\206\214\355\232\214\354\235\230\354\213\244\352\260\234\354\210\230.py" deleted file mode 100644 index 32a7aed..0000000 --- "a/19598\354\265\234\354\206\214\355\232\214\354\235\230\354\213\244\352\260\234\354\210\230.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -N = int(input()) -meeting_schedule = [list(map(int,input().split())) for _ in range(N)] -meeting_schedule.sort() - -cnt = 0 -heap = [] -for start,end in meeting_schedule: - if not heap or heap[0] > start : - cnt +=1 - heappush(heap,end) - else: - heappop(heap) - heappush(heap,end) - -print(cnt) \ No newline at end of file diff --git "a/19637if\353\254\271\354\242\200\353\214\200\354\213\240\354\215\250\354\244\230.py" "b/19637if\353\254\271\354\242\200\353\214\200\354\213\240\354\215\250\354\244\230.py" deleted file mode 100644 index aa78c9b..0000000 --- "a/19637if\353\254\271\354\242\200\353\214\200\354\213\240\354\215\250\354\244\230.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input=sys.stdin.readline - -from bisect import bisect_left - -N,M = map(int,input().split()) -names=[] -grades=[] -for _ in range(N): - name,grade = input().split() - names.append(name) - grades.append(int(grade)) - -for _ in range(M): - check=int(input()) - print(names[bisect_left(grades,check)]) \ No newline at end of file diff --git "a/1965\354\203\201\354\236\220\353\204\243\352\270\260.py" "b/1965\354\203\201\354\236\220\353\204\243\352\270\260.py" deleted file mode 100644 index 82bf9df..0000000 --- "a/1965\354\203\201\354\236\220\353\204\243\352\270\260.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -n = int(input()) -arr = list(map(int, input().split())) -answer = [arr[0]] -for num in arr[1:]: - if answer[-1] < num: - answer.append(num) - else: - answer[bisect_left(answer,num)] = num -print(len(answer)) \ No newline at end of file diff --git "a/1967\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" "b/1967\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" index 7c4b351..996fcee 100644 --- "a/1967\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" +++ "b/1967\355\212\270\353\246\254\354\235\230\354\247\200\353\246\204.py" @@ -1,38 +1,38 @@ -import sys -from collections import deque,defaultdict -input = sys.stdin.readline - -n = int(input()) -graph = defaultdict(list) - -for _ in range(n-1): - a,b,c = map(int,input().split()) - graph[a].append((b,c)) - graph[b].append((a,c)) - - - -def bfs(v): - visited = [-1] * (n + 1) - queue = deque() - queue.append(v) - visited[v] = 0 - max_node = [0, 0] - - while queue: - t = queue.popleft() - for e, w in graph[t]: - if visited[e] == -1: - visited[e] = visited[t] + w - queue.append(e) - if max_node[0] < visited[e]: - max_node = visited[e], e - - return max_node - - -dist, node = bfs(1) -dist, node = bfs(node) -print(dist) - +import sys +from collections import deque,defaultdict +input = sys.stdin.readline + +n = int(input()) +graph = defaultdict(list) + +for _ in range(n-1): + a,b,c = map(int,input().split()) + graph[a].append((b,c)) + graph[b].append((a,c)) + + + +def bfs(v): + visited = [-1] * (n + 1) + queue = deque() + queue.append(v) + visited[v] = 0 + max_node = [0, 0] + + while queue: + t = queue.popleft() + for e, w in graph[t]: + if visited[e] == -1: + visited[e] = visited[t] + w + queue.append(e) + if max_node[0] < visited[e]: + max_node = visited[e], e + + return max_node + + +dist, node = bfs(1) +dist, node = bfs(node) +print(dist) + # 트리의 지름(그래프 간 가장 먼 노드 사이의 거리) = 아무 노드에서 최장 노드, 그 노드에서 다시한번 최장노드 = 지름 \ No newline at end of file diff --git "a/19699\354\206\214-\353\202\234\353\213\244!.py" "b/19699\354\206\214-\353\202\234\353\213\244!.py" deleted file mode 100644 index cecc0a2..0000000 --- "a/19699\354\206\214-\353\202\234\353\213\244!.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(start,depth,sum_cow): - if depth==M: - if isPrime(sum_cow): - answer.add(sum_cow) - for i in range(start,N): - if not visited[i]: - visited[i]=True - DFS(i+1,depth+1,sum_cow+H[i]) - visited[i]=False - -def isPrime(n): - if n<2: - return False - for i in range(2,n): - if n%i==0: - return False - return True - -N,M = map(int,input().split()) -H = list(map(int,input().split())) -visited = [False]*N -answer = set() - -DFS(0,0,0) - -if answer: - print(*sorted(list(answer))) -else: - print(-1) diff --git a/1969DNA.py b/1969DNA.py deleted file mode 100644 index d052302..0000000 --- a/1969DNA.py +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -n, m = map(int, input().split()) -dnas = [input().rstrip() for _ in range(n)] -nut = ['A','C','G','T'] -dp_sum = [[0 for _ in range(4)] for _ in range(m)] - -for i in range(n): - for j in range(m): - for k in range(4): - if dnas[i][j] == nut[k]: - dp_sum[j][k] += 1 - break -result = '' -cnt = 0 -for i in range(m): - tmp = max(dp_sum[i]) - result += nut[dp_sum[i].index(tmp)] - cnt += n - tmp -print(result) -print(cnt) \ No newline at end of file diff --git "a/1976 \354\227\254\355\226\211\352\260\200\354\236\220.py" "b/1976 \354\227\254\355\226\211\352\260\200\354\236\220.py" deleted file mode 100644 index e09626a..0000000 --- "a/1976 \354\227\254\355\226\211\352\260\200\354\236\220.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -input = sys.stdin.readline - - -def union(x, y): - x = find(x) - y = find(y) - - if x > y: - x, y = y, x - parents[y] = x - - -def find(x): - if parents[x] == x: - return x - parents[x] = find(parents[x]) - return parents[x] - - -N = int(input()) -M = int(input()) -edges = [list(map(int, input().split())) for _ in range(N)] -plan = list(map(lambda x: int(x) - 1, input().split())) -parents = {i: i for i in range(N)} -for i in range(N): - for j in range(N): - if edges[i][j] and find(i) != find(j): - union(i, j) - -pivot = find(plan[0]) -for city in plan[1:]: - if find(city) != pivot: - print('NO') - break -else: - print('YES') \ No newline at end of file diff --git "a/1978\354\206\214\354\210\230\354\260\276\352\270\260.py" "b/1978\354\206\214\354\210\230\354\260\276\352\270\260.py" index a48d9b4..959fd79 100644 --- "a/1978\354\206\214\354\210\230\354\260\276\352\270\260.py" +++ "b/1978\354\206\214\354\210\230\354\260\276\352\270\260.py" @@ -1,19 +1,15 @@ - -N = int(input()) -num = list(map(int,input().split())) -cnt = 0 - -for i in range(N): - if num[i] == 1: - continue - elif num[i] == 2: - cnt+=1 - continue - else: - for j in range(2,num[i]): - if num[i]%j==0: - break - if j==num[i]-1: - cnt+=1 - -print(cnt) \ No newline at end of file + +A,B = map(int,input().split()) + +for i in range(A,B+1): + if i == 1: + continue + elif i == 2: + print(i) + continue + else: + for j in range(2,i): + if i%j==0: + break + if j==i-1: + print(i) diff --git "a/1987\354\225\214\355\214\214\353\262\263.py" "b/1987\354\225\214\355\214\214\353\262\263.py" deleted file mode 100644 index 10b5151..0000000 --- "a/1987\354\225\214\355\214\214\353\262\263.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - - -def bfs(x, y): - q = set([(x, y, board[x][y])]) - check[x][y] = board[x][y] - answer = 1 - while q: - x, y, string = q.pop() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < R and 0 <= ny < C and board[nx][ny] not in string: - new_string = string + board[nx][ny] - if check[nx][ny] != new_string: - check[nx][ny] = new_string - q.add((nx, ny, new_string)) - answer = max(answer, len(string) + 1) - if answer == 26: - return 26 - return answer - -R, C = map(int, input().split()) -board = [list(input().rstrip()) for _ in range(R)] -delta = [(0, 1), (1, 0), (-1, 0), (0, -1)] -check = [[''] * C for _ in range(R)] -print(bfs(0, 0)) \ No newline at end of file diff --git a/1991.py b/1991.py deleted file mode 100644 index e4bbba7..0000000 --- a/1991.py +++ /dev/null @@ -1,43 +0,0 @@ -class Node: - def __init__(self, item, left, right): - self.item = item - self.left = left - self.right = right - - -def inorder(node): - if node.left !='.': - inorder(tree[node.left]) - print(node.item, end='') - if node.right!='.': - inorder(tree[node.right]) - -def postorder(node): - if node.left !='.': - postorder(tree[node.left]) - if node.right!='.': - postorder(tree[node.right]) - print(node.item, end='') - -def preorder(node): - print(node.item, end='') - if node.left !='.': - preorder(tree[node.left]) - if node.right!='.': - preorder(tree[node.right]) - - - -N = int(input()) -tree={} - -for _ in range(N): - node,left,right = map(str, input().split()) - tree[node] = Node(item=node, left=left, right=right) - - -preorder(tree['A']) -print() -inorder(tree['A']) -print() -postorder(tree['A']) \ No newline at end of file diff --git a/1991_tree_circulation_trymore.py b/1991_tree_circulation_trymore.py deleted file mode 100644 index 61a927b..0000000 --- a/1991_tree_circulation_trymore.py +++ /dev/null @@ -1,19 +0,0 @@ -t = int(input()) -n= int(input()) -numbers = [] - -for _ in range(n): - numbers.append(input()) - -numbers.sort() -ans = 0 -for i in range(n-1): - if numbers[i+1].find(numbers[i]) != -1: - ans = 1 - break - -if ans == 1: - print("NO") -else: - print("YES") - diff --git "a/1991\355\212\270\353\246\254\354\210\234\355\232\214\354\204\244\352\263\204.py" "b/1991\355\212\270\353\246\254\354\210\234\355\232\214\354\204\244\352\263\204.py" index e4bbba7..b4c415c 100644 --- "a/1991\355\212\270\353\246\254\354\210\234\355\232\214\354\204\244\352\263\204.py" +++ "b/1991\355\212\270\353\246\254\354\210\234\355\232\214\354\204\244\352\263\204.py" @@ -1,43 +1,43 @@ -class Node: - def __init__(self, item, left, right): - self.item = item - self.left = left - self.right = right - - -def inorder(node): - if node.left !='.': - inorder(tree[node.left]) - print(node.item, end='') - if node.right!='.': - inorder(tree[node.right]) - -def postorder(node): - if node.left !='.': - postorder(tree[node.left]) - if node.right!='.': - postorder(tree[node.right]) - print(node.item, end='') - -def preorder(node): - print(node.item, end='') - if node.left !='.': - preorder(tree[node.left]) - if node.right!='.': - preorder(tree[node.right]) - - - -N = int(input()) -tree={} - -for _ in range(N): - node,left,right = map(str, input().split()) - tree[node] = Node(item=node, left=left, right=right) - - -preorder(tree['A']) -print() -inorder(tree['A']) -print() +class Node: + def __init__(self, item, left, right): + self.item = item + self.left = left + self.right = right + + +def inorder(node): + if node.left !='.': + inorder(tree[node.left]) + print(node.item, end='') + if node.right!='.': + inorder(tree[node.right]) + +def postorder(node): + if node.left !='.': + postorder(tree[node.left]) + if node.right!='.': + postorder(tree[node.right]) + print(node.item, end='') + +def preorder(node): + print(node.item, end='') + if node.left !='.': + preorder(tree[node.left]) + if node.right!='.': + preorder(tree[node.right]) + + + +N = int(input()) +tree={} + +for _ in range(N): + node,left,right = map(str, input().split()) + tree[node] = Node(item=node, left=left, right=right) + + +preorder(tree['A']) +print() +inorder(tree['A']) +print() postorder(tree['A']) \ No newline at end of file diff --git "a/1992\354\277\274\353\223\234\355\212\270\353\246\254.py" "b/1992\354\277\274\353\223\234\355\212\270\353\246\254.py" deleted file mode 100644 index f55193e..0000000 --- "a/1992\354\277\274\353\223\234\355\212\270\353\246\254.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline - - -def check(n,s_x,s_y): - pivot = matrix[s_x][s_y] - for i in range(s_x,s_x+n): - for j in range(s_y,s_y+n): - if matrix[i][j] != pivot: - return False - return True - - -def compress_video(n,s_x,s_y): - pivot = n//2 - if n==1: - q_tree.append(str(matrix[s_x][s_y])) - return - if check(n,s_x,s_y): - q_tree.append(str(matrix[s_x][s_y])) - return - q_tree.append('(') - for i in range(2): - for j in range(2): - compress_video(pivot,s_x+(pivot*i),s_y+(pivot*j)) - q_tree.append(')') - -N = int(input()) -matrix = [list(map(int,input().rstrip())) for _ in range(N)] -q_tree = [] - -compress_video(N,0,0) -print(''.join(q_tree)) \ No newline at end of file diff --git "a/19939\353\260\225 \355\204\260\353\234\250\353\246\254\352\270\260.py" "b/19939\353\260\225 \355\204\260\353\234\250\353\246\254\352\270\260.py" deleted file mode 100644 index 57ae3b9..0000000 --- "a/19939\353\260\225 \355\204\260\353\234\250\353\246\254\352\270\260.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) -min_gap = K * (K + 1) // 2 -if min_gap > N: - print(-1) - exit() -answer = K - 1 if not (N - min_gap) % K else K -print(answer) \ No newline at end of file diff --git "a/19948 \354\235\214\354\234\240\354\213\234\354\235\270\354\230\201\354\236\254.py" "b/19948 \354\235\214\354\234\240\354\213\234\354\235\270\354\230\201\354\236\254.py" deleted file mode 100644 index c3968fb..0000000 --- "a/19948 \354\235\214\354\234\240\354\213\234\354\235\270\354\230\201\354\236\254.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline - -poem = input().rstrip() -title = ''.join([a[0].upper() for a in poem.split()]) -poem += title + '.' -left_space = int(input()) -left_push_alphabet = {idx: cnt for idx, cnt in enumerate(map(int, input().split()))} -for i in range(len(poem) - 1): - if poem[i] == poem[i + 1]: - continue - if poem[i] == ' ': - if left_space: - left_space -= 1 - else: - print(-1) - exit() - else: - if left_push_alphabet[ord(poem[i].lower()) - 97]: - left_push_alphabet[ord(poem[i].lower()) - 97] -= 1 - else: - print(-1) - exit() -else: - print(title) \ No newline at end of file diff --git "a/19949 \354\230\201\354\236\254\354\235\230 \354\213\234\355\227\230.py" "b/19949 \354\230\201\354\236\254\354\235\230 \354\213\234\355\227\230.py" deleted file mode 100644 index 75156ba..0000000 --- "a/19949 \354\230\201\354\236\254\354\235\230 \354\213\234\355\227\230.py" +++ /dev/null @@ -1,53 +0,0 @@ -import sys -input = sys.stdin.readline - -ans = list(map(int, input().split())) -dp = [[[[-1 for score in range(11)] for pre2 in range(6)] for pre in range(6)] for depth in range(11)] - -def make_dp(depth, pre, pre2, score): - if dp[depth][pre][pre2][score] != -1: - return dp[depth][pre][pre2][score] - - if depth == 10: - return 1 if score >= 5 else 0 - - cnt = 0 - for next_num in range(1, 6): - if pre == pre2 and pre2 == next_num: - continue - if ans[depth] == next_num: - cnt += make_dp(depth + 1, pre2, next_num, score + 1) - else: - cnt += make_dp(depth + 1, pre2, next_num, score) - - dp[depth][pre][pre2][score] = cnt - return cnt - -print(make_dp(0, 0, 0, 0)) - - - -# 풀이2 -def solve(arr, depth, point): - global ans - if depth >= 6 and point <= depth - 6: - return - if depth == 10: - if point >= 5: - ans += 1 - else: - for i in range(1, 6): - ar = arr[:] - ar.append(i) - p = point + 1 if i == answers[depth] else point - if depth >= 2: - if not (i == ar[depth - 1] and i == ar[depth - 2]): - solve(ar, depth + 1, p) - else: - solve(ar, depth + 1, p) - - -answers = list(map(int, input().split())) -ans = 0 -solve([], 0, 0) -print(ans) \ No newline at end of file diff --git "a/19951 \355\203\234\354\203\201\354\235\264\354\235\230 \355\233\210\353\240\250\354\206\214 \354\203\235\355\231\234.py" "b/19951 \355\203\234\354\203\201\354\235\264\354\235\230 \355\233\210\353\240\250\354\206\214 \354\203\235\355\231\234.py" deleted file mode 100644 index 1ebd9fa..0000000 --- "a/19951 \355\203\234\354\203\201\354\235\264\354\235\230 \355\233\210\353\240\250\354\206\214 \354\203\235\355\231\234.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -H = list(map(int, input().split())) -save = [0] * (N+1) -for _ in range(M): - a, b, k = map(int, input().split()) - save[a-1] += k - save[b] -= k - -dp = [0] * (N+1) -dp[0] = save[0] -for i in range(1,N+1): - dp[i] = dp[i-1] + save[i] - -for i in range(N): - print(H[i] + dp[i], end=' ') \ No newline at end of file diff --git "a/20002\354\202\254\352\263\274\353\202\230\353\254\264.py" "b/20002\354\202\254\352\263\274\353\202\230\353\254\264.py" deleted file mode 100644 index 0a9f4ee..0000000 --- "a/20002\354\202\254\352\263\274\353\202\230\353\254\264.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -maps = [list(map(int,input().split())) for _ in range(N)] -dp = [[0]*(N+1) for _ in range(N+1)] - -for i in range(1,N+1): - for j in range(1,N+1): - dp[i][j] = dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+maps[i-1][j-1] - -max_profit=dp[1][1] -for k in range(N): - for i in range(1,N-k+1): - for j in range(1,N-k+1): - cur_profit = dp[i+k][j+k]-dp[i-1][j+k]-dp[i+k][j-1]+dp[i-1][j-1] - if max_profit < cur_profit: - max_profit=cur_profit - -print(max_profit) - - - diff --git "a/20007\353\226\241\353\217\214\353\246\254\352\270\260.py" "b/20007\353\226\241\353\217\214\353\246\254\352\270\260.py" deleted file mode 100644 index ec9dcd4..0000000 --- "a/20007\353\226\241\353\217\214\353\246\254\352\270\260.py" +++ /dev/null @@ -1,50 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -# 1. 0번에서 각 집에 가는 최소거리. -> 다익스트라 -def dijkstra(start): - heap = [] - dp_dists[start] = 0 - heappush(heap,[dp_dists[start],start]) - while heap: - cur_dist,cur_node = heappop(heap) - for next_node,next_dists in graph[cur_node]: - if dp_dists[next_node] > cur_dist + next_dists: - dp_dists[next_node] = cur_dist + next_dists - heappush(heap,[dp_dists[next_node],next_node]) - - -# 떡 한번에 하나씩. 집들 사이에 총 M개의 양방향 도로 -# 하루에 X이상 가지 않음. 가까운 집부터 방문. 왕복할 수 없으면 미룸. -# N-1개의 이웃집에 떡돌리려면 몇 일? -# 집은 0~N-1번까지. -N,M,X,Y = map(int,input().split()) -graph = {i:[] for i in range(N)} -dp_dists = [float('inf') for _ in range(N)] - -for _ in range(M): - a,b,c = map(int,input().split()) - graph[a].append([b,c]) - graph[b].append([a,c]) - -dijkstra(Y) - -# 2. 최소거리*2가 X이상이면 -1출력 -for i in range(N): - if dp_dists[i] > X//2: - print(-1) - exit() - -# 3. 최소거리*2의 합이 X이하인 조합의 최소갯수.//가까운 곳부터 방문 -> 정렬 -# 4. 오름차순 그냥 더하는 식으로.(가까운 곳 부터) -dp_dists.sort() -daily_move = 0 -day = 1 -for i in range(N): - if (daily_move + dp_dists[i])*2 <= X: - daily_move = daily_move + dp_dists[i] - else: - daily_move = dp_dists[i] - day+=1 -print(day) \ No newline at end of file diff --git "a/2002\354\266\224\354\233\224.py" "b/2002\354\266\224\354\233\224.py" deleted file mode 100644 index 9f932e1..0000000 --- "a/2002\354\266\224\354\233\224.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -deaguen = [input().rstrip() for _ in range(N)] -check = {car: False for car in deaguen} -youngsik = [input().rstrip() for _ in range(N)] - -idx = 0 -cnt = 0 -for last in youngsik: - while check[deaguen[idx]]: - idx += 1 - if last == deaguen[idx]: - idx += 1 - else: - cnt += 1 - check[last] = True -print(cnt) \ No newline at end of file diff --git "a/20040\354\202\254\354\235\264\355\201\264\352\262\214\354\236\204.py" "b/20040\354\202\254\354\235\264\355\201\264\352\262\214\354\236\204.py" deleted file mode 100644 index 20ee157..0000000 --- "a/20040\354\202\254\354\235\264\355\201\264\352\262\214\354\236\204.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline - -def find(x): - if x == arr[x]: - return x - arr[x] = find(arr[x]) - return arr[x] - -def union(x, y): - x = find(x) - y = find(y) - - if x < y: - arr[y] = x - else: - arr[x] = y - -N, M = map(int, input().split()) -arr = [i for i in range(N)] -for i in range(M): - a, b = map(int, input().split()) - if find(a) == find(b): - print(i+1) - exit() - union(a, b) -print(0) - diff --git "a/2004\354\241\260\355\225\251.py" "b/2004\354\241\260\355\225\251.py" index d221e30..3115474 100644 --- "a/2004\354\241\260\355\225\251.py" +++ "b/2004\354\241\260\355\225\251.py" @@ -1,18 +1,18 @@ -n, m = map(int, input().split()) - - -def two_count(n): - two = 0 - while n != 0: - n = n // 2 - two += n - return two - -def five_count(n): - five = 0 - while n != 0: - n = n // 5 - five += n - return five - +n, m = map(int, input().split()) + + +def two_count(n): + two = 0 + while n != 0: + n = n // 2 + two += n + return two + +def five_count(n): + five = 0 + while n != 0: + n = n // 5 + five += n + return five + print(min(two_count(n) - two_count(n - m) - two_count(m), five_count(n) - five_count(n - m) - five_count(m))) \ No newline at end of file diff --git "a/20055\354\273\250\353\262\240\354\235\264\354\226\264\353\262\250\355\212\270\354\234\204\354\235\230\353\241\234\353\264\207.py" "b/20055\354\273\250\353\262\240\354\235\264\354\226\264\353\262\250\355\212\270\354\234\204\354\235\230\353\241\234\353\264\207.py" deleted file mode 100644 index 08662f4..0000000 --- "a/20055\354\273\250\353\262\240\354\235\264\354\226\264\353\262\250\355\212\270\354\234\204\354\235\230\353\241\234\353\264\207.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -N, K = map(int, input().split()) -conveier = deque() -conveier.extend(list(map(int, input().split()))) -robot = deque() -robot.extend([0]*N) -K_cnt = conveier.count(0) -ans=0 -while K_cnt 0: - return 1 - elif tmp < 0: - return -1 - else: - return 0 - - -def findA(x1, y1, x2, y2): - if x1 == x2: - return INF - else: - return (y2 - y1) / (x2 - x1) - - -def findB(x1, y1, a): - return y1 - a * x1 - - -def findFunc(x1, y1, x2, y2): - a = findA(x1, y1, x2, y2) - if a == INF: - if y1 == y2: - return x1, y1, True - return x1, INF, True - b = findB(x1, y1, a) - return a, b, False - - -def findPoint(x1, y1, x2, y2, x3, y3, x4, y4): - a1, b1, flag1 = findFunc(x1, y1, x2, y2) - a2, b2, flag2 = findFunc(x3, y3, x4, y4) - if flag1: - if b1 == INF: - return a1, a2 * a1 + b2 - return x1, y1 - if flag2: - if b2 == INF: - return a2, a1 * a2 + b1 - return x3, y3 - else: - if a2 != a1: - return (b1 - b2) / (a2 - a1), (b1 * a2 - b2 * a1) / (a2 - a1) - else: - if min(x1, x2) <= max(x3, x4) and min(x3, x4) <= max(x1, x2) and min(y1, y2) <= max(y3, y4) and min(y3, y4) <= max(y1, y2): - if min(x1, x2) == max(x3, x4): - return min(x1, x2), min(x1, x2) * a1 + b1 - if max(x1, x2) == min(x3, x4): - return max(x1, x2), max(x1, x2) * a1 + b1 - return INF, INF - - -ans = 0 -if ccw(x1, y1, x2, y2, x3, y3) * ccw(x1, y1, x2, y2, x4, y4) == 0 and ccw(x3, y3, x4, y4, x1, y1) * ccw(x3, y3, x4, y4, x2, y2) == 0: - if min(x1, x2) <= max(x3, x4) and max(x1, x2) >= min(x3, x4) and min(y1, y2) <= max(y3, y4) and min(y3, y4) <= max(y1, y2): - ans = 1 -elif ccw(x1, y1, x2, y2, x3, y3) * ccw(x1, y1, x2, y2, x4, y4) <= 0 and ccw(x3, y3, x4, y4, x1, y1) * ccw(x3, y3, x4, y4, x2, y2) <= 0: - ans = 1 -print(ans) -if ans == 1: - xans, yans = findPoint(x1, y1, x2, y2, x3, y3, x4, y4) - if xans != INF and yans != INF: - if xans % 1 == 0: - xans = round(xans) - if yans % 1 == 0: - yans = round(yans) - print(xans, yans) \ No newline at end of file diff --git "a/20159 \353\217\231\354\236\221 \352\267\270\353\247\214 \353\260\221\354\236\245 \353\271\274\352\270\260\353\203\220.py" "b/20159 \353\217\231\354\236\221 \352\267\270\353\247\214 \353\260\221\354\236\245 \353\271\274\352\270\260\353\203\220.py" deleted file mode 100644 index 0a15d80..0000000 --- "a/20159 \353\217\231\354\236\221 \352\267\270\353\247\214 \353\260\221\354\236\245 \353\271\274\352\270\260\353\203\220.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -x = list(map(int, input().split())) -# 0, 2, 4 ... 밑장을 받거나 상대 주거나. 하고 홀수 idx를 받음. -even_sum, odd_sum = [0] * (N // 2), [0] * (N // 2) -even_sum[0], odd_sum[-1] = x[0], x[-1] -for i in range(1, N // 2): - even_sum[i] = x[2 * i] + even_sum[i - 1] - odd_sum[-i - 1] = x[-2 * i - 1] + odd_sum[-i] -max_sum = 0 -for i in range(len(even_sum)): - if not i == len(even_sum) - 1: - max_sum = max(max_sum, even_sum[i] + odd_sum[i + 1]) - max_sum = max(max_sum, even_sum[i] + odd_sum[i] - x[-1]) -max_sum = max(max_sum, odd_sum[0], even_sum[-1]) -print(max_sum) \ No newline at end of file diff --git "a/20162\352\260\204\354\213\235\355\214\214\355\213\260.py" "b/20162\352\260\204\354\213\235\355\214\214\355\213\260.py" deleted file mode 100644 index edba569..0000000 --- "a/20162\352\260\204\354\213\235\355\214\214\355\213\260.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -# 파티 만족도 : 파티동안 먹은 모든 간식의 평점 합 / - -N = int(input()) -scores = [int(input()) for _ in range(N)] -dp = [scores[i] for i in range(N)] -for i in range(1,N): - tmp=[0] - for j in range(i): - if scores[j] < scores[i]: - tmp.append(dp[j]) - dp[i] = max(tmp) + scores[i] -print(max(dp)) diff --git "a/20164 \355\231\200\354\210\230 \355\231\200\353\246\255 \355\230\270\354\204\235.py" "b/20164 \355\231\200\354\210\230 \355\231\200\353\246\255 \355\230\270\354\204\235.py" deleted file mode 100644 index 1f628fa..0000000 --- "a/20164 \355\231\200\354\210\230 \355\231\200\353\246\255 \355\230\270\354\204\235.py" +++ /dev/null @@ -1,36 +0,0 @@ -import sys -input = sys.stdin.readline - - -def count_odd(n): - cnt = 0 - for i in n: - if int(i) & 1: - cnt += 1 - return cnt - - -def divided(n, cnt): - global max_v, min_v - s = str(n) - cnt += count_odd(s) - - if len(s) == 1: - min_v = min(min_v, cnt) - max_v = max(max_v, cnt) - return - elif len(s) == 2: - divided(n // 10 + n % 10, cnt) - else: - for i in range(1, len(s) - 1): - for j in range(i + 1, len(s)): - new_num = int(s[:i]) + int(s[i: j]) + int(s[j:]) - divided(new_num, cnt) - -n = int(input()) -min_v = float('inf') -max_v = 0 - -divided(n, 0) - -print(min_v, max_v) \ No newline at end of file diff --git "a/20168 \352\263\250\353\252\251\353\214\200\354\236\245\355\230\270\354\204\235 \352\270\260\353\212\245\354\204\261.py" "b/20168 \352\263\250\353\252\251\353\214\200\354\236\245\355\230\270\354\204\235 \352\270\260\353\212\245\354\204\261.py" deleted file mode 100644 index 675cb50..0000000 --- "a/20168 \352\263\250\353\252\251\353\214\200\354\236\245\355\230\270\354\204\235 \352\270\260\353\212\245\354\204\261.py" +++ /dev/null @@ -1,39 +0,0 @@ -import heapq -import sys -input = sys.stdin.readline - - -def dijkstra(mid): - dist = [float('inf')] * (N + 1) - dist[start] = 0 - H = [(0, start)] - while H: - dist, cur_node = heapq.heappop(H) - if dist[cur_node] < dist: - continue - for next_node, cost in graph[cur_node]: - if cost > mid: - continue - if dist[next_node] > dist + cost: - dist[next_node] = dist + cost - heapq.heappush(H, (dist + cost, next_node)) - return dist[end] <= cost - -N, mid, start, end, cost = map(int, input().split()) -graph = {i: [] for i in range(1, N + 1)} -costs = set() -for i in range(mid): - a,b,c = map(int,input().split()) - graph[a].append((b,c)) - graph[b].append((a,c)) - costs.add(c) -costs = sorted(costs) -left = 0 -right = len(costs) -while left < right: - mid = (left + right) // 2 - if dijkstra(costs[mid]): - right = mid - else: - left = mid + 1 -print(costs[left] if left < len(costs) else -1) \ No newline at end of file diff --git "a/2018\354\210\230\353\223\244\354\235\230\355\225\2515.py" "b/2018\354\210\230\353\223\244\354\235\230\355\225\2515.py" deleted file mode 100644 index 98200d2..0000000 --- "a/2018\354\210\230\353\223\244\354\235\230\355\225\2515.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -prex_sum, left = 0, 0 -answer = 0 - -# 슬라이딩 윈도우 -for right in range(1,N+1): - # 결론적으로 end는 기존 슬라이딩 윈도우 처럼 일정 간격이 고정이 아니라 - # 일정 합 이상이되면 알아서 그 간격이 줄어드는 시스템이므로 한번 순회로 전부 조사 가능. - while left < N and prex_sum < N: - prex_sum += left+1 - left += 1 - if prex_sum == N: - answer += 1 - prex_sum -= right -print(answer) \ No newline at end of file diff --git "a/2018\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\353\260\251\352\270\210\352\267\270\352\263\241.py" "b/2018\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\353\260\251\352\270\210\352\267\270\352\263\241.py" deleted file mode 100644 index 1efff5d..0000000 --- "a/2018\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\353\260\251\352\270\210\352\267\270\352\263\241.py" +++ /dev/null @@ -1,68 +0,0 @@ -# #이 붙은 음표는 소문자로 변경 -def changecode(music_): - music_ = music_.replace('C#', 'c') - music_ = music_.replace('D#', 'd') - music_ = music_.replace('F#', 'f') - music_ = music_.replace('G#', 'g') - music_ = music_.replace('A#', 'a') - return music_ - -def caltime(musicinfo_): - starttime = musicinfo_[0] - endtime = musicinfo_[1] - hour = 1 * (int(endtime.split(':')[0]) - int(starttime.split(':')[0])) - if hour == 0: - total = int(endtime.split(':')[1]) - int(starttime.split(':')[1]) - else: - total = 60 * hour + int(endtime.split(':')[1]) - int(starttime.split(':')[1]) - - return total - -def solution(m, musicinfos): - answer = [] - m = changecode(m) - for idx, musicinfo in enumerate(musicinfos): - musicinfo = changecode(musicinfo) - musicinfo = musicinfo.split(',') - time = caltime(musicinfo) - - # 길이가 시간보다 더 긴 경우 - if len(musicinfo[3]) >= time : - melody = musicinfo[3][0:time] - else: - # 시간을 계산해서 몫과 나머지로 계산 - # 다른 사람 풀이 : q, r = divmod(time,len(musicinfo[3])) - a = time // len(musicinfo[3]) - b = time % len(musicinfo[3]) - melody = musicinfo[3] * a + musicinfo[3][0:b] - # 노래가 melody에 포함되면 정답후보에 저장 - if m in melody: - answer.append([idx, time, musicinfo[2]]) - # 정답이 있는 경우 - if len(answer) != 0: - # time -> index 기준으로 정렬 - answer = sorted(answer, key = lambda x: (-x[1], x[0])) - return answer[0][2] - # 정답이 없는 경우 - return "(None)" - - - - # 다른풀이 - -def shap_to_lower(s): - s = s.replace('C#','c').replace('D#','d').replace('F#','f').replace('G#','g').replace('A#','a') - return s - -def solution(m,musicinfos): - answer=[0,'(None)'] # time_len, title - m = shap_to_lower(m) - for info in musicinfos: - split_info = info.split(',') - time_length = (int(split_info[1][:2])-int(split_info[0][:2]))*60+int(split_info[1][-2:])-int(split_info[0][-2:]) - title = split_info[2] - part_notes = shap_to_lower(split_info[-1]) - full_notes = part_notes*(time_length//len(part_notes))+part_notes[:time_length%len(part_notes)] - if m in full_notes and time_length>answer[0]: - answer=[time_length,title] - return answer[-1] \ No newline at end of file diff --git "a/2018\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\355\224\204\353\240\214\354\246\2104\353\270\224\353\241\235.py" "b/2018\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\355\224\204\353\240\214\354\246\2104\353\270\224\353\241\235.py" deleted file mode 100644 index 08dddd5..0000000 --- "a/2018\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\355\224\204\353\240\214\354\246\2104\353\270\224\353\241\235.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline - -# 파이썬 -def pop_num(b, m, n): - pop_set = set() - # search - for i in range(1, n): - for j in range(1, m): - if b[i][j] == b[i-1][j-1] == b[i-1][j] == b[i][j-1] != '_': - pop_set |= set([(i, j), (i-1, j-1), (i-1, j), (i, j-1)]) - # set_board - for i, j in pop_set: - b[i][j] = 0 - for i, row in enumerate(b): - empty = ['_'] * row.count(0) - b[i] = empty + [block for block in row if block != 0] - return len(pop_set) - -def solution(m, n, board): - count = 0 - b = list(map(list,zip(*board))) - while True: - pop = pop_num(b, m, n) - if pop == 0: return count - count += pop \ No newline at end of file diff --git "a/2019\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" "b/2019\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" deleted file mode 100644 index 7569fa5..0000000 --- "a/2019\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" +++ /dev/null @@ -1,55 +0,0 @@ -import sys -input = sys.stdin.readline - -def solution(record): - answer = [] - userdict = {} - # mes : record의 message - # message를 받음과 동시에 유저 아이디 : 닉네임을 저장 - # Enter, Change가 들어온 경우 dictionary에 저장 - for mes in record: - if (mes.split(' ')[0] == 'Enter') | (mes.split(' ')[0] == 'Change'): - userdict[mes.split(' ')[1]] = mes.split(' ')[2] - - # for문을 돌면서, 하나씩 출력 - for mes in record: - if mes.split(' ')[0] == 'Enter': - # userdict[mes.split(' ')[1]] + '님이 들어왔습니다.' 이런식으로 해도 가능 - answer.append("{}님이 들어왔습니다.".format(userdict[mes.split(' ')[1]])) - elif mes.split(' ')[0] == 'Leave': - answer.append("{}님이 나갔습니다.".format(userdict[mes.split(' ')[1]])) - else: - pass - return answer - - - - -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -def solution(record): - answer = [] - namespace = {} - printer = {'Enter':'님이 들어왔습니다.', 'Leave':'님이 나갔습니다.'} - for r in record: - rr = r.split(' ') - if rr[0] in ['Enter', 'Change']: - namespace[rr[1]] = rr[2] - - for r in record: - if r.split(' ')[0] != 'Change': - answer.append(namespace[r.split(' ')[1]] + printer[r.split(' ')[0]]) - - return answer \ No newline at end of file diff --git "a/20207\353\213\254\353\240\245.py" "b/20207\353\213\254\353\240\245.py" deleted file mode 100644 index 48d3425..0000000 --- "a/20207\353\213\254\353\240\245.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -sch = [0]*(366) -for _ in range(N): - a, b = map(int, input().split()) - for i in range(a,b+1): - sch[i] += 1 - -area = 0 -max_h = 0 -for i in range(1,366): - if not sch[i-1] and sch[i]: - left = i - if max_h < sch[i]: - max_h = sch[i] - if not sch[i] and sch[i-1]: - right = i - area += (right-left)* max_h - max_h = 0 - left = 0 - right = 0 -area += (366-left)* max_h - -print(area) \ No newline at end of file diff --git "a/2020\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\352\260\200\354\202\254.py" "b/2020\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\352\260\200\354\202\254.py" deleted file mode 100644 index e72e55b..0000000 --- "a/2020\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234_\352\260\200\354\202\254.py" +++ /dev/null @@ -1,47 +0,0 @@ -class Node: - def __init__(self): - self.child = {} - self.count = 0 - -class Trie: - def __init__(self): - self.root = Node() - - def insert(self,word): - node = self.root - - for char in word: - if char not in node.child: - node.child[char] = Node() - node.count += 1 - node = node.child[char] - - def startswitch(self,prefix): - node = self.root - - for char in prefix: - if char=='?': - return node.count - if char not in node.child: - return 0 - node = node.child[char] - return node.count - -def solution(words, queries): - trielength = {i: Trie() for i in range(1,10001)} - re_trielength = {i: Trie() for i in range(1,10001)} - answer = [] - - for word in words: - length = len(word) - trielength[length].insert(word) - re_trielength[length].insert(word[::-1]) - - for query in queries: - length = len(query) - if query[0] !='?': - answer.append(trielength[length].startswitch(query)) - else: - answer.append(re_trielength[length].startswitch(query[::-1])) - - return answer \ No newline at end of file diff --git "a/2021 kakao \353\251\224\353\211\264 \353\246\254\353\211\264\354\226\274.py" "b/2021 kakao \353\251\224\353\211\264 \353\246\254\353\211\264\354\226\274.py" deleted file mode 100644 index 6528b53..0000000 --- "a/2021 kakao \353\251\224\353\211\264 \353\246\254\353\211\264\354\226\274.py" +++ /dev/null @@ -1,29 +0,0 @@ -from collections import defaultdict -from itertools import combinations - -def solution(orders, course): - answer = [] - sets = defaultdict(int) - for order in orders: - order = sorted(list(order)) - for num in course: - for new_comb in combinations(order, num): - sets[''.join(list(new_comb))] += 1 - ans_set = {num: [] for num in course} - for comb in sets: - if sets[comb] < 2: - continue - n = len(comb) - if n in ans_set: - if not ans_set[n]: - ans_set[n].append(comb) - elif sets[ans_set[n][-1]] < sets[comb] : - ans_set[n].clear() - ans_set[n].append(comb) - elif sets[ans_set[n][-1]] == sets[comb]: - ans_set[n].append(comb) - for num in ans_set: - for comb in ans_set[num]: - answer.append(comb) - answer.sort() - return answer \ No newline at end of file diff --git "a/2021 kakao \354\213\240\352\267\234 \354\225\204\354\235\264\353\224\224 \354\266\224\354\262\234.py" "b/2021 kakao \354\213\240\352\267\234 \354\225\204\354\235\264\353\224\224 \354\266\224\354\262\234.py" deleted file mode 100644 index ab138d7..0000000 --- "a/2021 kakao \354\213\240\352\267\234 \354\225\204\354\235\264\353\224\224 \354\266\224\354\262\234.py" +++ /dev/null @@ -1,18 +0,0 @@ -def solution(new_id): - answer = '' - for char in new_id: - if char.isalpha(): - answer += char.lower() - elif char == '.' and answer and answer[-1] != '.': - answer += '.' - elif char.isdigit() or char in '-_': - answer += char - if not answer: - answer += 'a' - elif len(answer) > 15: - answer = answer[:15] - if answer[-1] == '.': - answer = answer[:-1] - while len(answer) < 3: - answer = answer + answer[-1] - return answer \ No newline at end of file diff --git "a/2021 kakao \354\271\264\353\223\234 \354\247\235 \353\247\236\354\266\224\352\270\260.py" "b/2021 kakao \354\271\264\353\223\234 \354\247\235 \353\247\236\354\266\224\352\270\260.py" deleted file mode 100644 index 5218648..0000000 --- "a/2021 kakao \354\271\264\353\223\234 \354\247\235 \353\247\236\354\266\224\352\270\260.py" +++ /dev/null @@ -1,82 +0,0 @@ -from collections import defaultdict -from heapq import heappush, heappop -from itertools import permutations - - -def solution(board, r, c): - - def ctrl_move(x, y, dx, dy, visited): - for i in range(1, 4): - nx, ny = x + dx * i, y + dy * i - if (nx, ny) in visited and not visited[(nx, ny)]: - return (nx, ny) - if dx == 1 and nx >= 3: - return (3, ny) - elif dx == -1 and nx <= 0: - return (0, ny) - elif dy == 1 and ny >= 3: - return (nx, 3) - elif dy == -1 and ny <= 0: - return (nx, 0) - - - def make_count(target, x, y, visited): - q = [] - heappush(q, (0, x, y)) - check = [[float('inf')] * 4 for _ in range(4)] - check[x][y] = True - while q: - dist, x, y = heappop(q) - if (x, y) == target: - return dist + 1 - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < 4 and 0 <= ny < 4: - if check[nx][ny] > dist + 1: - check[nx][ny] = dist + 1 - heappush(q, (dist + 1, nx, ny)) - ctrl_x, ctrl_y = ctrl_move(x, y, dx, dy, visited) - if check[ctrl_x][ctrl_y] > dist + 1: - check[ctrl_x][ctrl_y] = dist + 1 - heappush(q, (dist + 1, ctrl_x, ctrl_y)) - - - - def dfs(sequence, x, y, depth, key, cnt, visited): - global min_cnt - if cnt > min_cnt: - return - if depth == len(sequence): - min_cnt = min(min_cnt, cnt) - return - if key: - for target in num_set[sequence[depth]]: - if visited[target]: - continue - dist = make_count(target, x, y, visited) - visited[target] = True - dfs(sequence, target[0], target[1], depth + 1, 0, cnt + dist, visited) - visited[target] = False - else: - for target in num_set[sequence[depth]]: - dist = make_count(target, x, y, visited) - visited[target] = True - dfs(sequence, target[0], target[1], depth, 1, cnt + dist, visited) - visited[target] = False - - - global min_cnt - num_set = defaultdict(list) - delta = ((0, 1), (1, 0), (-1, 0), (0, -1)) - visited = {} - for i in range(4): - for j in range(4): - if board[i][j]: - num_set[board[i][j]].append((i, j)) - visited[(i, j)] = False - - min_cnt = float('inf') - for each_set in permutations([num for num in num_set], len(num_set)): - dfs(each_set, r, c, 0, 0, 0, visited) - - return min_cnt \ No newline at end of file diff --git "a/2021 kakao \354\271\264\353\223\234 \354\247\2352.py" "b/2021 kakao \354\271\264\353\223\234 \354\247\2352.py" deleted file mode 100644 index 90cbbbc..0000000 --- "a/2021 kakao \354\271\264\353\223\234 \354\247\2352.py" +++ /dev/null @@ -1,59 +0,0 @@ -from collections import deque - - -def move(board, x, y, dx, dy): - nx, ny = x + dx, y + dy - if 0 <= nx < 4 and 0 <= ny < 4: - if board[nx * 4 + ny] == "0": - return move(board, nx, ny, dx, dy) - else: - return (nx, ny) - else: - return (x, y) - - -def solution(b, r, c): - answer = 0 - delta = [(1, 0), (-1, 0), (0, 1), (0, -1)] - board = "" - for row in b: - board += ''.join(list(map(str, row))) - q = deque([]) - enter = -1 - q.append((r, c, board, 0, enter)) - state = set() - - while q: - x, y, board, cnt, e = q.popleft() - if (x, y, board, cnt, e) in state: - continue - state.add((x, y, board, cnt, e)) - - cur_position = 4 * x + y - if board.count('0') == 16: - return cnt - - # 4 방향 이동 - for dx, dy in delta: - ny, nx = y + dy, x + dx - if 0 <= nx < 4 and 0 <= ny < 4: - q.append((nx, ny, board, cnt + 1, e)) - - # Ctrl + 4 방향 이동 - for dx, dy in delta: - nx, ny = move(board, x, y, dx, dy) - if ny == y and nx == x: - continue - q.append((nx, ny, board, cnt + 1, e)) - - # enter를 하는 경우 - if board[cur_position] != 0: - if e == -1: - n_e = cur_position - q.append((x, y, board, cnt + 1, n_e)) - else: - if e != cur_position and board[e] == board[cur_position]: - n_b = board.replace(board[e], '0') - q.append((x, y, n_b, cnt + 1, -1)) - - return answer \ No newline at end of file diff --git "a/2026\354\206\214\355\222\215.py" "b/2026\354\206\214\355\222\215.py" deleted file mode 100644 index a604db2..0000000 --- "a/2026\354\206\214\355\222\215.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def dfs(v,arr): - if len(arr)==K: - for num in arr: - print(num) - exit() - for i in range(v+1,N+1): - if not visited[i]: - for num in arr: - if num not in graph[i]: - break - else: - visited[i] = True - dfs(i,arr+[i]) - - - -K, N, F = map(int, input().split()) -graph = {i: [] for i in range(1,N+1)} -for _ in range(F): - a, b = map(int, input().split()) - graph[a] += [b] - graph[b] += [a] - -for i in range(1,N+1): - visited = {i: False for i in range(1,N+1)} - visited[i] = True - dfs(i,[i]) - -print(-1) \ No newline at end of file diff --git "a/20327\353\260\260\354\227\264\353\217\214\353\246\254\352\270\2606.py" "b/20327\353\260\260\354\227\264\353\217\214\353\246\254\352\270\2606.py" deleted file mode 100644 index 5f4f963..0000000 --- "a/20327\353\260\260\354\227\264\353\217\214\353\246\254\352\270\2606.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -def divide_matrix(N,start_x,start_y,end_x,end_y,target_size,rotate_num): - if N==target_size: - rotate_matrix(N,start_x,start_y,end_x,end_y,target_size,rotate_num) - half = 1<<(N-1) - divide_matrix(N-1,start_x,start_y,half,half,target_size,rotate_num) - divide_matrix(N-1,start_x,half,half,end_y,target_size,rotate_num) - divide_matrix(N-1,half,start_y,end_x,half,target_size,rotate_num) - divide_matrix(N-1,half,half,end_x,end_y,target_size,rotate_num) - -def rotate_matrix(N,start_x,start_y,end_x,end_y,target_size,rotate_num): - if rotate_num==1: - pass - - -N,R = map(int,input().split()) -matrix = [list(map(int,input().split())) for _ in range(1<=n: - print(i) \ No newline at end of file diff --git "a/2042\352\265\254\352\260\204\355\225\251\352\265\254\355\225\230\352\270\260_segtree.py" "b/2042\352\265\254\352\260\204\355\225\251\352\265\254\355\225\230\352\270\260_segtree.py" deleted file mode 100644 index 6f170b0..0000000 --- "a/2042\352\265\254\352\260\204\355\225\251\352\265\254\355\225\230\352\270\260_segtree.py" +++ /dev/null @@ -1,60 +0,0 @@ -import sys -input = sys.stdin.readline - -# 세그먼트 트리 생성 -def init(node, start, end): - # node가 leaf 노드인 경우 배열의 원소 값을 반환. - if start == end : - tree[node] = l[start] - return tree[node] - else : - # 재귀함수를 이용하여 왼쪽 자식과 오른쪽 자식 트리를 만들고 합을 저장. - tree[node] = init(node*2, start, (start+end)//2) + init(node*2+1, (start+end)//2+1, end) - return tree[node] - -# 구간 합 구하기 -# node가 담당하는 구간 [start, end] -# 합을 구해야하는 구간 [left, right] -def subSum(node, start, end, left, right) : - # 겹치지 않기 때문에, 더 이상 탐색을 이어갈 필요가 없다. - if left > end or right < start : - return 0 - # 구해야하는 합의 범위는 [left, right]인데, [start, end]는 그 범위에 모두 포함되고 - # 그 node의 자식도 모두 포함되기 때문에 더 이상 호출을 하는 것은 비효율적이다. - if left <= start and end <= right : - return tree[node] - # 왼쪽 자식과 오른쪽 자식을 루트로 하는 트리에서 다시 탐색을 시작해야한다. - return subSum(node*2, start, (start+end)//2, left, right) + subSum(node*2 + 1, (start+end)//2+1, end, left, right) - - -def update(node, start, end, index, diff) : - if index < start or index > end : - return - tree[node] += diff - # 리프 노드가 아닌 경우에는 자식도 변경해줘야 하기 때문에 검사해야함. - if start != end : - update(node*2, start, (start+end)//2, index, diff) - update(node*2+1, (start+end)//2+1, end, index, diff) - - -n, m, k = map(int, input().rstrip().split()) -l = [] -tree = [0] * 3000000 - -for _ in range(n) : - l.append(int(input().rstrip())) - -init(1, 0, n-1) - -for _ in range(m+k) : - a, b, c = map(int, input().rstrip().split()) - - # 1인경우 바꿔주고 - if a == 1 : - b = b-1 - diff = c - l[b] - l[b] = c - update(1, 0, n-1, b, diff) - # 2인경우 구간합을 반환한다. - elif a == 2 : - print(subSum(1, 0, n-1 ,b-1, c-1)) diff --git "a/20442\343\205\213\343\205\213\353\243\250\343\205\213\343\205\213.py" "b/20442\343\205\213\343\205\213\353\243\250\343\205\213\343\205\213.py" deleted file mode 100644 index 5390178..0000000 --- "a/20442\343\205\213\343\205\213\353\243\250\343\205\213\343\205\213.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin. readline - -s = input().strip() -left_K_cnt = [] -rignt_K_count = [] -# 정방향에서 K갯수 세면서 R나올때마다 cnt를 lk에 저장 -cnt = 0 -for i in s: - if i == 'K': - cnt += 1 - else: - left_K_cnt.append(cnt) -# 역방향에서 K세면서 R나올때마다 cnt를 rk에 저장. -cnt = 0 -for i in s[::-1]: - if i == 'K': - cnt += 1 - else: - rignt_K_count.append(cnt) -rignt_K_count.reverse() -# rk뒤집음. -# l,r 양끝에서 부터 한칸씩 땡기면서 검사. -l, r = 0, len(left_K_cnt) - 1 -ans = 0 -# l 과 r이 만나면 조사 끝. -while l <= r: - # 답은 r-l+1즉 R의 총 갯수 + 왼쪽 또는 오른족에 있는 K의 갯수중 작은 값. - ans = max(ans, r - l + 1 + 2 * min(left_K_cnt[l], rignt_K_count[r])) - # l의 왼쪽에 있는 K의 갯수가 r의 오른쪽에 있는 K의 갯수보다 적으면 맞춰주기 위해 l을 오른쪽으로 땡김 - if left_K_cnt[l] < rignt_K_count[r]: - l += 1 - else: - r -= 1 -print(ans) diff --git "a/20551 Sort \353\247\210\354\212\244\355\204\260 \353\260\260\354\247\200\355\233\210\354\235\230 \355\233\204\352\263\204\354\236\220.py" "b/20551 Sort \353\247\210\354\212\244\355\204\260 \353\260\260\354\247\200\355\233\210\354\235\230 \355\233\204\352\263\204\354\236\220.py" deleted file mode 100644 index 6778603..0000000 --- "a/20551 Sort \353\247\210\354\212\244\355\204\260 \353\260\260\354\247\200\355\233\210\354\235\230 \355\233\204\352\263\204\354\236\220.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -a_idx = {} -N, M = map(int, input().split()) -A = sorted([int(input()) for _ in range(N)]) -for i in range(N): - if A[i] not in a_idx: - a_idx[A[i]] = i -D = [int(input()) for _ in range(M)] -for num in D: - if num in a_idx: - print(a_idx[num]) - else: - print(-1) \ No newline at end of file diff --git "a/2058 \354\233\220\354\236\220\354\235\230 \354\227\220\353\204\210\354\247\200.py" "b/2058 \354\233\220\354\236\220\354\235\230 \354\227\220\353\204\210\354\247\200.py" deleted file mode 100644 index bf86f0c..0000000 --- "a/2058 \354\233\220\354\236\220\354\235\230 \354\227\220\353\204\210\354\247\200.py" +++ /dev/null @@ -1,26 +0,0 @@ - -import sys -input = sys.stdin.readline - -# tree에 진입합니다. -def dfs(cur_atom): - visited[cur_atom] = True - dp[cur_atom][1] = cur_atom - for gap in plus: # plus는 양성자크기들의 배열입니다. - for next_atom in (cur_atom+gap, cur_atom-gap): # 다음 노드는 지금 노드에서 양성자를 더해 갈수있는 위치입니다. - if next_atom in visited and not visited[next_atom]: - dfs(next_atom) - # 상태인자 1은 현 노드를 가져가는 선택지, 0은 가져가지 않는 선택지입니다. - dp[cur_atom][0] += max(dp[next_atom][1], dp[next_atom][0]) - dp[cur_atom][1] += dp[next_atom][0] - -# 각 atom_e상태가 plus를 받아들이거나 빼서 다른 atom_e에 도달할 수 있다. -# 그러나 인접한 에너지 준위가 존재하면 안된다. -# 어떤 atom_e의 조합을 선택해야 합이 최대가 되는가? -N, M = map(int, input().split()) -atom_e = [int(input()) for _ in range(N)] -plus = [int(input()) for _ in range(M)] # 각 에너지 준위 간의 차이값이 될 선택지인 양성자 크기 배열 -visited = {atom: False for atom in atom_e} # 모든 에너지준위에 대해 검사 -dp = {atom: [0,0] for atom in atom_e} -dfs(atom_e[0]) -print(max(dp[atom_e[0]][0], dp[atom_e[0]][1])) \ No newline at end of file diff --git "a/2086 \355\224\274\353\263\264\353\202\230\354\271\230\354\210\230\354\235\230\355\225\251.py" "b/2086 \355\224\274\353\263\264\353\202\230\354\271\230\354\210\230\354\235\230\355\225\251.py" deleted file mode 100644 index 6d66313..0000000 --- "a/2086 \355\224\274\353\263\264\353\202\230\354\271\230\354\210\230\354\235\230\355\225\251.py" +++ /dev/null @@ -1,31 +0,0 @@ - -n = int(input()) -odd = (n + 1) // 2 * 2 -Even = (n // 2 * 2) + 1 -ans = 0 -for n in (odd,Even): - A = [[1, 0], [0, 1]] - B = [[1, 1], [1, 0]] - - def matrix_mul(a, b): - result = [[0] * 2 for _ in range(2)] - - for i in range(2): - for j in range(2): - for k in range(2): - result[i][j] += a[i][k] * b[k][j] - - for i in range(2): - for j in range(2): - result[i][j] %= 1000000007 - - return result - - while n: - if n & 1: - A = matrix_mul(A, B) - B = matrix_mul(B, B) - - n //= 2 - - ans += A[1][0] diff --git "a/2089_-2\354\247\204\354\210\230.py" "b/2089_-2\354\247\204\354\210\230.py" index fad238c..c1296fc 100644 --- "a/2089_-2\354\247\204\354\210\230.py" +++ "b/2089_-2\354\247\204\354\210\230.py" @@ -1,18 +1,18 @@ -import sys - -N = int(sys.stdin.readline()) - -if not N: - sys.stdout.write('0') - exit() -res = '' -while N: - if N%(-2): - res = '1' + res - N = N//-2 + 1 - else: - res = '0' + res - N //= -2 - -sys.stdout.write(res) - +import sys + +N = int(sys.stdin.readline()) + +if not N: + sys.stdout.write('0') + exit() +res = '' +while N: + if N%(-2): + res = '1' + res + N = N//-2 + 1 + else: + res = '0' + res + N //= -2 + +sys.stdout.write(res) + diff --git "a/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264.py" "b/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264.py" index 803946b..a5ca2f0 100644 --- "a/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264.py" +++ "b/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264.py" @@ -1,26 +1,26 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -N, K = map(int,input().split()) -A = list(map(int,input().split())) - -# 200000이하 N, 같은 정수를 K개 이하 포함한 최장 연속 부분수열. -count = defaultdict(int) -max_length = 0 -last_start = 0 - -for i in range(N): - count[A[i]] += 1 - - if count[A[i]] > K: # 탐색 -> A숫자 count가 K+1개 되면 lenth i-0기록 -> - if max_length < i- last_start: # -> 또 나오면 max_length 비교. 최대면 최신화. - max_length = i- last_start - while count[A[i]] > K: # 처음으로 A숫자 나온 인덱스 뒤부터 재탐색 (시간초과나면 heapq나 deque) - count[A[last_start]] -= 1 # 초기화 되는 index 앞 count 전부 초기화. - last_start +=1 - else: - if max_length < i+1- last_start: # -> 수열 끝까지 가면 max_length 측정 - max_length = i+1- last_start - +import sys +input = sys.stdin.readline +from collections import defaultdict + +N, K = map(int,input().split()) +A = list(map(int,input().split())) + +# 200000이하 N, 같은 정수를 K개 이하 포함한 최장 연속 부분수열. +count = defaultdict(int) +max_length = 0 +last_start = 0 + +for i in range(N): + count[A[i]] += 1 + + if count[A[i]] > K: # 탐색 -> A숫자 count가 K+1개 되면 lenth i-0기록 -> + if max_length < i- last_start: # -> 또 나오면 max_length 비교. 최대면 최신화. + max_length = i- last_start + while count[A[i]] > K: # 처음으로 A숫자 나온 인덱스 뒤부터 재탐색 (시간초과나면 heapq나 deque) + count[A[last_start]] -= 1 # 초기화 되는 index 앞 count 전부 초기화. + last_start +=1 + else: + if max_length < i+1- last_start: # -> 수열 끝까지 가면 max_length 측정 + max_length = i+1- last_start + print(max_length) \ No newline at end of file diff --git "a/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264_defalut.py" "b/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264_defalut.py" index f7afee8..51756e2 100644 --- "a/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264_defalut.py" +++ "b/20922\352\262\271\354\271\230\353\212\224 \352\261\264 \354\213\253\354\226\264_defalut.py" @@ -1,32 +1,32 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -N, K = map(int,input().split()) -A = list(map(int,input().split())) - -# 200000이하 N, 같은 정수를 K개 이하 포함한 최장 연속 부분수열. -count = defaultdict(int) -point_check = defaultdict(list) -max_length = 0 -last_start = 0 - -for i in range(N): - count[A[i]] += 1 - point_check[A[i]] +=[i] - - if count[A[i]] > K: # 탐색 -> A숫자 count가 K+1개 되면 lenth i-0기록 -> - if max_length < i- last_start: # -> 또 나오면 max_length 비교. 최대면 최신화. - max_length = i- last_start - - for j in range(last_start,point_check[A[i]][0]): #count, point 초기화. - count[A[j]] -= 1 - point_check[A[j]].pop(0) - count[A[i]] -= 1 - last_start = point_check[A[i]].pop(0)+1 # 처음으로 A숫자 나온 인덱스 뒤부터 재탐색 (시간초과나면 heapq나 deque) - - else: - if max_length < i+1- last_start: # -> 수열 끝까지 가면 max_length 측정 - max_length = i+1- last_start - +import sys +input = sys.stdin.readline +from collections import defaultdict + +N, K = map(int,input().split()) +A = list(map(int,input().split())) + +# 200000이하 N, 같은 정수를 K개 이하 포함한 최장 연속 부분수열. +count = defaultdict(int) +point_check = defaultdict(list) +max_length = 0 +last_start = 0 + +for i in range(N): + count[A[i]] += 1 + point_check[A[i]] +=[i] + + if count[A[i]] > K: # 탐색 -> A숫자 count가 K+1개 되면 lenth i-0기록 -> + if max_length < i- last_start: # -> 또 나오면 max_length 비교. 최대면 최신화. + max_length = i- last_start + + for j in range(last_start,point_check[A[i]][0]): #count, point 초기화. + count[A[j]] -= 1 + point_check[A[j]].pop(0) + count[A[i]] -= 1 + last_start = point_check[A[i]].pop(0)+1 # 처음으로 A숫자 나온 인덱스 뒤부터 재탐색 (시간초과나면 heapq나 deque) + + else: + if max_length < i+1- last_start: # -> 수열 끝까지 가면 max_length 측정 + max_length = i+1- last_start + print(max_length) \ No newline at end of file diff --git "a/2096\353\202\264\353\240\244\352\260\200\352\270\260.py" "b/2096\353\202\264\353\240\244\352\260\200\352\270\260.py" deleted file mode 100644 index 723f320..0000000 --- "a/2096\353\202\264\353\240\244\352\260\200\352\270\260.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = [list(map(int, input().split())) for _ in range(N)] -max_sum = [[0,0,0],[0,0,0]] -min_sum = [[0,0,0],[0,0,0]] -# 슬라이딩 윈도우 N까지 미끄러짐. // dp를 같이 쓰는데 dp를 모두 저장하는 것이 아니라 전의 값과 현재 계산할 칸만 남겨둠. -for i in range(0,N): - - max_sum[1][0] = max(max_sum[0][1], max_sum[0][0]) + arr[i][0] - max_sum[1][1] = max(max_sum[0][1], max_sum[0][2], max_sum[0][0]) + arr[i][1] - max_sum[1][2] = max(max_sum[0][1], max_sum[0][2]) + arr[i][2] - - min_sum[1][0] = min(min_sum[0][0], min_sum[0][1]) + arr[i][0] - min_sum[1][1] = min(min_sum[0][1], min_sum[0][2], min_sum[0][0]) + arr[i][1] - min_sum[1][2] = min(min_sum[0][1], min_sum[0][2]) + arr[i][2] - - max_sum.append(max_sum.pop(0)) - min_sum.append(min_sum.pop(0)) - -print(max(max_sum[0]), min(min_sum[0])) - -# 아래도 동일한 방식이나 한줄에 연산을 해 값이 바뀌는것을막음(tmp배열을 쓰지 않도록 설계 이전값 없이 현재값에 계속 최신화 하게끔 함.) -# import sys -# input = sys.stdin.readline -# n = int(input()) -# s = [list(map(int, input().split())) for i in range(n)] -# lax, cax, rax = s[0][0], s[0][1], s[0][2] -# lin, cin, rin = s[0][0], s[0][1], s[0][2] -# for i in range(1, n): -# lax, cax, rax = max(lax, cax) + s[i][0], max(lax, cax, rax) + s[i][1], max(cax, rax) + s[i][2] -# lin, cin, rin = min(lin, cin) + s[i][0], min(lin, cin, rin) + s[i][1], min(cin, rin) + s[i][2] -# print(max(lax, cax, rax), min(lin, cin, rin)) \ No newline at end of file diff --git "a/2098 \354\231\270\355\214\220\354\233\220\354\210\234\355\232\214_\353\271\204\355\212\270\353\247\210\354\212\244\355\202\271.py" "b/2098 \354\231\270\355\214\220\354\233\220\354\210\234\355\232\214_\353\271\204\355\212\270\353\247\210\354\212\244\355\202\271.py" deleted file mode 100644 index 66b34ac..0000000 --- "a/2098 \354\231\270\355\214\220\354\233\220\354\210\234\355\232\214_\353\271\204\355\212\270\353\247\210\354\212\244\355\202\271.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -def find(now, before): - # 남아있는 경로를 이미 방문한 적이 있음 (지금 있는곳과 켜진 경로와 꺼진 경로가 예전꺼랑 같으면)그냥 반환. - if dp[now][before]: - return dp[now][before] - # # 모두 방문한 경우 내가 있는 마을에서 1번 마을로 갈 길이 있다면(비용이 있다면) 그 비용에 대해 반환 -> 반환되면 cost에 path[now][i]와 합쳐저 최솟값을 찾아감. - if before == (1< 0: - return path[now][0] - else: - # 못가면 무한대 반환. -> 결국 min연산에 의해 경로 삭제됨. - return sys.maxsize - # # 현재 지점에서 이동할 수 있는 지점들을 탐색 - cost = sys.maxsize - # 결국 모든 경로에 대해 조사하는 dfs느낌이지만 메모이제이션이나 dp를 사용해 메모리나 속도가 압도적. - # 시작점에서 나오는 모든 dfs재귀순환 연산이 끝나면.cost에는 모든경로와 비교한 최솟값이 저장됨. - for i in range(1, n): - # 여기서 i로 가는 길이 있고 (before를 i만큼 땡겨서 i번째 마을을 1의 자리에 놓고 2로 나눈 나머지가 0일때) 즉 i번째 마을을 들리지 않은 상태였을때. - if not (before>>i)%2 and path[now][i]: - # i부터 0까지 순회를 만든 최소 비용 i번 마을에 들러서 탐색을 시작한다. - tmp = find(i, before|(1<i[1]): - heappop(heap) -print(sum(heap)) \ No newline at end of file diff --git "a/2110\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.py" "b/2110\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.py" deleted file mode 100644 index e154279..0000000 --- "a/2110\352\263\265\354\234\240\352\270\260\354\204\244\354\271\230.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline - -def Binary(start,end): - result = 0 - while start <= end: - mid = (start+end)//2 - old = houses[0] - cnt=1 - - for i in range(1,len(houses)): - if houses[i] >= old+mid: - cnt+=1 - old = houses[i] - if cnt >=C: - start = mid+1 - result=mid - else: - end = mid-1 - return result - -N,C = map(int,input().split()) -houses = [] -for _ in range(N): - houses.append(int(input())) - -houses.sort() - -start = 1 -end = houses[-1]-houses[0] - - -print(Binary(start,end)) \ No newline at end of file diff --git "a/2116\354\243\274\354\202\254\354\234\204\354\214\200\352\270\260.py" "b/2116\354\243\274\354\202\254\354\234\204\354\214\200\352\270\260.py" deleted file mode 100644 index e318741..0000000 --- "a/2116\354\243\274\354\202\254\354\234\204\354\214\200\352\270\260.py" +++ /dev/null @@ -1,25 +0,0 @@ -N = int(input()) -dice = [] -for _ in range(N): - dice.append(list(map(int, input().split()))) -rotate = {0 : 5, 1 : 3, 2 : 4, 3 : 1, 4 : 2, 5 : 0} # 주사위의 아랫면에 따른 윗면 로테이션 등록(리스트 인덱스 기준) - -maxnum = 0 # 최대값을 저장해둘 상수 선언 -for i in range(6): # 첫 번째 주사위를 기준으로 1~6까지 모두 순회 - result = [] #각 주사위마다 옆면의 최대값 1개를 저장해둘 리스트 선언 - temp = [1, 2, 3, 4, 5, 6] # 주사위 각 면에 써져있는 1~6 - temp.remove(dice[0][i]) # 주사위 아랫면의 숫자 제거 - next = dice[0][rotate[i]] # 첫 번째 주사위의 윗면 값 계산 - temp.remove(next) # 첫 번째 주사위의 윗면 값 삭제 - result.append(max(temp)) # 첫 번째 주사위의 옆면들 중 가장 큰 값 삽입 - for j in range(1, N): # 두 번째 주사위부터 마지막 주사위까지 반복 - temp = [1, 2, 3, 4, 5, 6] - temp.remove(next) # 현재 주사위의 아랫면 숫자 제거 - next = dice[j][rotate[dice[j].index(next)]] # 현재 주사위의 윗면 계산 - temp.remove(next) # 현재 주사위의 윗면 삭제 - result.append(max(temp)) # 현재 주사위의 옆면들 중 가장 큰 값 삽입 - result = sum(result) # 각 주사위마다의 최대값을 모두 더한다. - if maxnum < result: # 이전의 최대값과 현재의 최대값을 비교하여 더 큰 값을 저장한다. - maxnum = result - -print(maxnum) \ No newline at end of file diff --git "a/21277\354\247\240\353\217\214\354\235\264\355\230\270\354\204\235.py" "b/21277\354\247\240\353\217\214\354\235\264\355\230\270\354\204\235.py" deleted file mode 100644 index 13367cc..0000000 --- "a/21277\354\247\240\353\217\214\354\235\264\355\230\270\354\204\235.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input=sys.stdin.readline - -N,M = map(int,input().split()) -puzzle = [list(map(int,list(input().rstrip()))) for _ in range(N)] -N2,M2 = map(int,input().split()) -puzzle2 = [list(map(int,list(input().rstrip()))) for _ in range(N2)] - -# 0도 -# 90도 -# 180도 -# 270도 -# 퍼즐 1,2를 동시에 탐색. 퍼즐1 0 퍼즐2 1이면 통과. diff --git "a/21278\355\230\270\354\204\235\354\235\264 \353\221\220 \353\247\210\353\246\254 \354\271\230\355\202\250.py" "b/21278\355\230\270\354\204\235\354\235\264 \353\221\220 \353\247\210\353\246\254 \354\271\230\355\202\250.py" deleted file mode 100644 index bc04fc2..0000000 --- "a/21278\355\230\270\354\204\235\354\235\264 \353\221\220 \353\247\210\353\246\254 \354\271\230\355\202\250.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M = map(int,input().split()) -graph = [[float('inf') for _ in range(N)] for _ in range(N)] - -for i in range(M): - a,b = map(int,input().split()) - graph[a-1][b-1] = 2 - graph[b-1][a-1] = 2 - -for i in range(N): - graph[i][i] = 0 - -for k in range(N): - for i in range(N): - for j in range(N): - if graph[i][j] >graph[i][k] + graph[k][j]: - graph[i][j] = graph[i][k] + graph[k][j] - -max_time = float('inf') - -for i in range(N-1): - for j in range(i,N): - chicken1 = i - chicken2 = j - sum_time = 0 - for building in range(N): - sum_time += min(graph[building][chicken1],graph[building][chicken2]) - if max_time > sum_time: - max_time = sum_time - max_chicken1 = chicken1 - max_chicken2 = chicken2 - -print(max_chicken1+1, max_chicken2+1, max_time) \ No newline at end of file diff --git "a/21314\353\257\274\352\262\270\354\210\230.py" "b/21314\353\257\274\352\262\270\354\210\230.py" deleted file mode 100644 index a6f3777..0000000 --- "a/21314\353\257\274\352\262\270\354\210\230.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - -minkyum = input().rstrip() - -n = len(minkyum) -max_v = '' -left = 0 -for i in range(n): - if minkyum[i]=='K': - max_v += '5' + '0'*(i - left) - left = i+1 -if minkyum[n-1] =='M': - max_v += '1'*(n - left) - -min_v = '' -left = 0 -for i in range(n): - if minkyum[i]=='K': - if i>0 and minkyum[i-1]=='M': - min_v += str(10**(i-left-1)) - min_v += '5' - left = i+1 -if minkyum[n-1] =='M': - min_v += '1' + '0'*(n-1 - left) -print(max_v) -print(min_v) \ No newline at end of file diff --git "a/21317 \354\247\225\352\262\200\353\213\244\353\246\254 \352\261\264\353\204\210\352\270\260.py" "b/21317 \354\247\225\352\262\200\353\213\244\353\246\254 \352\261\264\353\204\210\352\270\260.py" deleted file mode 100644 index f09cfc0..0000000 --- "a/21317 \354\247\225\352\262\200\353\213\244\353\246\254 \352\261\264\353\204\210\352\270\260.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -input = sys.stdin.readline - -def dfs(node, energy, key): - global min_energy - if energy >= min_energy: - return - if node == N: - min_energy = min(min_energy, energy) - return - if node + 1 <= N: - dfs(node + 1, energy + small_jump[node], key) - if node + 2 <= N: - dfs(node + 2, energy + big_jump[node], key) - if node + 3 <= N and key: - dfs(node + 3, energy + K, 0) - - -N = int(input()) -big_jump = [0] -small_jump = [0] -for _ in range(N - 1): - small, big = map(int, input().split()) - small_jump.append(small) - big_jump.append(big) -K = int(input()) -min_energy = float('inf') -dfs(1, 0, 1) -print(min_energy) \ No newline at end of file diff --git "a/21318 \355\224\274\354\225\204\353\205\270\354\262\264\354\241\260.py" "b/21318 \355\224\274\354\225\204\353\205\270\354\262\264\354\241\260.py" deleted file mode 100644 index c665592..0000000 --- "a/21318 \355\224\274\354\225\204\353\205\270\354\262\264\354\241\260.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = list(map(int, input().split())) -dp = [0]*N -for i in range(1,N): - if arr[i-1] <= arr[i]: - dp[i] = dp[i-1] + 1 - else: - dp[i] = dp[i-1] -Q = int(input()) -for _ in range(Q): - x, y = map(int, input().split()) - print((y-x) - (dp[y-1] - dp[x-1])) \ No newline at end of file diff --git "a/2133\355\203\200\354\235\274\354\261\204\354\232\260\352\270\260.py" "b/2133\355\203\200\354\235\274\354\261\204\354\232\260\352\270\260.py" index 60ed270..bcd09f2 100644 --- "a/2133\355\203\200\354\235\274\354\261\204\354\232\260\352\270\260.py" +++ "b/2133\355\203\200\354\235\274\354\261\204\354\232\260\352\270\260.py" @@ -1,13 +1,13 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -dp = [0]*31 - -dp[2] = 3 -for i in range(4,N+1,2): - dp[i] = dp[i-2]*3+2 - for j in range(4,i,2): - dp[i] += dp[i-j]*2 - -print(dp[N]) +import sys +input = sys.stdin.readline + +N = int(input()) +dp = [0]*31 + +dp[2] = 3 +for i in range(4,N+1,2): + dp[i] = dp[i-2]*3+2 + for j in range(4,i,2): + dp[i] += dp[i-j]*2 + +print(dp[N]) diff --git "a/2138 \354\240\204\352\265\254\354\231\200\354\212\244\354\234\204\354\271\230.py" "b/2138 \354\240\204\352\265\254\354\231\200\354\212\244\354\234\204\354\271\230.py" deleted file mode 100644 index 7995084..0000000 --- "a/2138 \354\240\204\352\265\254\354\231\200\354\212\244\354\234\204\354\271\230.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - -def change(now, cnt): - if cnt == 1: - now[0] ^= 1 - now[1] ^= 1 - for i in range(1, n-1): - if now[i-1] != target[i-1]: - cnt += 1 - now[i-1] ^= 1 - now[i] ^= 1 - now[i+1] ^= 1 - if now[n-2] != target[n-2]: - cnt += 1 - now[n-2] ^= 1 - now[n-1] ^= 1 - return cnt if now == target else float('inf') - - -n = int(input()) -now = list(map(int, input().rstrip())) -target = list(map(int,input().rstrip())) -res1 = change(now[:], 0) -res2 = change(now[:], 1) -print(min(res1, res2) if res1 != float('inf') or res2 != float('inf') else -1) - diff --git "a/2141\354\232\260\354\262\264\352\265\255.py" "b/2141\354\232\260\354\262\264\352\265\255.py" deleted file mode 100644 index 55f8a6b..0000000 --- "a/2141\354\232\260\354\262\264\352\265\255.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -def cal_dist(position): - dist = 0 - for town, population in arr: - dist += abs(position-town)*population - return dist - - -N = int(input()) -arr = [tuple(map(int, input().split())) for _ in range(N)] -left = -1000000000 -right = 1000000000 -answer = 0 -while left <= right: - mid = (left+right)//2 - if cal_dist(mid) < cal_dist(mid+1): - right = mid - 1 - answer = mid - else: - left = mid + 1 -arr.sort() -close_town_idx = bisect_left(arr,(answer,0)) -if cal_dist(arr[close_town_idx-1][0]) <= cal_dist(arr[close_town_idx][0]): - answer = close_town_idx-1 -else: - answer = close_town_idx -print(arr[answer][0]) \ No newline at end of file diff --git "a/2143 \353\221\220 \353\260\260\354\227\264\354\235\230 \355\225\251.py" "b/2143 \353\221\220 \353\260\260\354\227\264\354\235\230 \355\225\251.py" deleted file mode 100644 index 2ea0664..0000000 --- "a/2143 \353\221\220 \353\260\260\354\227\264\354\235\230 \355\225\251.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - - -T = int(input()) -n = int(input()) -arr_a = list(map(int, input().split())) -check = defaultdict(int) -for k in range(1, n+1): - left = 0 - s = 0 - for right in range(n): - s += arr_a[right] - if right - left == k-1: - check[T - s] += 1 - s -= arr_a[left] - left += 1 -ans = 0 -m = int(input()) -arr_b = list(map(int, input().split())) -for k in range(1, m+1): - left = 0 - s = 0 - for right in range(m): - s += arr_b[right] - if right - left == k-1: - if s in check: - ans += check[s] - s -= arr_b[left] - left += 1 -print(ans) \ No newline at end of file diff --git "a/2146_\354\242\214\355\221\234\354\260\250\354\235\264\354\232\251.py" "b/2146_\354\242\214\355\221\234\354\260\250\354\235\264\354\232\251.py" deleted file mode 100644 index c82101f..0000000 --- "a/2146_\354\242\214\355\221\234\354\260\250\354\235\264\354\232\251.py" +++ /dev/null @@ -1,47 +0,0 @@ -from collections import deque -import sys - -dx = [-1, 1, 0, 0] -dy = [0, 0, -1, 1] - - -def bfs(start): - q = deque() - result = list() - q.append((start[0], start[1])) - result.append((start[0], start[1])) - maps[start[0]][start[1]] = 0 - - while q: - x, y = q.popleft() - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - if 0 <= nx < n and 0 <= ny < n: - if maps[nx][ny] == 1: - maps[nx][ny] = 0 - q.append((nx, ny)) - result.append((nx, ny)) - return result - - -if __name__ == "__main__": - n = int(sys.stdin.readline()) - maps = [list(map(int, sys.stdin.readline().split())) for _ in range(n)] - island = [] - - for i in range(n): - for j in range(n): - if maps[i][j] != 0: - temp = bfs((i, j)) - island.append(temp) - - answer = 1e9 - for i in range(len(island)): - for j in range(i + 1, len(island)): - for x in range(len(island[i])): - for y in range(len(island[j])): - answer = min(answer, abs(island[i][x][0] - island[j][y][0]) + abs(island[i][x][1] - island[j][y][1])) - - print(answer - 1) - - \ No newline at end of file diff --git "a/2146\353\213\244\353\246\254\353\247\214\353\223\244\352\270\260.py" "b/2146\353\213\244\353\246\254\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 12f2b92..0000000 --- "a/2146\353\213\244\353\246\254\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,56 +0,0 @@ -import sys -from collections import deque, defaultdict -input = sys.stdin.readline - - -def find_continent(x, y): - q = deque() - q.append((x, y)) - matrix[x][y] = numbering - while q: - x, y = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N: - if matrix[nx][ny] == 1: - matrix[nx][ny] = numbering - q.append((nx, ny)) - elif not matrix[nx][ny]: - matrix[nx][ny] = numbering - water.append((nx, ny)) - dists[(nx, ny)] = 1 - - -def find_another_continent(): - min_val = float('inf') - while water: - for _ in range(len(water)): - x, y = water.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N: - if not matrix[nx][ny]: - matrix[nx][ny] = matrix[x][y] - water.append((nx, ny)) - dists[(nx, ny)] = dists[(x, y)] + 1 - else: - if matrix[x][y] != matrix[nx][ny]: - min_val = min(min_val, dists[(nx, ny)] + dists[(x, y)]) - if min_val != float('inf'): - return min_val - - -N = int(input()) -matrix = [list(map(int, input().split())) for _ in range(N)] - -numbering = 2 -delta = ((1, 0), (0, 1), (-1, 0), (0, -1)) - -water = deque() -dists = defaultdict(int) -for i in range(N): - for j in range(N): - if matrix[i][j] == 1: - find_continent(i, j) - numbering += 1 -print(find_another_continent()) diff --git "a/2146\353\213\244\353\246\254\353\247\214\353\223\244\352\270\260_re.py" "b/2146\353\213\244\353\246\254\353\247\214\353\223\244\352\270\260_re.py" deleted file mode 100644 index 1087f12..0000000 --- "a/2146\353\213\244\353\246\254\353\247\214\353\223\244\352\270\260_re.py" +++ /dev/null @@ -1,75 +0,0 @@ -import sys -sys.setrecursionlimit(10 ** 6) -from collections import deque - - -N = int(input()) -graph = [list(map(int, input().split())) for _ in range(N)] -check = [[False] * N for _ in range(N)] - -dx = [-1, 0, 0, 1] -dy = [0, 1, -1, 0] - -ans = sys.maxsize -count = 1 - - -def print_board(board): - for i in range(N): - for j in range(N): - print(board[i][j], end=" ") - print("") - - -# 각 섬에 번호를 붙여줘서 그룹핑하는 함수 -def dfs(y, x): - global count - check[y][x] = True - graph[y][x] = count - - for i in range(4): - ny, nx = y + dy[i], x + dx[i] - if ny < 0 or ny >= N or nx < 0 or nx >= N: - continue - if check[ny][nx] == False and graph[ny][nx]: - dfs(ny, nx) - - -def bfs(z): - global ans - dist = [[-1] * N for _ in range(N)] - q = deque() - - for i in range(N): # 섬들의 위치 모두 큐에 저장 - for j in range(N): - if graph[i][j] == z: - q.append([i, j]) - dist[i][j] = 0 - - while q: - y, x = q.popleft() - for i in range(4): - ny, nx = y + dy[i], x + dx[i] - if ny < 0 or ny >= N or nx < 0 or nx >= N: - continue - # 다른 섬에 도착한 경우 - if graph[ny][nx] > 0 and graph[ny][nx] != z: - ans = min(ans, dist[y][x]) - return - # 만약 바다이고, 간척 사업도 안된 곳이라면 새로 거리를 더해준다 - if graph[ny][nx] == 0 and dist[ny][nx] == -1: - dist[ny][nx] = dist[y][x] + 1 - q.append([ny, nx]) - - -for i in range(N): - for j in range(N): - if check[i][j] == False and graph[i][j] == 1: - dfs(i, j) - count += 1 - -# 각각의 섬에 대하여 bfs로 간척을 하여 다른 섬에 도달한다 -for i in range(1, count): - bfs(i) - -print(ans) \ No newline at end of file diff --git "a/21608\354\203\201\354\226\264\354\264\210\353\223\261\355\225\231\352\265\220.py" "b/21608\354\203\201\354\226\264\354\264\210\353\223\261\355\225\231\352\265\220.py" deleted file mode 100644 index d0221d1..0000000 --- "a/21608\354\203\201\354\226\264\354\264\210\353\223\261\355\225\231\352\265\220.py" +++ /dev/null @@ -1,70 +0,0 @@ -import sys -from collections import defaultdict -input = sys.stdin.readline - -def check(j,k): - near_list = [] - empty = 0 - for i in range(4): - if j+dx[i] >=0 and j+dx[i] < n and k+dy[i] >=0 and k+dy[i] < n: - if table[j+dx[i]][k+dy[i]]: - near_list.append(table[j+dx[i]][k+dy[i]]) - else: - empty += 1 - - return near_list,empty - -def find_seat(l): - l = sorted(l, key=lambda x:(x[0], x[1], x[2], x[3])) - cnt,emp,x,y = l[0] - return x,y - -n = int(input()) -dx = [-1,1,0,0] -dy = [0,0,-1,1] -student = defaultdict(list) - -for _ in range(n*n): - temp = list(map(int, input().split())) - student[temp[0]] = temp[1:] - -table = [[False] * n for _ in range(n)] - -for i in student.keys(): - l = [] - temp =[] - cnt = 0 - like_friend = 0 # i가 앉을수있는 위치에서 좋아하는 친구들의 수 - for j in range(n): - for k in range(n): - if table[j][k]: # 누가 앉아있으면 건너뛰고 - continue - #i학생이 j,k에 앉았을때 인접한 친구들과 인접한 빈칸의 수 - near_list, emp = check(j,k) - for like in student[i]: - if like in near_list: - cnt += 1 - temp.append(-cnt) - temp.append(-emp) - temp.append(j) - temp.append(k) - l.append(temp) - temp = [] - cnt = 0 - - #print(l) # l- 친구리스트와 빈칸, 해당 자리 - x,y = find_seat(l) - table[x][y] = i - -answer = 0 -score = {0:0, 1:1, 2:10, 3:100, 4:1000} -for i in range(n): - for j in range(n): - count = 0 - friend_list = check(i,j)[0] - for f in friend_list: - if f in student[table[i][j]]: - count += 1 - answer += score[count] - -print(answer) \ No newline at end of file diff --git "a/2164 \354\271\264\353\223\2342.py" "b/2164 \354\271\264\353\223\2342.py" deleted file mode 100644 index 9aef8e4..0000000 --- "a/2164 \354\271\264\353\223\2342.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -N = int(input()) -q = deque([i for i in range(1, N + 1)]) -while len(q) != 1: - q.popleft() - if len(q) == 1: - break - q.rotate(-1) - -print(q.pop()) \ No newline at end of file diff --git "a/2166\353\213\244\352\260\201\355\230\225\353\251\264\354\240\201_\354\231\270\354\240\201.py" "b/2166\353\213\244\352\260\201\355\230\225\353\251\264\354\240\201_\354\231\270\354\240\201.py" deleted file mode 100644 index 33b1cba..0000000 --- "a/2166\353\213\244\352\260\201\355\230\225\353\251\264\354\240\201_\354\231\270\354\240\201.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -import math -input = sys.stdin.readline - -n = int(input()) - -coord_list = [] -for _ in range(n): - x, y = map(int, input().split()) - coord_list.append((x, y)) - -coord_list.append(coord_list[0]) #(x1, y1) 좌표를 coord_list 마지막에 다시 추가 - -plus = 0 -minus = 0 -for i in range(len(coord_list) - 1): - plus += (coord_list[i][0] * coord_list[i+1][1]) - minus += (coord_list[i][1] * coord_list[i+1][0]) - # fabs는 소숫점 있는 수의 절댓값(abs는 정수) -area = math.fabs(0.5 * (plus - minus)) -print("%.1f" % area) \ No newline at end of file diff --git "a/2170\354\204\240\352\270\213\352\270\260.py" "b/2170\354\204\240\352\270\213\352\270\260.py" deleted file mode 100644 index 480ad68..0000000 --- "a/2170\354\204\240\352\270\213\352\270\260.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -lines = [list(map(int, input().split())) for _ in range(N)] -lines.sort() -answer = 0 -left = right = 0 - -for start, end in lines: - if not answer: - answer = abs(end - start) - left = start - right = end - continue - - # 여기가 스위핑문. 조건에서 벗어나는 라인은 조사 x - if left <= start and right >= end: - continue - - answer += abs(end - start) - if right > start: - answer -= abs(right - start) - left = start - right = end - -print(answer) \ No newline at end of file diff --git "a/2178\353\257\270\353\241\234\355\203\220\354\203\211.py" "b/2178\353\257\270\353\241\234\355\203\220\354\203\211.py" index 617a579..583509d 100644 --- "a/2178\353\257\270\353\241\234\355\203\220\354\203\211.py" +++ "b/2178\353\257\270\353\241\234\355\203\220\354\203\211.py" @@ -1,25 +1,25 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(50000) -from collections import deque - -N,M = map(int,input().split()) - -matrix = [list(map(lambda x :int(x),list(map(str,input().rstrip())))) for _ in range(N)] -queue = deque() -dx = [-1,1,0,0] -dy = [0,0,1,-1] - -def BFS(x,y): - queue.append([x,y]) - matrix[x][y] = 1 - while queue: - x,y = queue.popleft() - for k in range(4): - nx = x+dx[k] - ny = y+dy[k] - if 0<=nx 0: - if self.max_heap: - while (-self.max_heap[0][1] not in number_set) or number_algo[-self.max_heap[0][1]][0] != self.num or number_algo[-self.max_heap[0][1]][1] != -self.max_heap[0][0]: - heapq.heappop(self.max_heap) - if not self.max_heap: - break - if self.max_heap: - result = [-self.max_heap[0][0],-self.max_heap[0][1]] - else: - if self.min_heap: - while (self.min_heap[0][1] not in number_set) or number_algo[self.min_heap[0][1]][0] != self.num or number_algo[self.min_heap[0][1]][1] != self.min_heap[0][0]: - heapq.heappop(self.min_heap) - if not self.min_heap: - break - if self.min_heap: - result = self.min_heap[0] - return result - - -class Difficulty(): - def __init__(self,num): - self.num = num - self.min_heap = [] - self.max_heap = [] - - def insert(self,pb_num): - heapq.heappush(self.min_heap,pb_num) - heapq.heappush(self.max_heap,-pb_num) - def find_heap(self,x): - result = [] - if x > 0: - if self.min_heap: - while self.min_heap[0] not in number_set or (number_algo[self.min_heap[0]][1]) != self.num: - heapq.heappop(self.min_heap) - if not self.min_heap: - break - if self.min_heap: - result = self.min_heap[0] - - else: - if self.max_heap: - while -self.max_heap[0] not in number_set or (number_algo[-self.max_heap[0]][1]) != self.num: - heapq.heappop(self.max_heap) - if not self.max_heap: - break - if self.max_heap: - result = -self.max_heap[0] - return result - - -N = int(input()) -algo_set = set() -diff_set = set() -algo_dict = {} -diff_dict = {} -number_algo = {} -number_set = set() -for _ in range(N): - number,dif,algo = map(int,input().split()) - if algo not in algo_set: - algo_dict[algo] = Algorithm(algo) - algo_set.add(algo) - if dif not in diff_set: - diff_dict[dif] = Difficulty(dif) - diff_set.add(dif) - algo_dict[algo].insert(number,dif) - diff_dict[dif].insert(number) - number_algo[number] = [algo,dif] - number_set.add(number) - - -M = int(input()) - -for i in range(M): - command,*arg = input().split() - if command == 'recommend': - G,x = map(int,arg) - print(algo_dict[G].find_heap(x)[1]) - elif command == 'recommend2': - x = int(arg[0]) - diff_check = 0 if x == 1 else float('inf') - pb_num_check = -1 - for algo_num in algo_dict: - ch = algo_dict[algo_num].find_heap(x) - if not ch: continue - if x == 1: - if ch[0] >diff_check: - diff_check = ch[0] - pb_num_check = ch[1] - elif ch[0] == diff_check: - if pb_num_check < ch[1]: - pb_num_check = ch[1] - else: - if ch[0] < diff_check: - diff_check = ch[0] - pb_num_check = ch[1] - elif ch[0] == diff_check: - if pb_num_check > ch[1]: - pb_num_check = ch[1] - print(pb_num_check) - elif command == 'recommend3': - flag,L_num = map(int,arg) - result = -1 - if flag == -1: - L_num = L_num + flag - while 0<=L_num<=100: - if L_num in diff_set: - ch = diff_dict[L_num].find_heap(flag) - if not ch: - L_num = L_num + flag - continue - result = ch - print(ch) - break - L_num = L_num + flag - if result == -1: - print(-1) - - elif command == 'solved': - pb_num = int(arg[0]) - number_set.remove(pb_num) - del number_algo[pb_num] - else: - pb_num,diff_num,algo_num = map(int,arg) - if algo_num not in algo_set: - algo_dict[algo_num] = Algorithm(algo_num) - algo_set.add(algo_num) - if diff_num not in diff_set: - diff_dict[diff_num] = Difficulty(diff_num) - diff_set.add(diff_num) - algo_dict[algo_num].insert(pb_num,diff_num) - diff_dict[diff_num].insert(pb_num) - number_algo[pb_num] = [algo_num,diff_num] - number_set.add(pb_num) - - - -# 2 -import sys, heapq -input = sys.stdin.readline - -n = int(input()) - -algo_dict = {} -level_dict = {} -problem = {} - - -problem_min_heap = [] -problem_max_heap = [] - -for _ in range(n): - pb_num, level, al_num = map(int, input().split()) - # solved했는지 안 했는지 check - problem[pb_num] = [level, al_num] - # Recommend 2를 위한 heapq - heapq.heappush(problem_min_heap, (level, pb_num)) - heapq.heappush(problem_max_heap, (-level, -pb_num)) - # Algorithm Dict - if algo_dict.get(al_num) is not None: - # min_heap - heapq.heappush(algo_dict[al_num][0], (level, pb_num)) - # max_heap - heapq.heappush(algo_dict[al_num][1], (-level, -pb_num)) - else: - min_heap = [] - max_heap = [] - heapq.heappush(min_heap, (level, pb_num)) - heapq.heappush(max_heap, (-level, -pb_num)) - algo_dict[al_num] = [min_heap, max_heap] - # level Dict - if level_dict.get(level) is not None: - heapq.heappush(level_dict[level][0], pb_num) - heapq.heappush(level_dict[level][1], -pb_num) - else: - min_heap = [] - max_heap = [] - heapq.heappush(min_heap, pb_num) - heapq.heappush(max_heap, -pb_num) - level_dict[level] = [min_heap, max_heap] - -m = int(input()) - -for _ in range(m): - command, *args = list(input().rstrip().split()) - if command == "recommend": - al_num, x = list(map(int, args)) - if x == 1: - top = (algo_dict[al_num][1])[0] - while -top[0] != problem[-top[1]][0] or al_num != problem[-top[1]][1]: - heapq.heappop(algo_dict[al_num][1]) - top = (algo_dict[al_num][1])[0] - print(-top[1]) - else : - top = (algo_dict[al_num][0])[0] - while top[0] != problem[top[1]][0] or al_num != problem[top[1]][1]: - heapq.heappop(algo_dict[al_num][0]) - top = (algo_dict[al_num][0])[0] - print(top[1]) - - elif command == "recommend2": - x = int(args[0]) - if x == 1: - while -problem_max_heap[0][0] != problem[-problem_max_heap[0][1]][0]: - heapq.heappop(problem_max_heap) - print(-problem_max_heap[0][1]) - else: - while problem_min_heap[0][0] != problem[problem_min_heap[0][1]][0]: - heapq.heappop(problem_min_heap) - print(problem_min_heap[0][1]) - elif command == "recommend3": - x, level = list(map(int, args)) - success = False - if x == 1: - for lev in range(level, 101): - if level_dict.get(lev) is not None: - while len(level_dict[lev][0]) > 0 and lev != problem[(level_dict[lev][0])[0]][0]: - heapq.heappop(level_dict[lev][0]) - if len(level_dict[lev][0]) == 0: - continue - print((level_dict[lev][0])[0]) - success = True - break - if not success: - print(-1) - else : - for lev in range(level-1, 0, -1): - if level_dict.get(lev) is not None: - while len(level_dict[lev][1]) > 0 and lev != problem[-(level_dict[lev][1])[0]][0]: - heapq.heappop(level_dict[lev][1]) - if len(level_dict[lev][1]) == 0: - continue - print(-(level_dict[lev][1])[0]) - success = True - break - if not success: - print(-1) - elif command == "add": - pb_num, level, al_num = list(map(int, args)) - problem[pb_num] = [level, al_num] - heapq.heappush(problem_min_heap, (level, pb_num)) - heapq.heappush(problem_max_heap, (-level, -pb_num)) - if algo_dict.get(al_num) is not None: - # min_heap - heapq.heappush(algo_dict[al_num][0], (level, pb_num)) - # max_heap - heapq.heappush(algo_dict[al_num][1], (-level, -pb_num)) - else: - min_heap = [] - max_heap = [] - heapq.heappush(min_heap, (level, pb_num)) - heapq.heappush(max_heap, (-level, -pb_num)) - algo_dict[al_num] = [min_heap, max_heap] - # level Dict - if level_dict.get(level) is not None: - heapq.heappush(level_dict[level][0], pb_num) - heapq.heappush(level_dict[level][1], -pb_num) - else: - min_heap = [] - max_heap = [] - heapq.heappush(min_heap, pb_num) - heapq.heappush(max_heap, -pb_num) - level_dict[level] = [min_heap, max_heap] - elif command == "solved": - pb_num = int(args[0]) - problem[pb_num] = [0, 0] diff --git "a/21966(\354\244\221\353\236\265).py" "b/21966(\354\244\221\353\236\265).py" deleted file mode 100644 index 6cc0f68..0000000 --- "a/21966(\354\244\221\353\236\265).py" +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -s = input().rstrip() -if N <= 25: - print(s) - exit() -if '.' not in s[11:-12]: - print(s[:11]+'...'+s[-11:]) - exit() -print(s[:9] + '......' + s[-10:]) \ No newline at end of file diff --git "a/2204\353\217\204\353\271\204\354\235\230 \353\202\234\353\217\205\354\246\235 \355\205\214\354\212\244\355\212\270.py" "b/2204\353\217\204\353\271\204\354\235\230 \353\202\234\353\217\205\354\246\235 \355\205\214\354\212\244\355\212\270.py" deleted file mode 100644 index bf2bd58..0000000 --- "a/2204\353\217\204\353\271\204\354\235\230 \353\202\234\353\217\205\354\246\235 \355\205\214\354\212\244\355\212\270.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -while 1: - n = int(input()) - if not n: - break - strings = [] - lower_dict = defaultdict(str) - for _ in range(n): - s = input().rstrip() - l = s.lower() - lower_dict[l] = s - strings.append(l) - strings.sort() - print(lower_dict[strings[0]]) - - \ No newline at end of file diff --git "a/2206\353\262\275\353\277\214\354\210\230\352\263\240 \354\235\264\353\217\231\355\225\230\352\270\260.py" "b/2206\353\262\275\353\277\214\354\210\230\352\263\240 \354\235\264\353\217\231\355\225\230\352\270\260.py" deleted file mode 100644 index e62632c..0000000 --- "a/2206\353\262\275\353\277\214\354\210\230\352\263\240 \354\235\264\353\217\231\355\225\230\352\270\260.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -from collections import deque -input = sys.stdin.readline -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] -# 3차원 배열로 3차원 배열에 뚫을 수 잇으면 1 없으면 0으로 부여. 뚫은 좌표 로 쭉쭉 BFS펼치다가 가장먼저 도착지에 도착한게 최솟값. -# 벽을 뚫을때마다 bfs돌리면 절대 못감. -def bfs(): - q = deque() - q.append([0, 0, 1]) - visit = [[[0] * 2 for _ in range(m)] for i in range(n)] - visit[0][0][1] = 1 - while q: - a, b, w = q.popleft() - if a == n - 1 and b == m - 1: - return visit[a][b][w] - for i in range(4): - x = a + dx[i] - y = b + dy[i] - if 0 <= x < n and 0 <= y < m: - # 벽이있고 뚫을 능력이 있을때. - if s[x][y] == 1 and w == 1: - visit[x][y][0] = visit[a][b][1] + 1 - q.append([x, y, 0]) - # 벽이 없고 가보지 않은 곳. - elif s[x][y] == 0 and visit[x][y][w] == 0: - visit[x][y][w] = visit[a][b][w] + 1 - q.append([x, y, w]) - return -1 -n, m = map(int, input().split()) -s = [] -for i in range(n): - s.append(list(map(int, list(input().strip())))) -print(bfs()) \ No newline at end of file diff --git "a/2211\353\204\244\355\212\270\354\233\214\355\201\254\353\263\265\352\265\254_\353\213\244\354\235\265.py" "b/2211\353\204\244\355\212\270\354\233\214\355\201\254\353\263\265\352\265\254_\353\213\244\354\235\265.py" deleted file mode 100644 index b0479ca..0000000 --- "a/2211\353\204\244\355\212\270\354\233\214\355\201\254\353\263\265\352\265\254_\353\213\244\354\235\265.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -def dijkstra(start): - heap = [] - dp_dists[start] = 0 - heappush(heap,[dp_dists[start],start]) - while heap: - cur_dists,cur_node= heappop(heap) - for next_dists,next_node in network[cur_node]: - if dp_dists[next_node] > cur_dists + next_dists: - dp_dists[next_node] = cur_dists + next_dists - path[next_node] = cur_node - heap.append([dp_dists[next_node],next_node]) - -N,M = map(int,input().split()) -network = {i:[] for i in range(1,N+1)} -dp_dists = {i:float('inf') for i in range(1,N+1)} -path = {i:0 for i in range(1,N+1)} -for _ in range(M): - A,B,C = map(int,input().split()) - network[A].append([C,B]) - network[B].append([C,A]) - -dijkstra(1) - -print(N-1) -for i in range(2,N+1): - print(i,path[i]) \ No newline at end of file diff --git "a/2211\353\204\244\355\212\270\354\233\214\355\201\254\353\263\265\352\265\254_\355\201\254\353\243\250\354\212\244\354\271\274 \355\213\200\353\246\274.py" "b/2211\353\204\244\355\212\270\354\233\214\355\201\254\353\263\265\352\265\254_\355\201\254\353\243\250\354\212\244\354\271\274 \355\213\200\353\246\274.py" deleted file mode 100644 index 4c017ab..0000000 --- "a/2211\353\204\244\355\212\270\354\233\214\355\201\254\353\263\265\352\265\254_\355\201\254\353\243\250\354\212\244\354\271\274 \355\213\200\353\246\274.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - -def find(x): - if parents[x]==x: - return x - parents[x] = find(parents[x]) - return parents[x] - -def union(a,b): - a = find(a) - b = find(b) - - if a>b: - parents[a] = b - else: - parents[b] = a - -# N개의 컴퓨터 네트워크. -# 회선은 성능차이가 있음. -N,M = map(int,input().split()) -sercuits = [] -parents = [i for i in range(N+1)] -for _ in range(M): - A,B,C = map(int,input().split()) - sercuits.append([C,A,B]) - -sercuits.sort(reverse=True) - -cnt=0 -restore_line=[] -while sercuits: - time,a,b = sercuits.pop() - - if find(a) != find(b): - union(a,b) - cnt+=1 - restore_line.append([a,b]) - -print(cnt) -for line in restore_line: - print(*line) \ No newline at end of file diff --git "a/2213\355\212\270\353\246\254\354\227\220\354\204\234\354\235\230 \353\217\205\353\246\275\354\247\221\355\225\251.py" "b/2213\355\212\270\353\246\254\354\227\220\354\204\234\354\235\230 \353\217\205\353\246\275\354\247\221\355\225\251.py" deleted file mode 100644 index b08221c..0000000 --- "a/2213\355\212\270\353\246\254\354\227\220\354\204\234\354\235\230 \353\217\205\353\246\275\354\247\221\355\225\251.py" +++ /dev/null @@ -1,52 +0,0 @@ -import sys -input = sys.stdin.readline - -# tree dp를 그리는 dfs -def dfs(cur_node): - visited[cur_node] = True - dp[cur_node][0] = node_v[cur_node] - dp[cur_node][1] = 0 - for next_node in tree[cur_node]: - if not visited[next_node]: - dfs(next_node) - dp[cur_node][0] += dp[next_node][1] - dp[cur_node][1] += max(dp[next_node][0],dp[next_node][1]) - -# pre_node의 존재 유무에 따라 분기를 타는 trace -def trace(cur_node,pre_node): - trace_visited[cur_node] = True - - if not pre_node: - for next_node in tree[cur_node]: - if not trace_visited[next_node]: - trace(next_node,1) - else: - if dp[cur_node][0] > dp[cur_node][1]: - trace_res.append(cur_node) - for next_node in tree[cur_node]: - if not trace_visited[next_node]: - trace(next_node,0) - else: - for next_node in tree[cur_node]: - if not trace_visited[next_node]: - trace(next_node,1) - - -n = int(input()) -node_v = [0] + list(map(int,input().split())) -tree = {i: [] for i in range(1,n+1)} -dp = {i: [0,0] for i in range(1,n+1)} - -for _ in range(n-1): - a, b = map(int, input().split()) - tree[a] += [b] - tree[b] += [a] - -visited = {i: False for i in range(1,n+1)} -dfs(1) -print(max(dp[1][0],dp[1][1])) -trace_res = [] -trace_visited = {i: False for i in range(1,n+1)} -trace(1,1) -trace_res.sort() -print(*trace_res) \ No newline at end of file diff --git "a/2225\355\225\251\353\266\204\355\225\264.py" "b/2225\355\225\251\353\266\204\355\225\264.py" index f0fcb80..fac3cb4 100644 --- "a/2225\355\225\251\353\266\204\355\225\264.py" +++ "b/2225\355\225\251\353\266\204\355\225\264.py" @@ -1,15 +1,15 @@ -n, k = map(int, input().split()) -dp = [[0] * 201 for i in range(201)] -# 1열은 모두 1. 1행도 마찬가지. -for i in range(201): - dp[i][1] = 1 -#j는 n(행) i는 k(열) -# n은j, k는i 일때 답은 k-1열일때 n=0~n=j일때까지 모든 dp의 합. -for i in range(1, 201): - for j in range(201): - for l in range(j + 1): - dp[j][i] += dp[l][i - 1] -print(dp[n][k] % 1000000000) - - -# dp에 표를 그린다. 가로 1열, 세로 1열 (n,k) = (0,1)시작부터 끝까지 쭉 그림. +n, k = map(int, input().split()) +dp = [[0] * 201 for i in range(201)] +# 1열은 모두 1. 1행도 마찬가지. +for i in range(201): + dp[i][1] = 1 +#j는 n(행) i는 k(열) +# n은j, k는i 일때 답은 k-1열일때 n=0~n=j일때까지 모든 dp의 합. +for i in range(1, 201): + for j in range(201): + for l in range(j + 1): + dp[j][i] += dp[l][i - 1] +print(dp[n][k] % 1000000000) + + +# dp에 표를 그린다. 가로 1열, 세로 1열 (n,k) = (0,1)시작부터 끝까지 쭉 그림. diff --git "a/2225\355\225\251\353\266\204\355\225\264re.py" "b/2225\355\225\251\353\266\204\355\225\264re.py" index e16fb9b..a5b36d6 100644 --- "a/2225\355\225\251\353\266\204\355\225\264re.py" +++ "b/2225\355\225\251\353\266\204\355\225\264re.py" @@ -1,12 +1,12 @@ -import sys -input = sys.stdin.readline - -N,K = map(int,input().split()) -dp = [[1]*201 for _ in range(201)] - - -for i in range(1,N+1): - for j in range(2,K+1): - dp[i][j] = (dp[i-1][j] + dp[i][j-1])%1000000000 - -print(dp[N][K]) +import sys +input = sys.stdin.readline + +N,K = map(int,input().split()) +dp = [[1]*201 for _ in range(201)] + + +for i in range(1,N+1): + for j in range(2,K+1): + dp[i][j] = (dp[i-1][j] + dp[i][j-1])%1000000000 + +print(dp[N][K]) diff --git "a/2239\354\212\244\353\217\204\354\277\240_\352\263\265\353\266\200.py" "b/2239\354\212\244\353\217\204\354\277\240_\352\263\265\353\266\200.py" deleted file mode 100644 index 2bbfaa4..0000000 --- "a/2239\354\212\244\353\217\204\354\277\240_\352\263\265\353\266\200.py" +++ /dev/null @@ -1,53 +0,0 @@ -import sys -input = sys.stdin.readline - -# 1. 스도쿠에 빈 공간(0)이 있는지 확인한다. -# 2. 빈 공간이 없으면 스도쿠가 완성됐으므로 종료한다. -# 3. 빈 공간이 있으면 빈 공간(col, row)이 어딘지 말한다. -# 4. 빈 공간에 어떤 값(1~9)이 들어갈 수 있는지 탐색한다. -# - 찾았다면 스도쿠에 채워넣는다. -# - 채워넣을 수 있는 게 없다면 백 트래킹 한다. - -def cal(x, y): - return (x//3)*3 + (y//3) - -def solve_sudoku(n): - # 81칸 전부 캄색하고 배열 출력. - if n == 81: - for i in sudoku: - print(''.join(map(str, i))) - return True - - x,y = divmod(n,9) - # 있다면 다음칸으로 넘어가고 - if sudoku[x][y]: - return solve_sudoku(n+1) - else: - # 1~10숫자중에 뭘 넣을까 찾아본다. 3가지 항목 체크하고 숫자기입. 안되면 백트래킹 - for i in range(1, 10): - if not check_col[x][i] and not check_row[y][i] and not check_square[cal(x,y)][i]: - check_col[x][i] = check_row[y][i] = check_square[cal(x,y)][i] = True - sudoku[x][y] = i - # True값 반환오면 바로 True값 반환해서 빠르게 돌아가게 한다. - if solve_sudoku(n+1): - return True - # 아니면 다시 숫자 뺀다. - check_col[x][i] = check_row[y][i] = check_square[cal(x,y)][i] = False - sudoku[x][y] = 0 - # 1~10 다 안되면 일단 뺀다. - return False - - -sudoku = [list(map(int, input().rstrip())) for _ in range(9)] -# 각 9개의 행, 열, 사각형에 1~9까지의 숫자가 있냐 없냐 check -check_col = [[False]*10 for _ in range(9)] #행 -check_row = [[False]*10 for _ in range(9)] #열 -check_square = [[False]*10 for _ in range(9)] #사각형 -for i in range(9): - for j in range(9): - if sudoku[i][j]: - check_col[i][sudoku[i][j]] = True - check_row[j][sudoku[i][j]] = True - check_square[cal(i, j)][sudoku[i][j]] = True - -solve_sudoku(0) \ No newline at end of file diff --git "a/2243\354\202\254\355\203\225\354\203\201\354\236\220.py" "b/2243\354\202\254\355\203\225\354\203\201\354\236\220.py" deleted file mode 100644 index 054c8c9..0000000 --- "a/2243\354\202\254\355\203\225\354\203\201\354\236\220.py" +++ /dev/null @@ -1,45 +0,0 @@ -class FenwickTree: - def __init__(self): - self.size = 1000000 - self.tree = [0 for _ in range( self.size + 1)] - - def update(self, _idx, _diff): - while _idx <= self.size: - self.tree[ _idx] += _diff - _idx += (_idx & -_idx) - - def get_sum(self, _idx): - sum = 0 - while _idx > 0: - sum += self.tree[_idx] - _idx -= (_idx & -_idx) - return sum - - def get_candy(self, _pick): - left, right = 1, self.size - while left < right: - mid = int( (left + right) / 2) - cumCandies = self.get_sum( mid) - if cumCandies >= _pick: right = mid - else: left = mid + 1 - - return left - -def data_in(): - N = int(input()) - return N, [ input().split() for _ in range( N)] - -def solution( N, cmds): - fenwickTree = FenwickTree() - for cmd in cmds: - if cmd[0] == '2': # insert - fenwickTree.update( int( cmd[1]), int( cmd[2])) - else: # pick - pick = int( cmd[1]) - candy = fenwickTree.get_candy( pick) - print( candy) - fenwickTree.update( candy, -1) - -if __name__ == '__main__': - N, cmds = data_in() - solution( N, cmds) diff --git "a/2243\354\202\254\355\203\225\354\203\201\354\236\220_\355\217\254\352\270\260 \354\204\270\352\267\270\353\250\274\355\212\270\355\212\270\353\246\254\353\254\270\354\240\234.py" "b/2243\354\202\254\355\203\225\354\203\201\354\236\220_\355\217\254\352\270\260 \354\204\270\352\267\270\353\250\274\355\212\270\355\212\270\353\246\254\353\254\270\354\240\234.py" deleted file mode 100644 index 4226a72..0000000 --- "a/2243\354\202\254\355\203\225\354\203\201\354\236\220_\355\217\254\352\270\260 \354\204\270\352\267\270\353\250\274\355\212\270\355\212\270\353\246\254\353\254\270\354\240\234.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -n = int(input()) -basket = [] -for i in range(n): - command = input().split() - A = command[0] - if A=='1': - tasty = command[1] - basket.append(tasty) - else: - tasty = command[1] - push_pull = command[2] - if push_pull >0: - for i in range(push_pull): - basket.append(tasty) - else: - for i in range(-push_pull): - basket.pop() \ No newline at end of file diff --git "a/2250\355\212\270\353\246\254\354\235\230\353\206\222\354\235\264\354\231\200\353\204\210\353\271\204.py" "b/2250\355\212\270\353\246\254\354\235\230\353\206\222\354\235\264\354\231\200\353\204\210\353\271\204.py" deleted file mode 100644 index b65df43..0000000 --- "a/2250\355\212\270\353\246\254\354\235\230\353\206\222\354\235\264\354\231\200\353\204\210\353\271\204.py" +++ /dev/null @@ -1,48 +0,0 @@ -import sys -input = sys.stdin.readline - - -# 중위순회는 왼쪽 탐색, 본인 출력, 오른쪽 탐색(왼쪽에 더이상 갈 일이 없는 노드부터 same_level트리에 들어가게 됨(num은 가로 index)) -def inorder(root, level): - global num - if tree[root][0] != -1: - inorder(tree[root][0], level + 1) - same_level[level].append(num) - num += 1 - if tree[root][1] != -1: - inorder(tree[root][1], level + 1) - - - -n = int(input()) -tree = [[0] * 2 for _ in range(n + 1)] -node = [0 for _ in range(n + 1)] -same_level = [[] for _ in range(n + 1)] -num = 1 - -# 삽입하고 존재하는 노드는 1표시. -for i in range(n): - root, left, right = map(int, input().split()) - tree[root][0] = left - tree[root][1] = right - node[root] += 1 - if left != -1: - node[left] += 1 - if right != -1: - node[right] += 1 -for i in range(1, n + 1): - if node[i] == 1: - root = i - -# 입력한 tree에 대해 중위순회 실시(루트, 레벨 1부터.) -inorder(root, 1) - -# result에 1열부터 끝 level까지 모든 가로값에 대해 비교 후 최종결정.(가로길이와 레벨 저장.) -result = max(same_level[1]) - min(same_level[1]) + 1 -level = 1 -for i in range(2, n + 1): - if same_level[i]: - if result < max(same_level[i]) - min(same_level[i]) + 1: - result = max(same_level[i]) - min(same_level[i]) + 1 - level = i -print(level, result) \ No newline at end of file diff --git "a/2252\354\244\204\354\204\270\354\232\260\352\270\260.py" "b/2252\354\244\204\354\204\270\354\232\260\352\270\260.py" deleted file mode 100644 index b6c1cd3..0000000 --- "a/2252\354\244\204\354\204\270\354\232\260\352\270\260.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def topological_sort(): - queue=deque() - for i in range(1,N+1): - if not level[i]: - queue.append(i) - answer.append(i) - while queue: - cur_node=queue.popleft() - for next_node in graph[cur_node]: - level[next_node] -=1 - if not level[next_node]: - queue.append(next_node) - answer.append(next_node) - -N,M = map(int,input().split()) -graph = {i:[] for i in range(1,N+1)} -level = {i:0 for i in range(1,N+1)} -answer = [] -for _ in range(M): - a,b=map(int,input().split()) - graph[a] += [b] - level[b] += 1 - -topological_sort() - -print(*answer) \ No newline at end of file diff --git "a/2253 \354\240\220\355\224\204.py" "b/2253 \354\240\220\355\224\204.py" deleted file mode 100644 index 07cb96e..0000000 --- "a/2253 \354\240\220\355\224\204.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -dp = [[float('inf')] * (int((2 * N)** 0.5) + 2) for _ in range(N + 1)] -dp[1][0] = 0 -stones = set([int(input()) for _ in range(M)]) -for i in range(2, N + 1): - if i in stones: continue - for j in range(1, int((2 * i) ** 0.5) + 1): - dp[i][j] = min(dp[i - j][j - 1], dp[i - j][j], dp[i - j][j + 1]) + 1 - -answer = min(dp[N]) -print(answer if answer != float('inf') else -1) \ No newline at end of file diff --git "a/2261\352\260\200\354\236\245 \352\260\200\352\271\214\354\232\264 \353\221\220 \354\240\220.py" "b/2261\352\260\200\354\236\245 \352\260\200\352\271\214\354\232\264 \353\221\220 \354\240\220.py" deleted file mode 100644 index 83f1613..0000000 --- "a/2261\352\260\200\354\236\245 \352\260\200\352\271\214\354\232\264 \353\221\220 \354\240\220.py" +++ /dev/null @@ -1,53 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**9) - -def dist(a, b): - return ((b[0] - a[0])**2 + (b[1] - a[1])**2) - -def divide_and_conquer(start, end): - length = end - start - # 거리 구하기 쉬운 2~3개 남을 때까지 분할해서 정복한다. - if length == 2: - return dist(location[start], location[start+1]) - elif length == 3: - return min(dist(location[start], location[start+1]), dist(location[start], location[start+2]), dist(location[start+1], location[start+2])) - else: # length > 3 - # 중앙을 기준으로 분할 - mid = (start + end)//2 - # 분할 결과중 최솟값만 가져옴. - d = min(divide_and_conquer(start, mid), divide_and_conquer(mid, end)) - - # x의 중앙값.(중앙값 좌표의 x) - midX = location[mid][0] - cmp_list = [] - # 그 좌표로부터 x 거리 제곱이 d 보다 작으면 후보군에 삽입. - for i in range(start, end): - if (location[i][0] - midX)**2 <= d: - cmp_list.append(location[i]) - - clist_len = len(cmp_list) - if clist_len >= 2: - # y 에 대해 정렬 - cmp_list.sort(key= lambda x:x[1]) - # 모든 정점 조합에 대해 거리 검사. - for i in range(clist_len - 1): - for j in range(i+1, clist_len): - # y좌표 차이의 제곱이 d보다 작고 x좌표가 중앙값에 걸쳐있는 애들만 d에 최솟값 거리 비교를 해줌. 중앙값에 안걸쳐있으면 다 거름. - if (cmp_list[i][1] - cmp_list[j][1])**2 > d: - break - elif cmp_list[i][0] < midX and cmp_list[j][0] < midX: - continue - elif cmp_list[i][0] >= midX and cmp_list[j][0] >= midX: - continue - d = min(d, dist(cmp_list[i], cmp_list[j])) - return d - -n = int(input()) -location = list(set(tuple(map(int, input().split())) for _ in range(n))) -# 1. x에 대해 정렬. -location.sort(key = lambda x: x[0]) -if n != len(location): - print(0) -else: - print(divide_and_conquer(0, n)) \ No newline at end of file diff --git "a/2263\355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214.py" "b/2263\355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214.py" deleted file mode 100644 index 6d7434d..0000000 --- "a/2263\355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - - -n = int(input()) -in_order = list(map(int, input().split())) -post_order = list(map(int, input().split())) - -# 루트는 post_order[-1] -# in order에서 루트 왼쪽에 있는 애들이 왼쪽 서브트리. 오른쪽이 오른쪽 서브트리. 즉 분할 가능. diff --git "a/2263\355\212\270\353\246\254\354\235\230\354\210\234\355\232\214.py" "b/2263\355\212\270\353\246\254\354\235\230\354\210\234\355\232\214.py" index 4d70637..1103f8b 100644 --- "a/2263\355\212\270\353\246\254\354\235\230\354\210\234\355\232\214.py" +++ "b/2263\355\212\270\353\246\254\354\235\230\354\210\234\355\232\214.py" @@ -1,28 +1,28 @@ -import sys -sys.setrecursionlimit(10**6) - -n = int(input()) -in_order = list(map(int, input().split())) -post_order = list(map(int, input().split())) - -pos = [0]*(n+1) -for i in range(n): - pos[in_order[i]] = i # 중위 순회로 부모노드의 위치에서 왼쪽에 몇개있나 알수있음 - - -def divide(in_start, in_end, p_start, p_end): # 중위 시작, 끝, 후위시작, 끝 / 트리 나누면서 계속 나누어감.(트리 나눌때마다 인덱스 조정을 위한 것.) - if(in_start > in_end) or (p_start > p_end): - return - parents = post_order[p_end] # 후위순회에서 부모노드 찾기 (후위순회의 마지막 노드가 루트) / 후위순회의 뒤에있을수록 level이 낮은 node(부모노드) - print(parents, end=" ") - - left = pos[parents] - in_start # 왼쪽인자 갯수 (루트노드기준 왼쪽) - right = in_end - pos[parents] # 오른쪽인자 갯수 (루트노드기준 오른쪽) - - divide(in_start, in_start+left-1, p_start, p_start+left-1) # 왼쪽 트리(왼쪽 부분트리로 들어가 거기서 부모노드 찾고 왼쪽 오른쪽 나눈다.) 중위 시작 똑같고 끝은 왼쪽갯수-1인덱스고 후위시작 똑같고 후위끝 왼쪽 갯수-1 - divide(in_end-right+1, in_end, p_end-right, p_end-1) # 오른쪽 트리 (오른쪽 부모노드 찾고 왼쪽 오른쪽 나눈다.) 중위 시작 중위끝에서 오른쪽갯수만큼 뺀것. 중위 끝 똑같고 후위 시작은 후위 끝에서 오른쪽 갯수만큼 빼고 후위끝은 그냥 -1인덱스. - -divide(0, n-1, 0, n-1) - - - +import sys +sys.setrecursionlimit(10**6) + +n = int(input()) +in_order = list(map(int, input().split())) +post_order = list(map(int, input().split())) + +pos = [0]*(n+1) +for i in range(n): + pos[in_order[i]] = i # 중위 순회로 부모노드의 위치에서 왼쪽에 몇개있나 알수있음 + + +def divide(in_start, in_end, p_start, p_end): # 중위 시작, 끝, 후위시작, 끝 / 트리 나누면서 계속 나누어감.(트리 나눌때마다 인덱스 조정을 위한 것.) + if(in_start > in_end) or (p_start > p_end): + return + parents = post_order[p_end] # 후위순회에서 부모노드 찾기 (후위순회의 마지막 노드가 루트) / 후위순회의 뒤에있을수록 level이 낮은 node(부모노드) + print(parents, end=" ") + + left = pos[parents] - in_start # 왼쪽인자 갯수 (루트노드기준 왼쪽) + right = in_end - pos[parents] # 오른쪽인자 갯수 (루트노드기준 오른쪽) + + divide(in_start, in_start+left-1, p_start, p_start+left-1) # 왼쪽 트리(왼쪽 부분트리로 들어가 거기서 부모노드 찾고 왼쪽 오른쪽 나눈다.) 중위 시작 똑같고 끝은 왼쪽갯수-1인덱스고 후위시작 똑같고 후위끝 왼쪽 갯수-1 + divide(in_end-right+1, in_end, p_end-right, p_end-1) # 오른쪽 트리 (오른쪽 부모노드 찾고 왼쪽 오른쪽 나눈다.) 중위 시작 중위끝에서 오른쪽갯수만큼 뺀것. 중위 끝 똑같고 후위 시작은 후위 끝에서 오른쪽 갯수만큼 빼고 후위끝은 그냥 -1인덱스. + +divide(0, n-1, 0, n-1) + + + diff --git "a/2285 \354\232\260\354\262\264\352\265\255.py" "b/2285 \354\232\260\354\262\264\352\265\255.py" deleted file mode 100644 index 3329e94..0000000 --- "a/2285 \354\232\260\354\262\264\352\265\255.py" +++ /dev/null @@ -1,54 +0,0 @@ -from sys import stdin -import collections -readline = stdin.readline - -N = int(readline()) -countries = collections.defaultdict(int) - -def solve(): - _sum = 0 - for _ in range(N): - country, people = map(int, readline().split()) - countries[country] = people - _sum += people - - _sum /= 2 - temp, res = 0, 1 - for key in sorted(countries): - temp += countries[key] - res = key - if temp >= _sum: - break - - print(res) -solve() - - -# 2 -from sys import stdin - - -N = int(input()) -villages = [] -tot = 0 - -for _ in range(N): - x, a = map(int, stdin.readline().split()) - villages.append((x, a)) - tot += a - -villages.sort(key=lambda x: x[0]) - -if tot % 2: - tot += 1 - -tot //= 2 -tmp = 0 - - -for v in villages: - tmp += v[1] - - if tmp >= tot: - print(v[0]) - break diff --git "a/22858\354\233\220\354\203\201\353\263\265\352\265\254small.py" "b/22858\354\233\220\354\203\201\353\263\265\352\265\254small.py" deleted file mode 100644 index 2dc86b2..0000000 --- "a/22858\354\233\220\354\203\201\353\263\265\352\265\254small.py" +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) -after_shuffle = list(map(int, input().split())) -D = list(map(int, input().split())) - -for _ in range(K): - tmp = [0]*N - for i in range(N): - tmp[D[i]-1] = after_shuffle[i] - after_shuffle = tmp -print(*after_shuffle) \ No newline at end of file diff --git "a/22867\354\242\205\354\240\220.py" "b/22867\354\242\205\354\240\220.py" deleted file mode 100644 index 394e79b..0000000 --- "a/22867\354\242\205\354\240\220.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappush, heappop - -N = int(input()) -buses = [] -for _ in range(N): - arrive, leave = input().split() - a = int(''.join((''.join(arrive.split(':'))).split('.'))) - b = int(''.join((''.join(leave.split(':'))).split('.'))) - buses.append([a,b]) -buses.sort() - -heap = [] -heappush(heap,buses[0][1]) -for i in range(1,N): - if buses[i][0] >= heap[0]: - heappop(heap) - heappush(heap, buses[i][1]) - else: - heappush(heap, buses[i][1]) -print(len(heap)) \ No newline at end of file diff --git a/2294.py b/2294.py deleted file mode 100644 index 3c55f80..0000000 --- a/2294.py +++ /dev/null @@ -1,27 +0,0 @@ - - -N , K= map(int,input().split()) -name = list(map(int,input().split())) -concent = [] -cnt = 0 - - -for i in range(K): - if name[i] in concent: - continue - else: - if len(concent)= d_death_cnt: - print('Victory!') -else: - print('gg') \ No newline at end of file diff --git "a/2304\354\260\275\352\263\240\353\213\244\352\260\201\355\230\225.py" "b/2304\354\260\275\352\263\240\353\213\244\352\260\201\355\230\225.py" deleted file mode 100644 index c54a8e9..0000000 --- "a/2304\354\260\275\352\263\240\353\213\244\352\260\201\355\230\225.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -pillars = [list(map(int, input().split())) for _ in range(N)] -pillars.sort() -height = 0 -left = 0 -answer = 0 -for pillar in pillars: - if height <= pillar[1]: - answer += (pillar[0] - left)*height - height = pillar[1] - left = pillar[0] -height = 0 -left = 0 -pillars.reverse() -for pillar in pillars: - if height <= pillar[1]: - answer += (left - pillar[0])*height - height = pillar[1] - left = pillar[0] -left = 0 -h_t = 0 -for pillar in pillars: - if height == pillar[1]: - answer -= (left - pillar[0])*h_t - left = pillar[0] - h_t = pillar[1] -answer += height -print(answer) \ No newline at end of file diff --git "a/2307\353\217\204\353\241\234\352\262\200\353\254\270.py" "b/2307\353\217\204\353\241\234\352\262\200\353\254\270.py" deleted file mode 100644 index 4fc8f70..0000000 --- "a/2307\353\217\204\353\241\234\352\262\200\353\254\270.py" +++ /dev/null @@ -1,49 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -# 가중치 있는 그래프. -# 최소 시간. 양수. -# 경찰 도로 검문(간선 가중치 무한대).(탈출 지연) -# 1진입 N탈출. -> 다익스트라. -# 경찰이 도로를 막았을때 지연시킬 수 있는 최대시간을 정수로 출력. -# 지연효과없으면 0, 못빠져나가게 할수있으면(최소시간이inf면) -1출력. -def dijkstra(a,b): - dp_dists = {i:float('inf') for i in range(1,p_cnt+1)} - heap = [] - dp_dists[1] = 0 - heappush(heap,[dp_dists[1],1]) - while heap: - cur_dist,cur_node = heappop(heap) - for next_node, next_dist in roads[cur_node]: - if (cur_node ==a and next_node==b) or (cur_node==b and next_dist==a): - continue - if dp_dists[next_node] > cur_dist + next_dist: - dp_dists[next_node] = cur_dist + next_dist - heappush(heap,[dp_dists[next_node],next_node]) - if a==0: - optimal_path[next_node] = cur_node - return dp_dists[p_cnt] - - -p_cnt,road_cnt = map(int,input().split()) -roads = {i:[] for i in range(1,p_cnt+1)} -for _ in range(road_cnt): - a,b,t = map(int,input().split()) - roads[a].append((b,t)) - roads[b].append((a,t)) - -optimal_path = {i:0 for i in range(1,p_cnt+1)} -no_police = dijkstra(0,0) - -max_cost = 0 -for path in optimal_path: - a,b = optimal_path[path],path - new_time = dijkstra(a,b) - if max_cost<(new_time-no_police): - max_cost = new_time-no_police - -if max_cost==float('inf'): - print(-1) -elif max_cost>=0: - print(max_cost) diff --git "a/2309\354\235\274\352\263\261\353\202\234\354\236\245\354\235\264.py" "b/2309\354\235\274\352\263\261\353\202\234\354\236\245\354\235\264.py" index e40be20..798aa36 100644 --- "a/2309\354\235\274\352\263\261\353\202\234\354\236\245\354\235\264.py" +++ "b/2309\354\235\274\352\263\261\353\202\234\354\236\245\354\235\264.py" @@ -1,17 +1,26 @@ -import sys -input = sys.stdin.readline - -# 키의 합이 100 9명 중 7명의 - -dwarf = [int(input()) for _ in range(9)] - -for i in range(1,9): - for j in range(i): - if sum(dwarf)-(dwarf[i]+dwarf[j])==100: - del dwarf[i] - del dwarf[j] - dwarf.sort() - for k in range(7): - print(dwarf[k]) - exit() - +import sys +input = sys.stdin.readline + +N = int(input()) + +if N//1000000000 != 0: + ans = 10 + 9*900000000 + 8*90000000 + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//100000000 != 0: + ans = 9*(N-99999999) + 8*90000000 + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//10000000 != 0: + ans = 8*(N-9999999) + 7*9000000 + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//1000000 !=0: + ans = 7*(N-999999) + 6*900000 + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//100000 !=0: + ans = 6*(N-99999) + 5*90000 + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//10000 !=0: + ans = 5*(N-9999) + 4*9000 + 3*900 + 2*90 + 1*9 +elif N//1000 !=0: + ans = 4*(N-999) + 3*900 + 2*90 + 1*9 +elif N//100 !=0: + ans = 3*(N-99) + 2*90 + 1*9 +elif N//10 !=0: + ans = 2*(N-9) + 1*9 +else: + ans = 1*N +print(ans) diff --git "a/2316 \353\217\204\354\213\234\354\231\225\353\263\265\355\225\230\352\270\260 2.py" "b/2316 \353\217\204\354\213\234\354\231\225\353\263\265\355\225\230\352\270\260 2.py" deleted file mode 100644 index c57ff00..0000000 --- "a/2316 \353\217\204\354\213\234\354\231\225\353\263\265\355\225\230\352\270\260 2.py" +++ /dev/null @@ -1,341 +0,0 @@ -import sys -input=sys.stdin.readline -n,p=map(int,input().split()) -adj=[[] for _ in range(2*n)] -for i in range(n): - adj[2*i+1].append(2*i) -for _ in range(p): - i,j=map(int,input().split()) - adj[2*i-2].append(2*j-1) - adj[2*j-2].append(2*i-1) -def dfs(i): - global found,cnt - if i==3: - for k in range(len(path)-1): - u,v=path[k],path[k+1] - adj[u].remove(v) - adj[v].append(u) - found=1 - cnt+=1 - return - for j in adj[i]: - if found: - break - if not visit[j]: - visit[j]=1 - path.append(j) - dfs(j) - path.pop() -cnt=0 -while 1: - found=0 - visit=[1]+[0]*(2*n-1) - path=[0] - dfs(0) - if not found: - break -print(cnt) - - - -# 3 -import sys - - -def dfs(cur): - if cur == 2: - return 1 - - for nxt in range(2, 2 * n + 1): - if graph[cur][nxt] and not visit[nxt]: - visit[nxt] = 1 - if dfs(nxt): - graph[cur][nxt] -= 1 - graph[nxt][cur] += 1 - return 1 - - return 0 - - -n, m = map(int, sys.stdin.readline().split()) -graph = [[0] * (2 * n + 1) for _ in range(2 * n + 1)] - -for i in range(1, n + 1): - graph[i][i + n] = 1 - -for _ in range(m): - start, end = map(int, sys.stdin.readline().split()) - graph[start + n][end] += 1 - graph[end + n][start] += 1 - -ans = 0 -flow = 1 -while flow: - visit = [0] * (2 * n + 1) - flow = dfs(1 + n) - ans += flow - -print(ans) - - -# 4 -from collections import deque -import sys -input = sys.stdin.readline -n, p = map(int, input().split()) -C = [[0] * (2 * n) for _ in range(2 * n)] -F = [[0] * (2 * n) for _ in range(2 * n)] -graph = [[] for _ in range(2*n)] - -for i in range(p): - a, b = map(int, input().split()) - a = (a - 1) * 2 + 1 - b = (b - 1) * 2 - C[a][b] = 1 - graph[a].append(b) - graph[b].append(a) - C[b+1][a-1] = 1 - graph[b+1].append(a-1) - graph[a-1].append(b+1) -for i in range(n): - a, b = i * 2, i * 2 + 1 - C[a][b] = 1 - graph[a].append(b) - graph[b].append(a) - -def dfs(u, limit): - if limit <= 0: - return 0 - if u == E: - return limit - val = 0 - for v in graph[u]: - res = C[u][v] - F[u][v] - if level[v] == level[u] + 1 and res > 0: - flow = dfs(v, min(limit - val, res)) - F[u][v] += flow - F[v][u] -= flow - val += flow - if val == 0: - level[u] -= 1 - return val - -S, E = 1, 2 -total = 0 -while True: - Q = deque([S]) - level = [-1] * len(graph) - level[S] = 0 - while Q: - u = Q.popleft() - for v in graph[u]: - if level[v] == -1 and C[u][v] > F[u][v]: - level[v] = level[u] + 1 - Q.append(v) - if level[E] == -1: - break - total += dfs(S, sum(C[S][v] for v in graph[S])) -print(total) - - -# Dinic algorithm but with very sparse graphs -# adj = list of adjacent nodes, must be made bidirectional -# C = capacity dict -# s = index of source -# t = index of sink - -from collections import deque, defaultdict -def Dinic(G, C, s, t): - def send(u, limit): - if limit <= 0: return 0 - if u == t: return limit - val = 0 - for v in G[u]: - res = C[(u,v)]-flow[(u,v)] - if level[v] == level[u]+1 and res>0: - a = send(v, min(limit-val, res)) - flow[(u,v)]+= a; flow[(v,u)]-= a; val+= a - if val == 0: level[u]-= 1 - return val - Q, tot, n, flow = deque(), 0, len(G), defaultdict(int) - while 1: - Q.append(s); level = [-1]*n; level[s] = 0 - while len(Q) > 0: - u = Q.popleft() - for v in G[u]: - if level[v] == -1 and C[(u,v)] > flow[(u,v)]: level[v] = level[u]+1; Q.append(v) - if level[t] == -1: return tot#, flow - tot+= send(s, sum(C[(s,v)] for v in G[s])) - -def addedge(i, j, cap): - G[i].append(j); G[j].append(i); C[(i,j)]+= cap - -# 0 ~ n-1: vertex in -# n ~ 2n-1: vertex out -from sys import stdin -input = stdin.readline -n, p = map(int,input().split()) -G = [[] for i in range(2*n)] -C = defaultdict(int) - -for i in range(n): addedge(i, i+n, 1) -for i in range(p): - a, b = sorted(map(int,input().split())) - addedge(a+n-1, b-1, 1) - addedge(b+n-1, a-1, 1) -print(Dinic(G, C, n, 1)) - - -# 5 -INF = float("inf") - - -class Dinic: - def __init__(self, n): - self.lvl = [0] * n - self.ptr = [0] * n - self.q = [0] * n - self.adj = [[] for _ in range(n)] - - def add_edge(self, a, b, c, rcap=0): - self.adj[a].append([b, len(self.adj[b]), c, 0]) - self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0]) - - def dfs(self, v, t, f): - if v == t or not f: - return f - - for i in range(self.ptr[v], len(self.adj[v])): - e = self.adj[v][i] - if self.lvl[e[0]] == self.lvl[v] + 1: - p = self.dfs(e[0], t, min(f, e[2] - e[3])) - if p: - self.adj[v][i][3] += p - self.adj[e[0]][e[1]][3] -= p - return p - self.ptr[v] += 1 - - return 0 - - def calc(self, s, t): - flow, self.q[0] = 0, s - for l in range(31): # l = 30 maybe faster for random data - while True: - self.lvl, self.ptr = [0] * len(self.q), [0] * len(self.q) - qi, qe, self.lvl[s] = 0, 1, 1 - while qi < qe and not self.lvl[t]: - v = self.q[qi] - qi += 1 - for e in self.adj[v]: - if not self.lvl[e[0]] and (e[2] - e[3]) >> (30 - l): - self.q[qe] = e[0] - qe += 1 - self.lvl[e[0]] = self.lvl[v] + 1 - - p = self.dfs(s, t, INF) - while p: - flow += p - p = self.dfs(s, t, INF) - - if not self.lvl[t]: - break - - return flow - - -N,P = map(int,input().split()) -flow = Dinic(2 * N - 2) -for i in range(2,N): - flow.add_edge(i, i + N - 2, 1) -for _ in range(P): - a,b = map(int,input().split()) - aNew = a + (N - 2) * (a != 1 and a != 2) - aNew -= 1 - bNew = b + (N - 2) * (b != 1 and b != 2) - bNew -= 1 - flow.add_edge(aNew, b - 1, 1) - flow.add_edge(bNew, a - 1, 1) -print(flow.calc(0, 1)) - - -# 6 -from collections import deque -from sys import stdin, stdout - -N, P = map(int, stdin.readline().split()) -adj = [set() for _ in range(1+N*2)] -fn = [[0] * (1+N*2) for _ in range(1+N*2)] -cn = [[0] * (1+N*2) for _ in range(1+N*2)] - -for i in range(1, 1+N): - adj[i+N].add(i) - cn[i+N][i] += 1 - adj[i].add(i+N) - cn[i][i+N] += 0 -cn[2+N][2] += P - - -def flow(prev): - route = [2] - flow = 1 - while 1: - now = route[-1] - pre = prev[now] - flow = min(flow, cn[pre][now] - fn[pre][now]) - route.append(pre) - if pre == 1: - break - while route: - now = route.pop() - nxt = route[-1] - fn[now][nxt] += flow - fn[nxt][now] -= flow - if now % N != nxt % N: - if now > N: - fn[now-N][nxt+N] += flow - fn[nxt+N][now-N] -= flow - else: - fn[now+N][nxt-N] += flow - fn[nxt-N][now+N] -= flow - if nxt == 2: - break - return flow - - -def bfs(): - queue = deque() - queue.append(1) - prev = [-1]*(1+N*2) - while queue: - now = queue.popleft() - for nxt in adj[now]: - if cn[now][nxt] > fn[now][nxt] and prev[nxt] == -1: - prev[nxt] = now - queue.append(nxt) - if nxt == 2: - ans = flow(prev) - return ans - return 0 - - -for _ in range(P): - a, b = map(int, stdin.readline().split()) - cn[a][b+N] += 1 - adj[a].add(b+N) - cn[b][a+N] += 1 - adj[b].add(a+N) - - cn[a+N][b] += 0 - adj[a+N].add(b) - cn[b+N][a] += 0 - adj[b+N].add(a) - - -total = 0 -while 1: - temp = bfs() - if temp == 0: - break - total += temp - -stdout.write(f"{total}") \ No newline at end of file diff --git "a/23288 \354\243\274\354\202\254\354\234\204 \352\265\264\353\246\254\352\270\2602.py" "b/23288 \354\243\274\354\202\254\354\234\204 \352\265\264\353\246\254\352\270\2602.py" deleted file mode 100644 index c35fb02..0000000 --- "a/23288 \354\243\274\354\202\254\354\234\204 \352\265\264\353\246\254\352\270\2602.py" +++ /dev/null @@ -1,70 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def rotate_dice(d): - if d == 0: - dice['top'], dice['left'], dice['bottom'], dice['right'] = dice['left'], dice['bottom'], dice['right'], dice['top'] - elif d == 1: - dice['top'], dice['up'], dice['bottom'], dice['down'] = dice['up'], dice['bottom'], dice['down'], dice['top'] - elif d == 2: - dice['left'], dice['bottom'], dice['right'], dice['top'] = dice['top'], dice['left'], dice['bottom'], dice['right'] - else: - dice['up'], dice['bottom'], dice['down'], dice['top'] = dice['top'], dice['up'], dice['bottom'], dice['down'] - - -def bfs(x, y, pivot): - q = deque() - q.append((x, y)) - cnt = 1 - visited = set() - visited.add((x, y)) - while q: - x, y = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < M and maps[nx][ny] == pivot and (nx, ny) not in visited: - visited.add((nx, ny)) - cnt += 1 - q.append((nx, ny)) - return cnt * pivot - - -def move(x, y, k): - global answer - q = [] - q.append((x, y, 0)) - while k: - x, y, direction = q.pop() - nx, ny = x + delta[direction][0], y + delta[direction][1] - if nx < 0 or nx >= N: - direction = (direction + 2) % 4 - nx, ny = x + delta[direction][0], y + delta[direction][1] - elif ny < 0 or ny >= M: - direction = (direction + 2) % 4 - nx, ny = x + delta[direction][0], y + delta[direction][1] - # 방향성에 따라 주사위 회전 - rotate_dice(direction) - # bfs answer갱신 - answer += bfs(nx, ny, maps[nx][ny]) - # bottom값과 map값 사이 비교 후 방향 수정 - if dice['bottom'] > maps[nx][ny]: - direction = (direction + 1) % 4 - elif dice['bottom'] < maps[nx][ny]: - direction = (direction - 1) % 4 - q.append((nx, ny, direction)) - k -= 1 - - -N, M, K = map(int, input().split()) -maps = [list(map(int, input().split())) for _ in range(N)] -dice = {'up': 2, 'left': 4, 'top': 1, 'right': 3, 'down': 5, 'bottom': 6} -delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) -answer = 0 - -# 이동 -move(0, 0, K) -print(answer) - - diff --git "a/23289 \354\230\250\355\222\215\352\270\260 \354\225\210\353\205\225.py" "b/23289 \354\230\250\355\222\215\352\270\260 \354\225\210\353\205\225.py" deleted file mode 100644 index d5a6bf6..0000000 --- "a/23289 \354\230\250\355\222\215\352\270\260 \354\225\210\353\205\225.py" +++ /dev/null @@ -1,132 +0,0 @@ -from collections import defaultdict, deque -import sys -input = sys.stdin.readline - - -def spread_temperature(): - for warmer in warmers: - q = deque() - x, y = warmer - d = warmers[warmer] - nx, ny = x + delta[d][0], y + delta[d][1] - q.append((nx, ny)) - visited = set() - rooms[nx][ny] += 5 - level = 4 - while q and level: - for _ in range(len(q)): - x, y = q.popleft() - for dx, dy in winds[d]: - nx, ny = x + dx, y + dy - if 0 <= nx < R and 0 <= ny < C and (nx, ny) not in visited and (nx, ny) not in walls[d][(x, y)]: - visited.add((nx, ny)) - q.append((nx, ny)) - rooms[nx][ny] += level - level -= 1 - if not level: - break - - -def warmming_house(): - new_board = [[0] * C for _ in range(R)] - for x in range(R): - for y in range(C): - if rooms[x][y] >= 4: - for i in range(4): - nx, ny = x + delta[i][0], y + delta[i][1] - if 0 <= nx < R and 0 <= ny < C and rooms[x][y] > rooms[nx][ny]: - if (nx, ny) in walls[i][(x, y)]: - continue - unit = (rooms[x][y] - rooms[nx][ny]) // 4 - new_board[nx][ny] += unit - new_board[x][y] -= unit - for i in range(R): - for j in range(C): - rooms[i][j] += new_board[i][j] - - -def down_boundary(): - for i in range(R): - for j in (0, C - 1): - if rooms[i][j]: - rooms[i][j] -= 1 - for i in (0, R - 1): - for j in range(1, C - 1): - if rooms[i][j]: - rooms[i][j] -= 1 - - -def checking(): - for x, y in list(check): - if rooms[x][y] >= K: - check.discard((x, y)) - - -R, C, K = map(int, input().split()) -rooms = [list(map(int, input().split())) for _ in range(R)] -W = int(input()) - -right = defaultdict(set) -left = defaultdict(set) -up = defaultdict(set) -down = defaultdict(set) -walls = {idx: name for idx, name in enumerate([right, left, up, down])} -for _ in range(W): - x, y, t = map(int, input().split()) - x -= 1 - y -= 1 - if t: - walls[0][(x, y)].add((x, y + 1)) - walls[0][(x - 1, y)].add((x, y + 1)) - walls[0][(x + 1, y)].add((x, y + 1)) - walls[1][(x, y + 1)].add((x, y)) - walls[1][(x - 1, y + 1)].add((x, y)) - walls[1][(x + 1, y + 1)].add((x, y)) - walls[2][(x, y + 1)].add((x - 1, y)) - walls[2][(x, y)].add((x - 1, y + 1)) - walls[3][(x, y + 1)].add((x + 1, y)) - walls[3][(x, y)].add((x + 1, y + 1)) - else: - walls[0][(x, y)].add((x - 1, y + 1)) - walls[0][(x - 1, y)].add((x, y + 1)) - walls[1][(x, y)].add((x - 1, y - 1)) - walls[1][(x - 1, y)].add((x, y - 1)) - walls[2][(x, y)].add((x - 1, y)) - walls[2][(x, y - 1)].add((x - 1, y)) - walls[2][(x, y + 1)].add((x - 1, y)) - walls[3][(x - 1, y)].add((x, y)) - walls[3][(x - 1, y - 1)].add((x, y)) - walls[3][(x - 1, y + 1)].add((x, y)) - -winds = { - 0: [(-1, 1), (0, 1), (1, 1)], - 1: [(-1, -1), (0, -1), (1, -1)], - 2: [(-1, -1), (-1, 0), (-1, 1)], - 3: [(1, 1), (1, 0), (1, -1)], - } -delta = [(0, 1), (0, -1), (-1, 0), (1, 0)] -warmers = {} -check = set() -for i in range(R): - for j in range(C): - if rooms[i][j] == 5: - check.add((i, j)) - elif rooms[i][j]: - warmers[(i, j)] = rooms[i][j] - 1 - rooms[i][j] = 0 - -cnt = 0 -while len(check): - # 온풍기에서 바람이 한번씩 나온다. - spread_temperature() - # 온도 조절 - warmming_house() - # 가장 바깥쪽 칸의 온도 1씩 감소 - down_boundary() - # 초콜릿 1개 먹기 - cnt += 1 - if cnt > 100: - break - # 체킹 - checking() -print(cnt) \ No newline at end of file diff --git "a/23290 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\263\265\354\240\234.py" "b/23290 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\263\265\354\240\234.py" deleted file mode 100644 index 71aa41c..0000000 --- "a/23290 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\263\265\354\240\234.py" +++ /dev/null @@ -1,84 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque -from heapq import heappop, heappush - - -def move_fish(arr): - ret = [[[] for _ in range(4)] for _ in range(4)] - for x in range(4): - for y in range(4): - while arr[x][y]: - d = arr[x][y].pop() - for i in range(d, d - 8, -1): - i %= 8 - nx, ny = x + delta[i][0], y + delta[i][1] - if (nx, ny) != shark and 0 <= nx < 4 and 0 <= ny < 4 and not smell[nx][ny]: - ret[nx][ny].append(i) - break - else: - ret[x][y].append(d) - return ret - - -def move_shark(s): - x, y = s - q = deque() - # 현재좌표, 방문좌표, 방향점수, 총갯수, - q.append((x, y, set(), '', 0)) - for _ in range(3): - for _ in range(len(q)): - x, y, visited, dir_score, cnt = q.popleft() - for i in range(1, 5): - nx, ny = x + s_delta[i][0], y + s_delta[i][1] - if 0 <= nx < 4 and 0 <= ny < 4: - if (nx, ny) in visited: - q.append((nx, ny, visited, dir_score + str(i), cnt)) - else: - q.append((nx, ny, visited | {(nx, ny)}, dir_score + str(i), cnt + len(tmp[nx][ny]))) - heap = [] - while q: - x, y, visited, dir_score, cnt = q.pop() - heappush(heap, (-cnt, int(dir_score), x, y, visited)) - cnt, score, x, y, visited = heappop(heap) - for i, j in visited: - if tmp[i][j]: - tmp[i][j].clear() - smell[i][j] = 3 - return (x, y) - - -M, S = map(int, input().split()) -fishes = [tuple(map(lambda x: int(x) - 1, input().split())) for _ in range(M)] -delta = [(0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)] -s_delta = [0, (-1, 0), (0, -1), (1, 0), (0, 1)] -matrix = [[[] for _ in range(4)] for _ in range(4)] -for x, y, d in fishes: - matrix[x][y].append(d) - -shark = tuple(map(lambda x: int(x) - 1, input().split())) -smell = [[0] * 4 for _ in range(4)] -for _ in range(S): - # 모든 물고기 정보 복제 tmp. 5번에서 더해줌. - tmp = [[k[:] for k in row] for row in matrix] - # 모든 물고기 한칸 이동. 물고기 냄새 있거나 상어있으면 이동 불가. 이동할 수 있을때까지 delta -1 없으면 이동불가. - tmp = move_fish(tmp) - # 상어 연속 3칸 이동. 상하좌우로 인접한 칸으로 이동할 수 있다. 범위를 벗어나면 불가능한 이동. - shark = move_shark(shark) - # 이동 중에 상어가 물고기 있는 칸으로 이동하면 그 칸의 모든 물고기는 삭제. 냄새를 남김. 가능한 방법 중 물고기가 가장 많은 바법으로 남김. - # 여러가지인경우 사전순으로 이동. 상은 1, 좌는 2, 하는 3, 우는 4. 사전순 앞서는 경우로 이동. - # 2턴 전 냄새 사라짐. - for i in range(4): - for j in range(4): - if smell[i][j]: - smell[i][j] -= 1 - # 물고기 배열 tmp fishes에 더해줌. - for i in range(4): - for j in range(4): - matrix[i][j] += tmp[i][j] -answer = 0 -for i in range(4): - for j in range(4): - answer += len(matrix[i][j]) - -print(answer) \ No newline at end of file diff --git "a/23291 \354\226\264\355\225\255\354\240\225\353\246\254.py" "b/23291 \354\226\264\355\225\255\354\240\225\353\246\254.py" deleted file mode 100644 index d92ad16..0000000 --- "a/23291 \354\226\264\355\225\255\354\240\225\353\246\254.py" +++ /dev/null @@ -1,468 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -# 달팽이를 만든다. 시작좌표는 -def make_snail(): - row, col = n, n - if n**2 - N >= n: - col -= 1 - matrix = [[0] * col for _ in range(row)] - q = deque() - q.append((row - 1, col - 1, 0)) - blank_cnt = row * col - N - start = N - 1 - while q: - x, y, d = q.popleft() - matrix[x][y] = arr[start] - if blank_cnt: - matrix[x][y] = -1 - for i in range(d, d + 4): - i %= 4 - nx, ny = x + delta[i][0], y + delta[i][1] - if 0 <= nx < row and 0 <= ny < col and not matrix[nx][ny]: - q.append((nx, ny, i)) - if blank_cnt: - blank_cnt -= 1 - else: - start -= 1 - break - return matrix - - -# 최솟값들에 대해 1더해준다. -def engage_minimum(): - min_v = min(arr) - for i in range(N): - if arr[i] == min_v: - arr[i] += 1 - - -def spread(matrix): - row = len(matrix) - col = len(matrix[0]) - new_matrix = [[0] * col for _ in range(row)] - if matrix[-1][-1] == -1: - row -= 1 - a, b = row - 1, row - if matrix[a][0] != -1 and matrix[b][0] != -1: - if matrix[a][0] < matrix[b][0]: - a, b = b, a - move = (matrix[a][0] - matrix[b][0]) // 5 - new_matrix[a][0] -= move - new_matrix[b][0] += move - for y in range(col): - if matrix[row][y] == -1: - break - for dy in (1, -1): - ny = y + dy - if 0 <= ny < col and matrix[row][ny] != -1: - if matrix[row][y] - matrix[row][ny] < 5: - continue - move = (matrix[row][y] - matrix[row][ny]) // 5 - new_matrix[row][ny] += move - new_matrix[row][y] -= move - for x in range(row): - for y in range(col): - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < row and 0 <= ny < col: - if matrix[x][y] - matrix[nx][ny] < 5: - continue - move = (matrix[x][y] - matrix[nx][ny]) // 5 - new_matrix[nx][ny] += move - new_matrix[x][y] -= move - if matrix[-1][-1] == -1: - row += 1 - for i in range(row): - for j in range(col): - matrix[i][j] += new_matrix[i][j] - return matrix - - -# 달팽이인데 오른족 아래 빈칸 상태면 왼쪽 위부터 행을 순서대로 읽는다. -# 완전한 정사각형이면 왼쪽 아래부터 위로 열을 순대로 읽는다. -def make_arr(matrix): - row = len(matrix) - col = len(matrix[0]) - ret = [] - if matrix[-1][-1] == -1: - for i in range(row): - for j in range(col): - if matrix[i][j] == -1: - continue - ret.append(matrix[i][j]) - else: - for i in range(col): - for j in range(row - 1, -1, -1): - ret.append(matrix[j][i]) - return ret - - -# 행 4개에 분배하기. 배열 4등분 해서 뒤집은 3번째, 2번째, 뒤집은 1번째, 4번째 순. -def make_four_row(arr): - new_matrix = [] - new_matrix.append(arr[pivot * 2:pivot * 3][::-1]) - new_matrix.append(arr[pivot:pivot * 2]) - new_matrix.append(arr[:pivot][::-1]) - new_matrix.append(arr[pivot * 3:]) - return new_matrix - - -N, K = map(int, input().split()) -arr = list(map(int, input().split())) -pivot = N // 4 -for i in range(2, 11): - if i**2 >= N: - n = i - break - -delta = ((0, -1), (-1, 0), (0, 1), (1, 0)) - -answer = 0 -while max(arr) - min(arr) > K: - # 1. 최솟값들에 대해 1씩 넣어준다. - engage_minimum() - # 2. 왼쪽을 중앙으로 시작해서 달팽이. - # N보다 큰 제곱수의 2차원 배열을 만든 후 남는 칸수만큼 오른쪽에서 offset을 준 뒤 달팽이 하며 감아 들어가면 됨. - matrix = make_snail() - # 3. 달팽이에서 인접칸 검사 (a - b) // 5만큼 분배. 동시 분배. - matrix = spread(matrix) - # 4. 펼치는건 왼쪽 아래부터 위로 - arr = make_arr(matrix) - # 첫 N // 4는 뒤집어서 2행, 다음 N// 4는 그대로 1행, 그다음 N // 4는 뒤집어서 0행 마지막 N // 4는 그대로 3행. - matrix = make_four_row(arr) - # 6. 물고기 분배 한번 더. - matrix = spread(matrix) - # 7. 1열부터 펼치면 3행부터 거꾸로 올라가며 펼치면 됨. - arr = make_arr(matrix) - answer += 1 -print(answer) - - -# jh님 코드 -def rot_cw(grid): - h = len(grid); w = len(grid[0]) - G = [[0]*h for i in range(w)] - for i in range(h): - for j in range(w): - G[j][h-i-1] = grid[i][j] - return G - -def rot_180(grid): - return [row[::-1] for row in grid[::-1]] - -def move_fish(multi): - h = len(multi) - w = len(multi[0]) - movable = [] - for i in range(h): - for j in range(w): - if multi[i][j] == -1: continue - for ni,nj in (i-1,j),(i+1,j),(i,j-1),(i,j+1): - if not (0<=ni 0: movable.append((i,j,ni,nj,d)) - for i,j,ni,nj,d in movable: - multi[i][j]-= d - multi[ni][nj]+= d - -MIS = lambda: map(int,input().split()) - -n, k = MIS() -box = list(MIS()) -op = 0 - -while max(box) - min(box) > k: - op+= 1 - # supplement to minimum - mfish = min(box) - for i in range(n): - if box[i] == mfish: box[i]+= 1 - # cw - multi = [[box[0]], [box[1]]] - single = box[2:] - while 1: - height = len(multi) - if height > len(single): break - multi = rot_cw(multi) + [single[:height]] - single = single[height:] - # move fish - for i in range(len(multi)-1): - multi[i].extend([-1] * len(single)) - multi[-1].extend(single) - move_fish(multi) - # linearize - box = [] - for j in range(len(multi[0])): - row = [multi[i][j] for i in range(len(multi)-1, -1, -1)] - box.extend([x for x in row if x != -1]) - # rot 180 - multi = [box] - for STEP in range(2): - w = len(multi[0]) - left = rot_180([row[:w//2] for row in multi]) - right = [row[w//2:] for row in multi] - multi = left + right - move_fish(multi) - # linearize - box = [] - for j in range(len(multi[0])): - row = [multi[i][j] for i in range(len(multi)-1, -1, -1)] - box.extend([x for x in row if x != -1]) -print(op) - -# gk님 코드 -import sys -def input(): - return sys.stdin.readline().rstrip() - -def check(arr): - if max(arr) - min(arr) <=K: - return False - return True -def push(): - min_value = min(arr[-1]) - for i in range(N): - if arr[-1][i] == min_value: - arr[-1][i] += 1 -def roll(arr): - row,col = 1,1 - new_N = N - time = 0 - while True: - new_temp = [[-1 for _ in range(new_N-col)] for _ in range(row+1)] - - for y in range(col,new_N): - new_temp[-1][y-col] = arr[-1][y] - - for y in range(col): - for x in range(len(arr)): - new_temp[y][len(arr)-x-1] = arr[x][y] - new_N = new_N-col - if time%2: - row += 1 - col += 1 - time += 1 - arr = [row[:] for row in new_temp] - row_N = len(new_temp) - if row_N*(col+1) >N: - break - return arr -def outOfbound(x,y,row,col): - if 0<=x=5: - gap = (new_arr[x][y] - new_arr[nx][ny])//5 - temp[x][y] -= gap - temp[nx][ny] += gap - for x in range(row): - for y in range(col): - new_arr[x][y] += temp[x][y] -def flatting(maze): - temp_arr = [[]] - row = len(maze) - col = len(maze[0]) - for y in range(col): - for x in range(row-1,-1,-1): - if maze[x][y]==-1:continue - temp_arr[-1].append(maze[x][y]) - return temp_arr -def spread(): - spread_arr = flatting(new_arr) - temp = [[-1 for _ in range(N//4)] for _ in range(4)] - - for x in range(4): - if x%2: - start_x = N//4*x - y = 0 - while y=0: - temp[x][y] = spread_arr[-1][start_x] - start_x += 1 - y -= 1 - return temp - - -N,K = map(int,input().split()) - -arr = [list(map(int,input().split()))] -dx = [-1,0,1,0] -dy = [0,-1,0,1] -turn = 0 -while check(arr[-1]): - push() - new_arr = roll(arr) - blow() - new_arr = spread() - blow() - arr = flatting(new_arr) - turn += 1 -print(turn) - - -# as님 코드 -from sys import stdin - -dx = [1,0] -dy = [0,1] -input = stdin.readline - -n,k = map(int, input().split()) -board = [[0]*n for _ in range(n)] -board[0] = list(map(int, input().split())) - -def solv(): - answer = 0 - while True: - add_fish() - stack_rotate() - modify_fish_count() - set_board() - - fold_board() - modify_fish_count() - set_board() - answer += 1 - if max(board[0])-min(board[0]) <= k: - print(answer) - return -def add_fish(): - global board - target = min(board[0]) - for idx in range(n): - if board[0][idx] == target: - board[0][idx] += 1 - - board[1][1] = board[0][0] - board[0][0] = 0 - -def stack_rotate(): - while True: - step = 0 - length = 0 - max_x = search_max_x() - - flag=False - for y in range(n): - if not flag: - if board[0][y] == 0: - step += 1 - else: - flag = True - if board[1][y] != 0: - length = 1 - else: - if board[1][y] != 0: - length += 1 - else: - break - if step > 0: - renew_board(step,max_x) - - if board[0][length+max_x-1] == 0: - return - for x in range(max_x): - for y in range(length): - board[length-y][length+x],board[x][y] = board[x][y],0 - -def renew_board(step,max_x): - global board - for y in range(step, n): - for x in range(max_x): - board[x][y-step],board[x][y] = board[x][y],0 -def set_board(): - global board - new_row = [] - max_x = search_max_x() - - for y in range(n): - if board[0][y] == 0: - break - for x in range(max_x): - if board[x][y] == 0: - break - new_row.append(board[x][y]) - - for x in range(max_x): - board[x] = [0]*n - board[0] = new_row - -def fold_board(): - length = n//2 - for y in range(length): - board[1][n-y-1], board[0][y] = board[0][y], 0 - - renew_board(length,2) - - length = n//4 - for x in range(2): - for y in range(length): - board[3-x][n//2-y-1],board[x][y]=board[x][y],0 - - renew_board(length, 4) - -def modify_fish_count(): - global board - - tmp = [[0]*n for _ in range(n)] - for x in range(n): - if board[x][0] == 0: - break - for y in range(n): - if board[x][y] == 0: - break - for dir in range(2): - nx = x + dx[dir] - ny = y + dy[dir] - - if point_validator(nx,ny): - d = abs(board[x][y]-board[nx][ny])//5 - if board[x][y] > board[nx][ny]: - tmp[x][y] -= d - tmp[nx][ny] += d - elif board[x][y] < board[nx][ny]: - tmp[nx][ny] -= d - tmp[x][y] += d - - for x in range(n): - for y in range(n): - board[x][y] += tmp[x][y] -def point_validator(x,y): - if x < 0 or y < 0 or x >= n or y >= n: - return False - elif board[x][y] == 0: - return False - return True -def search_max_x(): - for y in range(n): - if board[0][y] == 0: - continue - for x in range(n): - if board[x][y] == 0: - return x - return n -solv() diff --git "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\235.py" "b/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\235.py" deleted file mode 100644 index a3f9634..0000000 --- "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\235.py" +++ /dev/null @@ -1,45 +0,0 @@ -INF = 1_000_000 -N = int(input()) -T = [INF] * (N+N) - - -def update(i, v): - i = i + N - p = i // 2 - T[i] = v - while p and T[i] < T[p]: - T[p] = T[i] - i, p = p, p // 2 - - -def get(i, j): - r = 1_000_000 - i, j = i + N, j + N - while i <= j: - if i&1: - r = min(T[i], r) - i += 1 - if not j&1: - r = min(T[j], r) - j -= 1 - i, j = i//2, j//2 - return r - - -B = [0] * (N+1) -C = [0] * (N+1) - -A = list(map(int, input().split())) -i = 0 -for b in map(int, input().split()): - i += 1 - B[b] = i -i = 0 -for c in map(int, input().split()): - i += 1 - C[c] = i -c = N -for x in A: - c -= get(1-1, B[x]-1) < C[x] - update(B[x]-1, C[x]-1) -print(c) \ No newline at end of file diff --git "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2351.py" "b/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2351.py" deleted file mode 100644 index f9ed8ac..0000000 --- "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2351.py" +++ /dev/null @@ -1,71 +0,0 @@ -"""Solution code for "BOJ 2336. 굉장한 학생". - -- Problem link: https://www.acmicpc.net/problem/2336 -- Solution link: http://www.teferi.net/ps/problems/boj/2336 - -(This code was generated by Import Inliner v0.1) -""" - -import operator -import sys -from typing import Callable, Iterable, TypeVar - -INF = float('inf') -T = TypeVar('T') - - -# >>>[BEGIN] teflib.segmenttree.SegmentTree [v1.1] (Copied from teflib/segmenttree.py)<<< -class SegmentTree: - """Non-recursive segment tree supporting point update and range query.""" - - def __init__(self, - values: Iterable[T], - merge: Callable[[T, T], T] = operator.add): - l = list(values) - self._size = len(l) - self._tree = [0] * self._size + l - self._merge = merge - for i in range(self._size - 1, 0, -1): - self._tree[i] = merge(self._tree[i * 2], self._tree[i * 2 + 1]) - - def update(self, pos: int, value: T): - i = pos + self._size - while i: - self._tree[i] = self._merge(self._tree[i], value) - i >>= 1 - - def query(self, beg: int, end: int) -> T: - ret = self._tree[beg + self._size] - l, r = beg + self._size + 1, end + self._size - 1 - while l <= r: - if l % 2: - ret = self._merge(self._tree[l], ret) - if not r % 2: - ret = self._merge(self._tree[r], ret) - l, r = (l + 1) >> 1, (r - 1) >> 1 - return ret -# >>>[END] teflib.segmenttree.SegmentTree [v1.1]<<< - - -def main(): - N = int(sys.stdin.readline()) - student_to_rank = [0] * (N + 1) - for rank, student in enumerate(sys.stdin.readline().split()): - student_to_rank[int(student)] = rank - ranks = [[0, 0] for _ in range(N)] - for test_num in range(2): - for rank, student in enumerate(sys.stdin.readline().split()): - ranks[student_to_rank[int(student)]][test_num] = rank - - segtree = SegmentTree([INF] * N, min) - answer = 0 - for rank2, rank3 in ranks: - if segtree.query(0, rank2) > rank3: - answer += 1 - segtree.update(rank2, rank3) - - print(answer) - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2352.py" "b/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2352.py" deleted file mode 100644 index fa2ba4e..0000000 --- "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2352.py" +++ /dev/null @@ -1,54 +0,0 @@ -import sys -from math import log2, ceil - -n = int(sys.stdin.readline()) -num0 = list(map(int, sys.stdin.readline().split())) -score1 = [0] * (n + 1) -score2 = [0] * (n + 1) - -num1 = list(map(int, sys.stdin.readline().split())) -num2 = list(map(int, sys.stdin.readline().split())) - -for i in range(n): - score1[num1[i]] = i + 1 - score2[num2[i]] = i + 1 - -height = ceil(log2(n)) -tree = [float('inf')] * 2 ** (height + 1) - - -def minimum(a, b): - res = float('inf') - a += 2 ** height - 1 - b += 2 ** height - 1 - while a <= b: - if a % 2: - res = min(res, tree[a]) - a += 1 - if b % 2 == 0: - res = min(res, tree[b]) - b -= 1 - a //= 2 - b //= 2 - - return res - - -def update(k, c): - idx = 2 ** height + k - 1 - tree[idx] = c - while idx > 1: - idx //= 2 - tree[idx] = min(tree[2 * idx], tree[2 * idx + 1]) - - -ans = 1 -update(score1[num0[0]], score2[num0[0]]) - -for i in range(1, n): - tar = num0[i] - if minimum(1, score1[tar] - 1) > score2[tar]: - ans += 1 - update(score1[tar], score2[tar]) - -print(ans) \ No newline at end of file diff --git "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2353.py" "b/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2353.py" deleted file mode 100644 index 6a2b3f5..0000000 --- "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2353.py" +++ /dev/null @@ -1,43 +0,0 @@ -import sys - - -def update(idx, val): - while idx <= n: - tree[idx] = min(tree[idx], val) - idx += (idx & -idx) - - -def query(end): - ret = float('inf') - - while end > 0: - ret = min(ret, tree[end]) - end -= (end & -end) - - return ret - -n = int(sys.stdin.readline()) -student = [[] for _ in range(n + 1)] -tree = [float('inf')] * (n + 1) -student[0] = [0, 0, 0] - -for _ in range(3): - temp = list(map(int, sys.stdin.readline().split())) - - for i in range(1, n + 1): - num = temp[i - 1] - student[num].append(i) - -student.sort(key=lambda x:x[0]) - -ans = 0 -for i in range(1, n + 1): - sec_exam, thi_exam = student[i][1], student[i][2] - former_rank = query(sec_exam) - - if former_rank > thi_exam: - ans += 1 - - update(sec_exam, thi_exam) - -print(ans) \ No newline at end of file diff --git "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2354.py" "b/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2354.py" deleted file mode 100644 index 539862a..0000000 --- "a/2336 \352\265\211\354\236\245\355\225\234 \355\225\231\354\203\2354.py" +++ /dev/null @@ -1,249 +0,0 @@ -import typing - -def _ceil_pow2(n: int) -> int: - x = 0 - while (1 << x) < n: - x += 1 - - return x -def _bsf(n: int) -> int: - x = 0 - while n % 2 == 0: - x += 1 - n //= 2 - - return x -class LazySegTree: - def __init__( - self, - op: typing.Callable[[typing.Any, typing.Any], typing.Any], - e: typing.Any, - mapping: typing.Callable[[typing.Any, typing.Any], typing.Any], - composition: typing.Callable[[typing.Any, typing.Any], typing.Any], - id_: typing.Any, - v: typing.Union[int, typing.List[typing.Any]]) -> None: - self._op = op - self._e = e - self._mapping = mapping - self._composition = composition - self._id = id_ - - if isinstance(v, int): - v = [e] * v - - self._n = len(v) - self._log = _ceil_pow2(self._n) - self._size = 1 << self._log - self._d = [e] * (2 * self._size) - self._lz = [self._id] * self._size - for i in range(self._n): - self._d[self._size + i] = v[i] - for i in range(self._size - 1, 0, -1): - self._update(i) - - def set(self, p: int, x: typing.Any) -> None: - assert 0 <= p < self._n - - p += self._size - for i in range(self._log, 0, -1): - self._push(p >> i) - self._d[p] = x - for i in range(1, self._log + 1): - self._update(p >> i) - - def get(self, p: int) -> typing.Any: - assert 0 <= p < self._n - - p += self._size - for i in range(self._log, 0, -1): - self._push(p >> i) - return self._d[p] - - def prod(self, left: int, right: int) -> typing.Any: - assert 0 <= left <= right <= self._n - - if left == right: - return self._e - - left += self._size - right += self._size - - for i in range(self._log, 0, -1): - if ((left >> i) << i) != left: - self._push(left >> i) - if ((right >> i) << i) != right: - self._push(right >> i) - - sml = self._e - smr = self._e - while left < right: - if left & 1: - sml = self._op(sml, self._d[left]) - left += 1 - if right & 1: - right -= 1 - smr = self._op(self._d[right], smr) - left >>= 1 - right >>= 1 - - return self._op(sml, smr) - - def all_prod(self) -> typing.Any: - return self._d[1] - - def apply(self, left: int, right: typing.Optional[int] = None, - f: typing.Optional[typing.Any] = None) -> None: - assert f is not None - - if right is None: - p = left - assert 0 <= left < self._n - - p += self._size - for i in range(self._log, 0, -1): - self._push(p >> i) - self._d[p] = self._mapping(f, self._d[p]) - for i in range(1, self._log + 1): - self._update(p >> i) - else: - assert 0 <= left <= right <= self._n - if left == right: - return - - left += self._size - right += self._size - - for i in range(self._log, 0, -1): - if ((left >> i) << i) != left: - self._push(left >> i) - if ((right >> i) << i) != right: - self._push((right - 1) >> i) - - l2 = left - r2 = right - while left < right: - if left & 1: - self._all_apply(left, f) - left += 1 - if right & 1: - right -= 1 - self._all_apply(right, f) - left >>= 1 - right >>= 1 - left = l2 - right = r2 - - for i in range(1, self._log + 1): - if ((left >> i) << i) != left: - self._update(left >> i) - if ((right >> i) << i) != right: - self._update((right - 1) >> i) - - def max_right( - self, left: int, g: typing.Callable[[typing.Any], bool]) -> int: - assert 0 <= left <= self._n - assert g(self._e) - - if left == self._n: - return self._n - - left += self._size - for i in range(self._log, 0, -1): - self._push(left >> i) - - sm = self._e - first = True - while first or (left & -left) != left: - first = False - while left % 2 == 0: - left >>= 1 - if not g(self._op(sm, self._d[left])): - while left < self._size: - self._push(left) - left *= 2 - if g(self._op(sm, self._d[left])): - sm = self._op(sm, self._d[left]) - left += 1 - return left - self._size - sm = self._op(sm, self._d[left]) - left += 1 - - return self._n - - def min_left(self, right: int, g: typing.Any) -> int: - assert 0 <= right <= self._n - assert g(self._e) - - if right == 0: - return 0 - - right += self._size - for i in range(self._log, 0, -1): - self._push((right - 1) >> i) - - sm = self._e - first = True - while first or (right & -right) != right: - first = False - right -= 1 - while right > 1 and right % 2: - right >>= 1 - if not g(self._op(self._d[right], sm)): - while right < self._size: - self._push(right) - right = 2 * right + 1 - if g(self._op(self._d[right], sm)): - sm = self._op(self._d[right], sm) - right -= 1 - return right + 1 - self._size - sm = self._op(self._d[right], sm) - - return 0 - - def _update(self, k: int) -> None: - self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1]) - - def _all_apply(self, k: int, f: typing.Any) -> None: - self._d[k] = self._mapping(f, self._d[k]) - if k < self._size: - self._lz[k] = self._composition(f, self._lz[k]) - - def _push(self, k: int) -> None: - self._all_apply(2 * k, self._lz[k]) - self._all_apply(2 * k + 1, self._lz[k]) - self._lz[k] = self._id - -N = int(input()) - -students = [] - -for _ in range(N): - students.append([]) - -a = list(map(int,input().split())) -for i in range(N): - students[a[i] - 1].append(i + 1) - -a = list(map(int,input().split())) -for i in range(N): - students[a[i] - 1].append(i + 1) - -a = list(map(int,input().split())) -for i in range(N): - students[a[i] - 1].append(i + 1) - -for i in range(N): - students[i] = tuple(students[i]) - -students.sort() - -rankData = LazySegTree(min, N, max, max, 0, [0] * N) - -cnt = 0 -for student in students: - if rankData.prod(student[1] - 1, N) < N + 1 - student[2]: - cnt += 1 - rankData.apply(student[1] - 1, N, N + 1 - student[2]) - # print(" ".join(map(str, map(lambda x: rankData.get(x), range(N))))) - -print(cnt) \ No newline at end of file diff --git "a/2357\354\265\234\353\214\223\352\260\222\354\265\234\354\206\237\352\260\222.py" "b/2357\354\265\234\353\214\223\352\260\222\354\265\234\354\206\237\352\260\222.py" deleted file mode 100644 index cccc4cc..0000000 --- "a/2357\354\265\234\353\214\223\352\260\222\354\265\234\354\206\237\352\260\222.py" +++ /dev/null @@ -1,52 +0,0 @@ -import sys -input = sys.stdin.readline -from math import ceil,log2 - -def init_min_tree(node,start,end): - if start==end: - min_tree[node] = a[start] - return min_tree[node] - mid= (start+end)//2 - min_tree[node] = min(init_min_tree(node*2,start,mid),init_min_tree(node*2+1,mid+1,end)) - return min_tree[node] - -def init_max_tree(node,start,end): - if start==end: - max_tree[node] = a[start] - return max_tree[node] - mid= (start+end)//2 - max_tree[node] = max(init_max_tree(node*2,start,mid),init_max_tree(node*2+1,mid+1,end)) - return max_tree[node] - -def query_min(node,start,end,left,right): - if start > right or end < left: - return float('inf') - if left <= start and end <= right: - return min_tree[node] - mid= (start+end)//2 - return min(query_min(node*2,start,mid,left,right),query_min(node*2+1,mid+1,end,left,right)) - -def query_max(node,start,end,left,right): - if start > right or end < left: - return 0 - if left <= start and end <= right: - return max_tree[node] - mid= (start+end)//2 - return max(query_max(node*2,start,mid,left,right),query_max(node*2+1,mid+1,end,left,right)) - - -N,M = map(int,input().split()) -a = [] -h = int(ceil(log2(N))) -min_tree = [0]*(1< cleared_nums[target+1]: - even = target+1 - elif cleared_nums[target-1] < cleared_nums[target+1]: - even = target-1 - else: - even = target-1 - two_even = True - - cnt += cleared_nums[even] - cleared_nums[target] - del cleared_nums[target] - if two_even: - del cleared_nums[even] - - print(cnt) \ No newline at end of file diff --git "a/2406\354\225\210\354\240\225\354\240\201\354\235\270 \353\204\244\355\212\270\354\233\214\355\201\254.py" "b/2406\354\225\210\354\240\225\354\240\201\354\235\270 \353\204\244\355\212\270\354\233\214\355\201\254.py" deleted file mode 100644 index 0d75f54..0000000 --- "a/2406\354\225\210\354\240\225\354\240\201\354\235\270 \353\204\244\355\212\270\354\233\214\355\201\254.py" +++ /dev/null @@ -1,148 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -def find(x): - if parent[x]==x: - return x - parent[x] = find(parent[x]) - return parent[x] - -def union(a,b): - a = find(a) - b = find(b) - - if level[a] >= level[b]: - parent[b] = a - if level[a]==level[b]: - level[a] += 1 - else: - parent[a] = b - -n, m = map(int, input().split()) -parent = {i:i for i in range(1,n+1)} -level = {i: 0 for i in range(1,n+1)} -# 2~n번컴퓨터까지 MST를 만들어라? -for _ in range(m): - x, y = map(int, input().split()) - if find(x) != find(y): - union(x,y) - -cost_matrix = [list(map(int, input().split())) for _ in range(n)] -costs = [] -for i in range(1,n-1): - for j in range(i+1,n): - heappush(costs,(cost_matrix[i][j],i+1,j+1)) - -min_cost = 0 -cnt = 0 -coms = [] -while costs: - c, a, b = heappop(costs) - if find(a) != find(b): - union(a,b) - min_cost += c - cnt += 1 - coms.append([a,b]) -print(min_cost, cnt) -for com in coms: - print(*com) - - - -# 다른풀이 -import sys -import heapq -def input(): - return sys.stdin.readline().rstrip() -def find_parent(ind): - if make_set[ind] == ind: - return ind - make_set[ind] = find_parent(make_set[ind]) - return make_set[ind] - -def union(x,y): - X = find_parent(x) - Y = find_parent(y) - if X == Y: - return False - else: - if ranks[X] < ranks[Y]: - X,Y = Y,X - make_set[Y] = X - if ranks[X] == ranks[Y]: - ranks[X] += 1 - return True - -N,M = map(int,input().split()) - -make_set = [i for i in range(N+1)] -ranks = [1 for _ in range(N+1)] -connect_cnt = 0 -for _ in range(M): - x,y = map(int,input().split()) - if union(x,y): - connect_cnt += 1 - -node_list = [] - -for x in range(N): - temp = list(map(int,input().split())) - - for y in range(N): - if x == 0 or y ==0 or x==y or x>y: - continue - else: - node_list.append((temp[y],x+1,y+1)) - -if connect_cnt == N-2: - print(0,0) -else: - heapq.heapify(node_list) - result = 0 - answer = [] - while node_list: - pay,x,y = heapq.heappop(node_list) - - if union(x,y): - result += pay - connect_cnt += 1 - answer.append((x,y)) - if connect_cnt == N-2: - break - print(result,len(answer)) - for row in answer: - print(*row) - - -# 다른풀이 -input = __import__('sys').stdin.readline -import heapq -n,m = map(int,input().split()) -e = [] -for i in range(m): - e.append(tuple(map(lambda x:int(x)-1,input().split()))) -adj = [list(map(int,input().split())) for i in range(n)] -for a,b in e: - adj[a][b] = 0 - adj[b][a] = 0 - -cost = [float('inf')]*n -cost[1] = 0 -visit = [False]*n -visit[0] =True -cost[0] = 0 -H = [(0,1,0)] -e = [] -while H: - c,u,p = heapq.heappop(H) - if (not visit[u]) and c==cost[u]: - visit[u] = True - if c: - e.append((u+1,p+1)) - for v in range(n): - if (not visit[v]) and adj[u][v] m: - continue - for nx in range(x - 2, x + 3): - if nx not in v[ny]: - continue - v[ny].remove(nx) - Q.append((nx, ny, d + 1)) -print(-1) \ No newline at end of file diff --git "a/2417\354\240\225\354\210\230\354\240\234\352\263\261\352\267\274.py" "b/2417\354\240\225\354\210\230\354\240\234\352\263\261\352\267\274.py" deleted file mode 100644 index e555a8c..0000000 --- "a/2417\354\240\225\354\210\230\354\240\234\352\263\261\352\267\274.py" +++ /dev/null @@ -1,2 +0,0 @@ -from math import ceil -print(ceil(int(input())**0.5)) \ No newline at end of file diff --git "a/2422\355\225\234\354\234\244\354\240\225\354\235\264 \354\235\264\355\203\210\353\246\254\354\225\204\354\227\220 \352\260\200\354\204\234 \354\225\204\354\235\264\354\212\244\355\201\254\353\246\274\354\235\204 \354\202\254\353\250\271\353\212\224\353\215\260.py" "b/2422\355\225\234\354\234\244\354\240\225\354\235\264 \354\235\264\355\203\210\353\246\254\354\225\204\354\227\220 \352\260\200\354\204\234 \354\225\204\354\235\264\354\212\244\355\201\254\353\246\274\354\235\204 \354\202\254\353\250\271\353\212\224\353\215\260.py" deleted file mode 100644 index 9d55d9c..0000000 --- "a/2422\355\225\234\354\234\244\354\240\225\354\235\264 \354\235\264\355\203\210\353\246\254\354\225\204\354\227\220 \352\260\200\354\204\234 \354\225\204\354\235\264\354\212\244\355\201\254\353\246\274\354\235\204 \354\202\254\353\250\271\353\212\224\353\215\260.py" +++ /dev/null @@ -1,54 +0,0 @@ -import sys -input = sys.stdin.readline - -def dfs(s,cnt): - global ans - if cnt==3: - ans += 1 - return - if cnt > 3: - return - for next in range(s+1,N+1): - if not eat[next] and next not in donot_list: - eat[next] = True - for hate in ice_cream[next]: - donot_list.append(hate) - dfs(next, cnt + 1) - eat[next] = False - for hate in ice_cream[next]: - donot_list.pop() - -N, M = map(int, input().split()) -ice_cream = {i: [] for i in range(1,N+1)} -eat = {i: False for i in range(1,N+1)} -donot_list = [] -ice_cream[0] = [] -for _ in range(M): - a,b = map(int, input().split()) - ice_cream[a] += [b] - ice_cream[b] += [a] -ans = 0 -dfs(0,0) -print(ans) - - - -# 민구님 풀이 3개뽑는 총 조합 - 안되는 조합의 수 -# import sys -# input = sys.stdin.readline - -# N, M = map(int, input().split()) -# worsts = set() -# for _ in range(M): -# a, b = map(int, input().split()) -# worst = 1<<(a-1) -# worst |= 1<<(b-1) -# for i in range(N): -# worsts.add(bin(worst|(1<=(0.9)*f[m]: - l = m + 1 - else: - r = m - c += r-i-1 -print(c) diff --git "a/2435\352\270\260\354\203\201\354\262\255 \354\235\270\355\204\264 \354\213\240\355\230\204\354\210\230.py" "b/2435\352\270\260\354\203\201\354\262\255 \354\235\270\355\204\264 \354\213\240\355\230\204\354\210\230.py" deleted file mode 100644 index e857f11..0000000 --- "a/2435\352\270\260\354\203\201\354\262\255 \354\235\270\355\204\264 \354\213\240\355\230\204\354\210\230.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -arr = list(map(int, input().split())) -left = 0 -prefix_sum = 0 -answer = -float('inf') -for right in range(N): - prefix_sum += arr[right] - while right-left+1 >= M: - answer = max(answer, prefix_sum) - prefix_sum -= arr[left] - left += 1 -print(answer) \ No newline at end of file diff --git "a/2447\353\263\204\354\260\215\352\270\26010.py" "b/2447\353\263\204\354\260\215\352\270\26010.py" index 5ca3c64..44937a6 100644 --- "a/2447\353\263\204\354\260\215\352\270\26010.py" +++ "b/2447\353\263\204\354\260\215\352\270\26010.py" @@ -1,32 +1,32 @@ -# 분할 정복 알고리즘 / 분할, 정복, 합치기. - -# 정복 -# star 배열을 통해 새 matrix를 생성해 반환하는게 목적. -# 반복문에서 3*len(star)로 별이 그려지는 모든 배열을 검사하며 len(star) -# 즉 최초 n의 크기에 따라 빈칸 " "을 추가적으로 삽입하는 방식을 차용한다. -# (n=9일때 3으로 나눠 몫이 1인 index = 1 요소의 가운데 ) -def conquer(n): - matrix=[] - for i in range(3 * len(n)): - if i // len(n) == 1: - matrix.append(n[i % len(n)] + " " * len(n) + n[i % len(n)]) - else: - matrix.append(n[i % len(n)] * 3) - return(list(matrix)) - -# default로 n=3일때 배열과 k값을 미리 줌. -star = ["***","* *","***"] -n = int(input()) -k = 0 - -# 분할(3의k승형으로 분할. 최종적으로 n=3인 모형에 k값만 가지고 간다. -while n != 3: - n = int(n / 3) - k += 1 - -# 조합 -# n=3일때 conquer의 결과를 확장시켜 n=9를 그린다. k승만큼 반복한다. -for i in range(k): - star = conquer(star) -for i in star: +# 분할 정복 알고리즘 / 분할, 정복, 합치기. + +# 정복 +# star 배열을 통해 새 matrix를 생성해 반환하는게 목적. +# 반복문에서 3*len(star)로 별이 그려지는 모든 배열을 검사하며 len(star) +# 즉 최초 n의 크기에 따라 빈칸 " "을 추가적으로 삽입하는 방식을 차용한다. +# (n=9일때 3으로 나눠 몫이 1인 index = 1 요소의 가운데 ) +def conquer(n): + matrix=[] + for i in range(3 * len(n)): + if i // len(n) == 1: + matrix.append(n[i % len(n)] + " " * len(n) + n[i % len(n)]) + else: + matrix.append(n[i % len(n)] * 3) + return(list(matrix)) + +# default로 n=3일때 배열과 k값을 미리 줌. +star = ["***","* *","***"] +n = int(input()) +k = 0 + +# 분할(3의k승형으로 분할. 최종적으로 n=3인 모형에 k값만 가지고 간다. +while n != 3: + n = int(n / 3) + k += 1 + +# 조합 +# n=3일때 conquer의 결과를 확장시켜 n=9를 그린다. k승만큼 반복한다. +for i in range(k): + star = conquer(star) +for i in star: print(i) \ No newline at end of file diff --git "a/2448\353\263\204\354\260\215\352\270\26011.py" "b/2448\353\263\204\354\260\215\352\270\26011.py" index 5462a20..8ed64e7 100644 --- "a/2448\353\263\204\354\260\215\352\270\26011.py" +++ "b/2448\353\263\204\354\260\215\352\270\26011.py" @@ -1,34 +1,34 @@ -import sys -input = sys.stdin.readline - - -# 정복 -def Conquer(shift): - c = len(tri) #최초 3 (즉 세로줄 수) - for i in range(c): #triangle 한줄씩 꺼냄. - tri.append(tri[i] + tri[i]) #tri.append(tri[i] + tri[i]) 3일때그림아래쪽에 바로 2개를 그림. - tri[i] = (" " * shift + tri[i] + " " * shift) #tri[i] = (" "*shift + tri[i] + " " * shift) - #아래쪽에 트리 두개 더한 그림을 그렸다면 원래 있던 그림에도 한줄씩 꺼내 " "공백을 - #삐져나온만큼 더해준다. - #그럼 세로 3줄 -> 6줄 -> 12줄 -> 24줄 각 줄당 두줄씩 K번 더 그려지게된다. -# 입력 -tri = [" * "," * * ","***** "] # 삼각형 밑변끼리 붙지 않도록 오른쪽 한칸 띄어야함. -N = int(input()) - - -# 분할 - -k=0 -N = N//3 -while N != 1 : - N = N//2 - k +=1 -# 조합 -for i in range(k): - Conquer(int(pow(2,i))) #pow는 i승을 의미. 스페이스를 매k마다 2배씩 더 그려야 하기 때문. -for stars in tri: - print(stars) - - - - +import sys +input = sys.stdin.readline + + +# 정복 +def Conquer(shift): + c = len(tri) #최초 3 (즉 세로줄 수) + for i in range(c): #triangle 한줄씩 꺼냄. + tri.append(tri[i] + tri[i]) #tri.append(tri[i] + tri[i]) 3일때그림아래쪽에 바로 2개를 그림. + tri[i] = (" " * shift + tri[i] + " " * shift) #tri[i] = (" "*shift + tri[i] + " " * shift) + #아래쪽에 트리 두개 더한 그림을 그렸다면 원래 있던 그림에도 한줄씩 꺼내 " "공백을 + #삐져나온만큼 더해준다. + #그럼 세로 3줄 -> 6줄 -> 12줄 -> 24줄 각 줄당 두줄씩 K번 더 그려지게된다. +# 입력 +tri = [" * "," * * ","***** "] # 삼각형 밑변끼리 붙지 않도록 오른쪽 한칸 띄어야함. +N = int(input()) + + +# 분할 + +k=0 +N = N//3 +while N != 1 : + N = N//2 + k +=1 +# 조합 +for i in range(k): + Conquer(int(pow(2,i))) #pow는 i승을 의미. 스페이스를 매k마다 2배씩 더 그려야 하기 때문. +for stars in tri: + print(stars) + + + + diff --git "a/2458\355\202\244\354\210\234\354\204\234.py" "b/2458\355\202\244\354\210\234\354\204\234.py" deleted file mode 100644 index 4b2a394..0000000 --- "a/2458\355\202\244\354\210\234\354\204\234.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -knowing_tall = [[0 for _ in range(N)] for _ in range(N)] - -# 플로이드 워셜은 인접행렬을 쓴다. -for i in range(M): - high, low = map(int, input().split()) - knowing_tall[high-1][low-1] =1 - -# 플로이드 워셜의 핵심은 matrix[a][b]랑 matrix[b][a]의 차이를 잘 생각하고 그래프를 설계. -for k in range(N): - for i in range(N): - for j in range(N): - # 내가 아는애랑 키차이 알고 걔가 다른애랑 키차이 알면 나도 걔랑 암. - if knowing_tall[i][k] +knowing_tall[k][j] ==2: - knowing_tall[i][j] =1 - -know_cnt =[0 for _ in range(N)] -for i in range(N): - for j in range(N): - if knowing_tall[i][j] ==1: - know_cnt[i] +=1 - know_cnt[j] +=1 - -print(know_cnt.count(N-1)) \ No newline at end of file diff --git "a/2469 \354\202\254\353\213\244\353\246\254 \355\203\200\352\270\260.py" "b/2469 \354\202\254\353\213\244\353\246\254 \355\203\200\352\270\260.py" deleted file mode 100644 index a89f6d2..0000000 --- "a/2469 \354\202\254\353\213\244\353\246\254 \355\203\200\352\270\260.py" +++ /dev/null @@ -1,39 +0,0 @@ -import sys -input = sys.stdin.readline - -k, n = int(input()), int(input()) -start = [] -for i in range(k): - start.append(chr(ord('A') + i)) -last = list(input().rstrip()) -ladder_game = [list(input().rstrip()) for _ in range(n)] -flag = 0 -for row in range(n): - if flag: break - for col in range(k - 1): - if ladder_game[row][col] == '-': - start[col], start[col + 1] = start[col + 1], start[col] - elif ladder_game[row][col] == '?': - flag = 1 - break - -flag = 0 -for row in range(n - 1, -1, -1): - if flag: break - for col in range(k - 1): - if ladder_game[row][col] == '-': - last[col], last[col + 1] = last[col + 1], last[col] - elif ladder_game[row][col] == '?': - flag = 1 - break - -answer = '' -for i in range(k - 1): - if start[i] == last[i + 1] and start[i + 1] == last[i] and (i==0 or answer[-1] == '*'): - start[i], start[i + 1] = start[i + 1], start[i] - answer += '-' - elif start[i] == last[i]: - answer += '*' -if len(answer) != k - 1: - answer = 'x' * (k-1) -print(answer) \ No newline at end of file diff --git "a/2473 \354\204\270 \354\232\251\354\225\241.py" "b/2473 \354\204\270 \354\232\251\354\225\241.py" deleted file mode 100644 index 77819c6..0000000 --- "a/2473 \354\204\270 \354\232\251\354\225\241.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -liquid = sorted(list(map(int, input().split()))) - -close_zero = float('inf') -selected = [0]*3 - -for start in range(n - 2): - left, right = start + 1, n - 1 - - while left < right: - sum_value = abs(liquid[start] + liquid[left] + liquid[right]) - - if sum_value < close_zero: - selected = [liquid[start], liquid[left], liquid[right]] - close_zero = sum_value - - if sum_value < 0: - left += 1 - elif sum_value > 0: - right -= 1 - else: - print(*selected) - exit() - -print(*selected) \ No newline at end of file diff --git "a/2475\352\262\200\354\246\235\354\210\230.py" "b/2475\352\262\200\354\246\235\354\210\230.py" deleted file mode 100644 index 058c075..0000000 --- "a/2475\352\262\200\354\246\235\354\210\230.py" +++ /dev/null @@ -1,2 +0,0 @@ - -print(sum(list(map(lambda x: int(x)**2, input().split()))) % 10) diff --git "a/2477\354\260\270\354\231\270\353\260\255.py" "b/2477\354\260\270\354\231\270\353\260\255.py" deleted file mode 100644 index b5935d9..0000000 --- "a/2477\354\260\270\354\231\270\353\260\255.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -melon = int(input()) # 참외 개수 K -values = [input().split() for _ in range(6)] # 나머지 2~7 line의 6 줄을 입력 받는다. -directions = [int(v[0]) for v in values] # 방향을 뽑아내서 저장한다. -lengths = [int(v[1]) for v in values] # 길이를 뽑아내서 저장한다. -max_lengths, box_lengths = [], [] - -for i in range(1, 5): - if directions.count(i) == 1: # direction이 한번만 존재한다 == 큰 박스의 변 - max_lengths.append(lengths[directions.index(i)]) # 큰박스의 변 길이 저장 - temp = directions.index(i) + 3 # 큰 박스 + 3 == 작은 박스의 변 - if temp >= 6: - temp -= 6 # cycle을 위해 6 이상일 경우 -6 - box_lengths.append(lengths[temp]) - -area = max_lengths[0] * max_lengths[1] - box_lengths[0] * box_lengths[1] -print(melon * area) \ No newline at end of file diff --git "a/2491\354\210\230\354\227\264.py" "b/2491\354\210\230\354\227\264.py" deleted file mode 100644 index 81fdc3f..0000000 --- "a/2491\354\210\230\354\227\264.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -def count_LIS(arr): - cnt = 1 - max_cnt = 0 - for i in range(1,N): - if arr[i-1] <= arr[i]: - cnt += 1 - else: - max_cnt = max(cnt,max_cnt) - cnt = 1 - max_cnt = max(cnt,max_cnt) - return max_cnt - -N = int(input()) -if N==1: - print(1) - exit() -arr = list(map(int, input().split())) -length1 = count_LIS(arr) -arr.reverse() -length2 = count_LIS(arr) -print(max(length1,length2)) \ No newline at end of file diff --git "a/2504\352\264\204\355\230\270\354\235\230\352\260\222.py" "b/2504\352\264\204\355\230\270\354\235\230\352\260\222.py" deleted file mode 100644 index c65e9db..0000000 --- "a/2504\352\264\204\355\230\270\354\235\230\352\260\222.py" +++ /dev/null @@ -1,61 +0,0 @@ -import sys - -str = sys.stdin.readline().rstrip() - -stack = list() - -for i in str: - - if i == ")": - temp = 0 - - while stack: - top = stack.pop() - if top == "(": - if temp == 0: - stack.append(2) - else: - stack.append(2 * temp) - break - elif top == "[": - print("0") - exit(0) - else: - if temp == 0: - temp = int(top) - else: - temp = temp + int(top) - - elif i == "]": - temp = 0 - - while stack: - top = stack.pop() - if top == "[": - if temp == 0: - stack.append(3) - else: - stack.append(3 * temp) - break - elif top == "(": - print("0") - exit(0) - else: - if temp == 0: - temp = int(top) - else: - temp = temp + int(top) - - else: - stack.append(i) - -result = 0 - -for i in stack: - if i == "(" or i == "[": - print(0) - exit(0) - else: - result += i - -print(result) \ No newline at end of file diff --git "a/2527\354\247\201\354\202\254\352\260\201\355\230\225.py" "b/2527\354\247\201\354\202\254\352\260\201\355\230\225.py" deleted file mode 100644 index 4243ded..0000000 --- "a/2527\354\247\201\354\202\254\352\260\201\355\230\225.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(4): - x1,y1,p1,q1,x2,y2,p2,q2 = map(int, input().split()) - if p1 < x2 or p2 < x1 or y1 > q2 or q1 < y2: - print('d') - continue - elif x1==p2 or x2==p1: - if q1==y2 or q2==y1: - print('c') - continue - else: - print('b') - continue - elif q1==y2 or q2==y1: - print('b') - continue - else: - print('a') - continue \ No newline at end of file diff --git "a/2529\353\266\200\353\223\261\355\230\270.py" "b/2529\353\266\200\353\223\261\355\230\270.py" index acf953a..96983e7 100644 --- "a/2529\353\266\200\353\223\261\355\230\270.py" +++ "b/2529\353\266\200\353\223\261\355\230\270.py" @@ -1,29 +1,29 @@ -n = int(input()) -inequality = input().split() -check = [False] * 10 -max, min = "", "" - -def possible(i, j, k): - if k == '<': - return i < j - if k == '>': - return i > j - return True - -def DFS(depth, s): - global max, min - if depth == n + 1: - if not len(min): - min = s - else: - max = s - return - for i in range(10): - if not check[i]: - if depth == 0 or possible(s[-1], str(i), inequality[depth - 1]): - check[i] = True - DFS(depth + 1, s + str(i)) - check[i] = False -DFS(0, "") -print(max) +n = int(input()) +inequality = input().split() +check = [False] * 10 +max, min = "", "" + +def possible(i, j, k): + if k == '<': + return i < j + if k == '>': + return i > j + return True + +def DFS(depth, seqs): + global max, min + if depth == n + 1: + if not len(min): + min = seqs + else: + max = seqs + return + for i in range(10): + if not check[i]: + if depth == 0 or possible(seqs[-1], str(i), inequality[depth - 1]): + check[i] = True + DFS(depth + 1, seqs + str(i)) + check[i] = False +DFS(0, "") +print(max) print(min) \ No newline at end of file diff --git "a/2533\354\202\254\355\232\214\353\247\235\354\204\234\353\271\204\354\212\244(SNS).py" "b/2533\354\202\254\355\232\214\353\247\235\354\204\234\353\271\204\354\212\244(SNS).py" deleted file mode 100644 index e0af4ba..0000000 --- "a/2533\354\202\254\355\232\214\353\247\235\354\204\234\353\271\204\354\212\244(SNS).py" +++ /dev/null @@ -1,77 +0,0 @@ -from sys import setrecursionlimit, stdin -setrecursionlimit(1000000) -input = stdin.readline # 입력 시간 안줄여주면 시간초과 난다 -n = int(input().rstrip()) -tree = [[] for _ in range(n+1)] # 2차원 인접 리스트 -for _ in range(n-1): - n1, n2 = [int(x) for x in input().rstrip().split()] - tree[n1].append(n2) - tree[n2].append(n1) # 여기서 한쪽 노드만 인접하게 설정해줘서 계속 오답났다. - -# DFS -# 1. 단말 노드이면 연결된 노드는 얼리어답터 -# 2. 연결된 노드가 모두 얼리어답터 아니면 무조건 얼리어답터 -early = set() -visited = set() -def dfs(n): - global tree, early, visited - visited.add(n) - if len(tree[n]) <= 1: # 단말노드이다 - return True - for i in tree[n]: - if not i in visited: # 양방향 그래프이므로 무한루프에 빠지지 않게끔 - if dfs(i): - early.add(n) - elif not i in early: # 연결된 노드가 얼리어답터 아니면 - early.add(n) - return False # 단말노드 아니다 - -# 단말노드에서 시작하지 않게끔 -for i, start in enumerate(tree): - if len(start) > 1: - dfs(i) - break -# 모두 단말노드인 경우 -if n==2: - print(1) -else: - print(len(early)) - - - - -# tree dp -import sys -input = sys.stdin.readline -from collections import deque -N = int(input()) -graph = [[] for _ in range(N+1)] -for i_ in range(N-1): - a,b= map(int,input().split()) - graph[a].append(b) - graph[b].append(a) - - -dp = [[0]*2 for _ in range(N+1)] -visited = [0]*(N+1) -dp[1][0] += 1 -visited[1] = 1 -depth = [0] * (N+1) -stack = [] -stack.append(1) -while stack: - cnt = 0 - top = stack[-1] - for elem in graph[top]: - if visited[elem] == 0: - visited[elem] = 1 - dp[elem][0] = 1 - depth[elem] = depth[top]+ 1 - stack.append(elem) - cnt += 1 - if cnt == 0: - stack.pop() - for elem in graph[top]: - if depth[elem] < depth[top]: - dp[elem][0] += min(dp[top][0],dp[top][1]) - dp[elem][1] += dp[top][0] diff --git "a/2559\354\210\230\354\227\264.py" "b/2559\354\210\230\354\227\264.py" deleted file mode 100644 index c87a3c8..0000000 --- "a/2559\354\210\230\354\227\264.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - - -N, K = map(int, input().split()) -arr = list(map(int, input().split())) - -left = 0 -sum_arr = 0 -max_sum = -float('inf') -for right in range(N): - sum_arr += arr[right] - if right-left+1 == K: - max_sum = max(max_sum,sum_arr) - sum_arr -= arr[left] - left += 1 -print(max_sum) diff --git "a/2563 \354\203\211\354\242\205\354\235\264.py" "b/2563 \354\203\211\354\242\205\354\235\264.py" deleted file mode 100644 index 5b168ad..0000000 --- "a/2563 \354\203\211\354\242\205\354\235\264.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -board = [[0]*101 for _ in range(101)] -for _ in range(N): - x,y = map(int, input().split()) - for i in range(x,x+10): - for j in range(y,y+10): - board[i][j] = 1 -cnt = 0 -for i in range(1,101): - for j in range(1,101): - if board[i][j]: - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/2564\352\262\275\353\271\204\354\233\220.py" "b/2564\352\262\275\353\271\204\354\233\220.py" deleted file mode 100644 index 3e9112c..0000000 --- "a/2564\352\262\275\353\271\204\354\233\220.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -K = int(input()) -store = [] -for _ in range(K): - store_dir, dist = map(int, input().split()) - if store_dir==1: - y = M - x = dist - elif store_dir==2: - y=0 - x = dist - elif store_dir==3: - x=0 - y=M-dist - else: - x=N - y = M-dist - store.append([x,y]) -dongguen_dir, dist = map(int, input().split()) -if dongguen_dir==1: - y = M - x = dist -elif dongguen_dir==2: - y=0 - x = dist -elif dongguen_dir==3: - x=0 - y=M-dist -else: - x=N - y = M-dist -answer = 0 -for store_x,store_y in store: - if not abs(store_x-x) == N and not abs(store_y-y)==M: - answer += abs(store_x-x) + abs(store_y-y) - else: - answer += min(x+y+store_x+store_y,2*N+2*M-(x+y+store_x+store_y)) -print(answer) \ No newline at end of file diff --git "a/2571\354\203\211\354\242\205\354\235\2643.py" "b/2571\354\203\211\354\242\205\354\235\2643.py" deleted file mode 100644 index a7854cd..0000000 --- "a/2571\354\203\211\354\242\205\354\235\2643.py" +++ /dev/null @@ -1,80 +0,0 @@ -import sys -input = sys.stdin.readline - -def find_rectangle(x,y): - - max_size = 100 - for i in range(100): - if x+i >100: - break - for j in range(100): - if y + j > 100: - break - max_size = max(max_size,calculate_area(x,y,x+i,y+j)) - return max_size - -def calculate_area(x,y,h,w): - cnt = 0 - for i in range(x,h+1): - for j in range(y,w+1): - if not paper[i][j]: - return 0 - else: - cnt += 1 - return cnt - - - -n = int(input()) -paper = [[0]*101 for _ in range(101)] -for _ in range(n): - x, y = map(int, input().split()) - for i in range(x,x+10): - for j in range(y,y+10): - paper[i][j] = 1 - -max_size = 100 -for i in range(100): - for j in range(100): - if paper[i][j]==1: - max_size = max(max_size,find_rectangle(i,j)) -print(max_size) - - - - -# 다른 답. -import sys -input = sys.stdin.readline - - -paper = [[0]*102 for _ in range(100)] -for i in range(int(input())): - x, y = map(int,input().split()) - for i in range(x+1,x+11): - for j in range(y,y+10): - paper[j][i]=1 - -# 0행을 기준으로 높이값을 저장.(1이 이어지는 길이) -for i in range(1,100): - for j in range(1,102): - if paper[i][j]: - paper[i][j]=paper[i-1][j]+1 - -max_size = 0 -# 행 순회 -for row in range(100): - paper_row = paper[row] - # S는 계산하지 않은 열을 넣을 이전 열 idx stack 최초 값 0은 0열의 높이값은 모두 0이기 때문에 기준으로 삼기 위해. - pre_idx_stack = [0] - # 열 순회 - for cur_col in range(1,102): - # S는 마지막으로 살펴본 열의 idx 현재 살펴보는열의 높이가 이전 열의 높이보다 작으면 같아질떄까지 s빼면서 직사각형 비교해줌. - # 높이가 작아진다는 말은 곧 위에 빈칸이 있다는 뜻으로 빈칸이 반영 되기 이전에 높은 값에 대해 최대높이를 갱신시킨 후 넘어가겠다는 뜻. - while pre_idx_stack and paper_row[pre_idx_stack[-1]] > paper_row[cur_col]: - h = paper_row[pre_idx_stack[-1]] - pre_idx_stack.pop() - # cur_col-1는 현재 idx 바로 이전값 pre_idx_stack[-1]은 h높이를 가지는idx - max_size = max(max_size, (cur_col-pre_idx_stack[-1]-1)*h) - pre_idx_stack.append(cur_col) -print(max_size) \ No newline at end of file diff --git "a/2573 \353\271\231\354\202\260.py" "b/2573 \353\271\231\354\202\260.py" deleted file mode 100644 index 1e837b0..0000000 --- "a/2573 \353\271\231\354\202\260.py" +++ /dev/null @@ -1,8 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -mountain = [list(map(int, input().split())) for __ in range(N)] -# 녹이고 - -# 두덩어린지 check \ No newline at end of file diff --git "a/2578\353\271\231\352\263\240.py" "b/2578\353\271\231\352\263\240.py" deleted file mode 100644 index ea71944..0000000 --- "a/2578\353\271\231\352\263\240.py" +++ /dev/null @@ -1,59 +0,0 @@ -import sys -input = sys.stdin.readline - -def check(x,y): - global cnt - if not row_check[x] and not sum(bingo[x]): - row_check[x] = True - cnt += 1 - if not col_check[y]: - for i in range(5): - if bingo[i][y]: - break - else: - col_check[y] = True - cnt += 1 - if x==y and not diagonal_check[0]: - for i in range(5): - if bingo[i][i]: - break - else: - diagonal_check[0] = True - cnt += 1 - if x+y==4 and not diagonal_check[1]: - for i in range(5): - if bingo[i][4-i]: - break - else: - diagonal_check[1] = True - cnt += 1 - if cnt >= 3: - return True - return False - - - -def call_num(n): - for i in range(5): - for j in range(5): - if bingo[i][j]==n: - bingo[i][j]=0 - if check(i,j): - return True - return False - - -bingo = [list(map(int, input().split())) for _ in range(5)] -call = [list(map(int, input().split())) for _ in range(5)] -row_check = {i: False for i in range(5)} -col_check = {i: False for i in range(5)} -diagonal_check = {i: False for i in range(2)} -cnt = 0 -for i in range(5): - for j in range(5): - if call_num(call[i][j]): - answer = i*5+j+1 - print(answer) - exit() - - \ No newline at end of file diff --git "a/2581 \354\206\214\354\210\230.py" "b/2581 \354\206\214\354\210\230.py" deleted file mode 100644 index a6ddb43..0000000 --- "a/2581 \354\206\214\354\210\230.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - - -def che(): - nums = [True]*(N+1) - nums[0]=nums[1]=False - primes = [] - for i in range(2,int(N**0.5)+1): - if nums[i]: - for j in range(i+i, N+1, i): - nums[j] = False - return [i for i in range(M,N+1) if nums[i]] - -M = int(input()) -N = int(input()) -arr = che() -if arr: - print(sum(arr)) - print(arr[0]) -else: - print(-1) diff --git "a/2605 \354\244\204\354\204\270\354\232\260\352\270\260.py" "b/2605 \354\244\204\354\204\270\354\232\260\352\270\260.py" deleted file mode 100644 index 23d4014..0000000 --- "a/2605 \354\244\204\354\204\270\354\232\260\352\270\260.py" +++ /dev/null @@ -1,9 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = list(map(int,input().split())) -answer = [] -for i in range(1,N+1): - answer.insert(arr[i-1],i) -print(*answer[::-1]) \ No newline at end of file diff --git "a/2606\353\260\224\354\235\264\353\237\254\354\212\244.py" "b/2606\353\260\224\354\235\264\353\237\254\354\212\244.py" deleted file mode 100644 index 924e891..0000000 --- "a/2606\353\260\224\354\235\264\353\237\254\354\212\244.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline - -# disjoint-set 서로소집합 union-find알고리즘. -# union은 원소 a,b가 속해있는 서로소 집합을 대푯값으로 묶어 표시한다. -def union(a,b): - a=find(a) - b=find(b) - - if level[a] >= level[b]: - parent[b] = a - level[a] += 1 - else: - parent[a] = b - level[b] += 1 - -# find는 각 집합의 대푯값(tree로 치면 root node)를 추적하는 함수. -def find(x): - if x==parent[x]: - return x - parent[x] = find(parent[x]) - return parent[x] - -N = int(input()) -M = int(input()) -parent = {i:i for i in range(1,N+1)} -level = {i:1 for i in range(1,N+1)} -# a,b가 속해있는 집합이 다르면?(root node가 다르면?) -# union연산을 통해 집합을 합친다. -for _ in range(M): - a,b = map(int,input().split()) - if find(a) != find(b): - union(a,b) - -# 1번 노드와 연결되어있는 컴퓨터의 갯수를 세준다. -cnt=0 -for computer in range(2,N+1): - if find(1)==find(computer): - cnt+=1 - -print(cnt) \ No newline at end of file diff --git "a/2609\354\265\234\352\263\265\354\225\275\352\263\265\353\260\260.py" "b/2609\354\265\234\352\263\265\354\225\275\352\263\265\353\260\260.py" index f294a9e..9a714fe 100644 --- "a/2609\354\265\234\352\263\265\354\225\275\352\263\265\353\260\260.py" +++ "b/2609\354\265\234\352\263\265\354\225\275\352\263\265\353\260\260.py" @@ -1,11 +1,16 @@ -import sys -A, B = map(int, sys.stdin.readline().split()) -a, b = A, B -while b != 0: - a = a % b - a, b = b, a - -# gcd -print(a) -#lcm -print(A*B//a) +import sys + +T = int(input()) +for test in range(T): + A, B = map(int, sys.stdin.readline().split()) + a, b = A, B + + + while b != 0: + a = a % b + a, b = b, a + + + #lcm + print(a) +/ \ No newline at end of file diff --git "a/2613 \354\210\253\354\236\220\352\265\254\354\212\254.py" "b/2613 \354\210\253\354\236\220\352\265\254\354\212\254.py" deleted file mode 100644 index 2300049..0000000 --- "a/2613 \354\210\253\354\236\220\352\265\254\354\212\254.py" +++ /dev/null @@ -1,61 +0,0 @@ -import sys -input= sys.stdin.readline - -# 계속 sum에 더해가면서 진행하다가 미리 정해두었던 mid기준을 충족하면 -# 그 지점 i 에서 다시 less_than_target 시작하고 group count 1부터 다시 시작. 총 M개로 나뉠때까지 진행. -# 다해서 M개 이상 되면 최솟값 탐색을 위해 왼쪽 탐색, M개 안되면 mid늘려야하므로 오른쪽 탐색. -def get_Mgroup(target_sum): - sum_each_group=0 - group_cnt = 1 - for i in range(N): - sum_each_group += ball_lists[i] - if sum_each_group > target_sum: - sum_each_group = ball_lists[i] - group_cnt+=1 - if group_cnt <=M: - return True - else: - return False - -def cut_each_points(target_sum,M,N): - print(target_sum) - less_than_target=0 - ball_cnt = 0 - for i in range(N): - less_than_target += ball_lists[i] - if less_than_target > target_sum: - less_than_target = ball_lists[i] - M -=1 - print(ball_cnt, end=" ") - ball_cnt=0 - ball_cnt+=1 - - if N-i ==M: - break - - while M: - print(ball_cnt, end=" ") - ball_cnt=1 - M-=1 - - -N,M = map(int,input().split()) -ball_lists = list(map(int,input().split())) - -# 이분 탐색. 탐색 범위는 원소의 sum영역이 될 수 있는 모든 값. -# 좌: 원소중 최대값, 우: 총합값으로 이분 탐색을 진행 target_sum을 찾음. -left_sum_limit = max(ball_lists) -right_sum_limit = sum(ball_lists) - -# 좌 우 탐색할 영역 선택. 선택 갯수를 만족하면 좀 더 작게 하기위해 좌측 탐색 -# M을 만족하지 못하면 mid를 크게잡아 만족시켜야 하기 때문에 우측탐색. -# 계속 반으로 나눠가며 영역 탐색. -# left가 right를 만나는 영역(최적 mid값을 찾으면 종료.) -while left_sum_limit <= right_sum_limit: - target_sum = (left_sum_limit+right_sum_limit)//2 - if get_Mgroup(target_sum): - right_sum_limit = target_sum -1 - else: - left_sum_limit = target_sum+1 - -cut_each_points(left_sum_limit,M,N) \ No newline at end of file diff --git "a/2613\354\210\253\354\236\220\352\265\254\354\212\254_\353\251\224\353\252\250\353\246\254\354\213\234\352\260\204\354\264\210\352\263\274\354\223\260.py" "b/2613\354\210\253\354\236\220\352\265\254\354\212\254_\353\251\224\353\252\250\353\246\254\354\213\234\352\260\204\354\264\210\352\263\274\354\223\260.py" deleted file mode 100644 index 4fa2702..0000000 --- "a/2613\354\210\253\354\236\220\352\265\254\354\212\254_\353\251\224\353\252\250\353\246\254\354\213\234\352\260\204\354\264\210\352\263\274\354\223\260.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input= sys.stdin.readline -from itertools import combinations - -# N-1개의 사이에서 M-1개의 작대기를 뽑는 조합. -# 각 max값중 최댓값과 slice한 작대기 위치 패킹해 저장. -# 저장된 max값 정렬 후 맨앞에있는 배열 출력. - -N,M = map(int,input().split()) -ball_lists = list(map(int,input().split())) - -maxes = float('inf') -for comb in combinations(range(1,N),M-1): - last_cut_point = 0 - max_sum = 0 - for cut_point in comb: - if max_sum < sum(ball_lists[last_cut_point:cut_point]): - max_sum = sum(ball_lists[last_cut_point:cut_point]) - last_cut_point = cut_point - if max_sum < sum(ball_lists[last_cut_point:]): - max_sum = sum(ball_lists[last_cut_point:]) - if maxes > max_sum: - maxes = max_sum - max_comb = comb - -print(maxes) -last_cut_p = 0 -for cut_p in max_comb: - print(cut_p-last_cut_p, end=" ") - last_cut_p = cut_p -print(N-last_cut_p) diff --git "a/2623\354\235\214\354\225\205\355\224\204\353\241\234\352\267\270\353\236\250.py" "b/2623\354\235\214\354\225\205\355\224\204\353\241\234\352\267\270\353\236\250.py" deleted file mode 100644 index 772afee..0000000 --- "a/2623\354\235\214\354\225\205\355\224\204\353\241\234\352\267\270\353\236\250.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -from collections import defaultdict,deque -input = sys.stdin.readline - -def topological_sorting(): - queue = deque() - for i in range(1, N+1): - if level[i] == 0: - queue.append(i) - while queue: - cur_order = queue.popleft() - final_order.append(cur_order) - for post_order in post_order_table[cur_order]: - level[post_order] -= 1 - if level[post_order] == 0: - queue.append(post_order) - -N, M = map(int, input().split()) -level = [0 for _ in range(N+1)] -post_order_table = defaultdict(list) -final_order = [] - -for _ in range(M): - order = list(map(int, input().split())) - for i in range(1,len(order) - 1): - post_order_table[order[i]] += [order[i+1]] - level[order[i+1]] += 1 - -topological_sorting() - -if len(final_order) != N: - print(0) - exit() - -for singer in final_order: - print(singer) - diff --git "a/2628\354\242\205\354\235\264\354\236\220\353\245\264\352\270\260.py" "b/2628\354\242\205\354\235\264\354\236\220\353\245\264\352\270\260.py" deleted file mode 100644 index dfeecd7..0000000 --- "a/2628\354\242\205\354\235\264\354\236\220\353\245\264\352\270\260.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -cut_row = [0,M] -cut_col = [0,N] -for _ in range(int(input())): - a,b = map(int,input().split()) - if not a: - cut_row.append(b) - else: - cut_col.append(b) -cut_row.sort() -cut_col.sort() - -len_row = [] -len_col = [] -for i in range(1,len(cut_row)): - len_row.append(cut_row[i] - cut_row[i-1]) -for i in range(1,len(cut_col)): - len_col.append(cut_col[i] - cut_col[i-1]) -if not len_row: - len_row.append(M) -if not len_col: - len_col.append(N) -max_s = 0 -for row in len_row: - for col in len_col: - max_s = max(max_s,row*col) -print(max_s) \ No newline at end of file diff --git "a/2629\354\226\221\355\214\224\354\240\200\354\232\270.py" "b/2629\354\226\221\355\214\224\354\240\200\354\232\270.py" deleted file mode 100644 index 6b885f9..0000000 --- "a/2629\354\226\221\355\214\224\354\240\200\354\232\270.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -input = sys.stdin.readline - -chu_N = int(input()) -chu_list = list(map(int,input().split())) - -glass_ball_N = int(input()) -ball_list = list(map(int,input().split())) - -# 추 무게 합이 되는 집합 -dp_chu = {i:False for i in range(sum(chu_list)+1)} -# initialize -dp_chu[0] = True - -# 추를 더하는 경우만 체크 -for chu in chu_list: - for sum_chu, exist in list(dp_chu.items()): - if exist: - if not dp_chu[sum_chu+chu]: - dp_chu[sum_chu+chu] = True - -# 추를 빼는 경우를 체크 -# 하나의 추를 더하고 빼는 경우(양쪽에 모두 올려놓는 경우)도 체크하게 되나 결과집합에서는 동일하다. -for chu in chu_list: - for sum_chu, exist in list(dp_chu.items()): - if exist: - if sum_chu-chu >=0 and not dp_chu[sum_chu-chu]: - dp_chu[sum_chu-chu] = True - -# 유리구슬의 한계무게가 추의 한계무게보다 훨씬 크므로 그경우를 배제하면 나머지는 hash table에서 매칭하면 된다. -for ball in ball_list: - if ball > sum(chu_list): - print("N", end= " ") - continue - if dp_chu[ball]: - print("Y", end=" ") - else: - print("N", end=" ") -else: - print() \ No newline at end of file diff --git "a/2630\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260.py" "b/2630\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index bd5599e..0000000 --- "a/2630\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - -def check(x,y,size): - color = matrix[x][y] - for i in range(x,x+size): - for j in range(y,y+size): - if not color==matrix[i][j]: - return False - if color==1: - answer[1] += 1 - else: - answer[0] += 1 - return True - - -def divide_paper(start_x,start_y,length): - if not check(start_x,start_y,length//2): - divide_paper(start_x,start_y,length//2) - if not check(start_x+length//2,start_y,length//2): - divide_paper(start_x+length//2,start_y,length//2) - if not check(start_x,start_y+length//2,length//2): - divide_paper(start_x,start_y+length//2,length//2) - if not check(start_x+length//2,start_y+length//2,length//2): - divide_paper(start_x+length//2,start_y+length//2,length//2) - - -N = int(input()) -matrix = [list(map(int, input().split())) for _ in range(N)] -answer = [0,0] -if not check(0,0,N): - divide_paper(0,0,N) -for color in answer: - print(color) \ No newline at end of file diff --git "a/2635 \354\210\230 \354\235\264\354\226\264\352\260\200\352\270\260.py" "b/2635 \354\210\230 \354\235\264\354\226\264\352\260\200\352\270\260.py" deleted file mode 100644 index 250e64a..0000000 --- "a/2635 \354\210\230 \354\235\264\354\226\264\352\260\200\352\270\260.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -if N==1: - print(4) - print(1,1,0,1) - exit() -max_len = 0 -for i in range(1,N): - dp = [N,i] - for j in range(2,N): - tmp = dp[j-2] - dp[j-1] - if tmp < 0: - if len(dp) > max_len: - max_len = len(dp) - max_arr = dp - break - dp.append(tmp) -print(max_len) -print(*max_arr) \ No newline at end of file diff --git "a/2637\354\236\245\353\202\234\352\260\220\354\241\260\353\246\275.py" "b/2637\354\236\245\353\202\234\352\260\220\354\241\260\353\246\275.py" deleted file mode 100644 index 63621b5..0000000 --- "a/2637\354\236\245\353\202\234\352\260\220\354\241\260\353\246\275.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict,deque - -def BFS(): - global dp_items - dp_items = [[0]*(N+1) for _ in range(N+1)] # level 0 부터 N번 부품까지 각 필요부품 갯수를 상향으로 쌓는다. - queue = deque() - for i in range(1,N+1): # inititalize - if level[i] ==0: - queue.append(i) - while queue: - cur_item = queue.popleft() - for next,next_items in subs[cur_item]: - if sum(dp_items[cur_item])==0: #level=0인 애들은 dp[next]에 next조합에필요한 갯수만큼 적어준다. - dp_items[next][cur_item] +=next_items - else: #전 부품 있는 애들은 전꺼 조합에 필요한 갯수*필요한 전꺼 갯수 - for i in range(1,N+1): - dp_items[next][i] += dp_items[cur_item][i] * next_items - - level[next] -=1 #계산 끝나면 level down으로 하층으로 보낸다. - if level[next]==0: #더 이상 받는 부품이 없으면 queue에 넣어 그 윗층계산을 하게한다. - queue.append(next) - -N = int(input()) -M = int(input()) - -subs = defaultdict(list) -level = [0]*(N+1) -for _ in range(M): # 아래쪽 부터 올라갈 것이므로 화살표 방향도 Y->X로 가게끔 설계 - X,Y,K = map(int,input().split()) - subs[Y].append((X,K)) - level[X] +=1 - -BFS() - -for i in range(1,N): #N번 부품이 각각 필요한 재료를 index와 tuple로 packaging해 출력한다. - cnt = dp_items[N][i] - if cnt: - print(i,cnt) \ No newline at end of file diff --git "a/2637\354\236\245\353\202\234\352\260\220\354\241\260\353\246\275_\353\213\244\353\245\270\354\202\254\353\236\214\352\272\274.py" "b/2637\354\236\245\353\202\234\352\260\220\354\241\260\353\246\275_\353\213\244\353\245\270\354\202\254\353\236\214\352\272\274.py" deleted file mode 100644 index 8781868..0000000 --- "a/2637\354\236\245\353\202\234\352\260\220\354\241\260\353\246\275_\353\213\244\353\245\270\354\202\254\353\236\214\352\272\274.py" +++ /dev/null @@ -1,35 +0,0 @@ -def get_parts(part): - # part 를 만들기 위해 필요한 기본 부품 dictionary 반환 - if chk[part]: - return need[part] - target_cnt = {} - for need_item, need_cnt in need[part].items(): # need_item: part을 만들기 위해 필요한 부품 / need_cnt: 필요한 부품 갯수 - if len(need[need_item]) == 0: # 기본 부품일 경우 (i를 만드는데에 필요한 부품이 없다) - if need_item in target_cnt: - target_cnt[need_item] += need_cnt - else: - target_cnt[need_item] = need_cnt - continue - for k, v in get_parts(need_item).items(): # get(need_item) : need_item를 만드는데에 필요한 부품들 - if k in target_cnt: - target_cnt[k] += v * need_cnt - else: - target_cnt[k] = v * need_cnt - need[part] = target_cnt - chk[part] = True - return target_cnt - - -N = int(input()) -M = int(input()) -need = {i: {} for i in range(1, N + 1)} # need[a][b] = c : a를 만드는데에 b가 c개 필요하다 -chk = {i: True for i in range(1, N + 1)} # chk[a] = True -for _ in range(M): - X, Y, K = map(int, input().split()) - need[X][Y] = K - chk[X] = False - -ans = get_parts(N) -for i in range(1, N): - if i in ans: - print(i, ans[i]) diff --git "a/2644\354\264\214\354\210\230\352\263\204\354\202\260.py" "b/2644\354\264\214\354\210\230\352\263\204\354\202\260.py" deleted file mode 100644 index a9c3ffc..0000000 --- "a/2644\354\264\214\354\210\230\352\263\204\354\202\260.py" +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(start,target): - visited = {i: 0 for i in range(n+1)} - visited[start] = 1 - q = deque() - q.append(start) - while q: - cur_node = q.popleft() - if cur_node==target: - return visited[cur_node] -1 - for next_node in graph[cur_node]: - if not visited[next_node]: - visited[next_node] = visited[cur_node] + 1 - q.append(next_node) - return -1 - - -n = int(input()) -a, b = map(int, input().split()) -m = int(input()) -graph = {i: [] for i in range(1,n+1)} -for _ in range(m): - x, y = map(int, input().split()) - graph[y] += [x] - graph[x] += [y] - -print(bfs(a,b)) - diff --git "a/2665 \353\257\270\353\241\234\353\247\214\353\223\244\352\270\260.py" "b/2665 \353\257\270\353\241\234\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 05a794e..0000000 --- "a/2665 \353\257\270\353\241\234\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappush, heappop - - -def dijkstra(): - heap = [] - heappush(heap, [0, 0, 0]) - visited[0][0] = 1 - while heap: - cost, x, y = heappop(heap) - if x == n - 1 and y == n - 1: - return cost - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny]: - visited[nx][ny] = True - if maze[nx][ny] == 0: - heappush(heap, [cost + 1, nx, ny]) - else: - heappush(heap, [cost, nx, ny]) - - -n = int(input()) -maze = [list(map(int, input().rstrip())) for _ in range(n)] -visited = [[0] * n for _ in range(n)] - -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] - -print(dijkstra()) diff --git "a/2667\353\213\250\354\247\200\353\262\210\355\230\270\353\266\231\354\235\264\352\270\260.py" "b/2667\353\213\250\354\247\200\353\262\210\355\230\270\353\266\231\354\235\264\352\270\260.py" index a5ae3f0..39972e7 100644 --- "a/2667\353\213\250\354\247\200\353\262\210\355\230\270\353\266\231\354\235\264\352\270\260.py" +++ "b/2667\353\213\250\354\247\200\353\262\210\355\230\270\353\266\231\354\235\264\352\270\260.py" @@ -1,39 +1,39 @@ -import sys -input = sys.stdin.readline -from collections import deque - -N = int(input()) -matrix = [list(map(int,list(map(str,input().rstrip())))) for _ in range(N)] -queue = deque() -cnt = 1 -dx = [1,-1,0,0] -dy = [0,0,1,-1] -ans = [] - -def BFS(x,y,cnt): - matrix[x][y] = cnt - count = 1 - queue.append([x,y]) - while queue: - x,y = queue.popleft() - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx extend써야 배열 +연산처럼 들어감 - seqs = [] - for i in range(M//10+1): - seqs.extend(list(map(int,input().split()))) - - # 출력하는 갯수 : 홀수의 갯수. - print(M//2+1) - - # M=1일때 index에러 대비해서 따로 빼줌. - print(seqs[0], end=" ") - - # count이용 출력 숫자 10개로 조절. 줄바꿈. - # for else문으로 반복문 끝났을 때 한칸띄어서 다음 입력이 깔끔하게 제어. - if M !=1: - cnt=1 - for i in range(2,M,2): - print(sorted(seqs[:i+1])[(i+1)//2], end=" ") - cnt+=1 - if cnt==10: - print() - cnt=0 - else: +import sys +input = sys.stdin.readline + + + +for test in range(int(input())): + M = int(input()) + + # 여러줄 입력을 한 리스트에 -> extend써야 배열 +연산처럼 들어감 + seqs = [] + for i in range(M//10+1): + seqs.extend(list(map(int,input().split()))) + + # 출력하는 갯수 : 홀수의 갯수. + print(M//2+1) + + # M=1일때 index에러 대비해서 따로 빼줌. + print(seqs[0], end=" ") + + # count이용 출력 숫자 10개로 조절. 줄바꿈. + # for else문으로 반복문 끝났을 때 한칸띄어서 다음 입력이 깔끔하게 제어. + if M !=1: + cnt=1 + for i in range(2,M,2): + print(sorted(seqs[:i+1])[(i+1)//2], end=" ") + cnt+=1 + if cnt==10: + print() + cnt=0 + else: print() \ No newline at end of file diff --git "a/2729 \354\235\264\354\247\204\354\210\230 \353\215\247\354\205\210.py" "b/2729 \354\235\264\354\247\204\354\210\230 \353\215\247\354\205\210.py" deleted file mode 100644 index 1a3c6db..0000000 --- "a/2729 \354\235\264\354\247\204\354\210\230 \353\215\247\354\205\210.py" +++ /dev/null @@ -1,6 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - a, b = map(lambda x: int(x, 2), input().split()) - print(bin(a + b)[2:]) diff --git "a/2743\353\213\250\354\226\264\352\270\270\354\235\264\354\236\254\352\270\260.py" "b/2743\353\213\250\354\226\264\352\270\270\354\235\264\354\236\254\352\270\260.py" index 2bf9570..b45f6d9 100644 --- "a/2743\353\213\250\354\226\264\352\270\270\354\235\264\354\236\254\352\270\260.py" +++ "b/2743\353\213\250\354\226\264\352\270\270\354\235\264\354\236\254\352\270\260.py" @@ -1,5 +1,5 @@ -n = input() - -ans = len(n) - +n = input() + +ans = len(n) + print(ans) \ No newline at end of file diff --git "a/2745\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" "b/2745\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" index 65a15a0..d940036 100644 --- "a/2745\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" +++ "b/2745\354\247\204\353\262\225\353\263\200\355\231\230_\353\202\230\354\244\221\354\227\220 \353\230\220\352\263\265\353\266\200.py" @@ -1,12 +1,12 @@ -system = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" -N, B = input().split() -B = int(B) -N = list(N) -ans = 0 -i=0 - -while N: - ans += system.find(N.pop())*(B**i) - i += 1 - +system = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" +N, B = input().split() +B = int(B) +N = list(N) +ans = 0 +i=0 + +while N: + ans += system.find(N.pop())*(B**i) + i += 1 + print(ans) \ No newline at end of file diff --git "a/2758 \353\241\234\353\230\220.py" "b/2758 \353\241\234\353\230\220.py" deleted file mode 100644 index 252b869..0000000 --- "a/2758 \353\241\234\353\230\220.py" +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline - -dp = [[1 if j==0 else i if j==1 else 0 for i in range(2001)] for j in range(15)] -for i in range(2,15): - for j in range(1,2001): - dp[i][j] = dp[i-1][j//2] + dp[i][j-1] - -for _ in range(int(input())): - n,m = map(int,input().split()) - sys.stdout.write(str(dp[n][m]) +'\n') \ No newline at end of file diff --git "a/2776\354\225\224\352\270\260\354\231\225.py" "b/2776\354\225\224\352\270\260\354\231\225.py" deleted file mode 100644 index c182383..0000000 --- "a/2776\354\225\224\352\270\260\354\231\225.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - N = int(input()) - arr1 = set(input().split()) - M = int(input()) - for num in input().split(): - print(1 if num in arr1 else 0) \ No newline at end of file diff --git "a/2792\353\263\264\354\204\235\354\203\201\354\236\220.py" "b/2792\353\263\264\354\204\235\354\203\201\354\236\220.py" deleted file mode 100644 index 257dd34..0000000 --- "a/2792\353\263\264\354\204\235\354\203\201\354\236\220.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline -from math import ceil - -def answer(): - global n, m, jewerlies - start, end, ans = (1, max(jewerlies), 0) - - while(start <= end): - mid, sections = ((start+end)//2, 0) - - for i in jewerlies: - sections += ceil(i/mid) - # 보석을 나눈 분배가 아이들의 수보다 적으면 일단 ans에 저장.그리고 분배 섹션 늘리고 보석수 줄이기 위해 왼쪽으로 이동. - if sections <= n: - ans, end = (mid, mid-1) - else: - start = mid+1 - return ans - -n, m = map(int, input().split()) -jewerlies = [] -for _ in range(m): - jewerlies.append(int(input())) - -print(answer()) \ No newline at end of file diff --git "a/2805\353\202\230\353\254\264\354\236\220\353\245\264\352\270\260.py" "b/2805\353\202\230\353\254\264\354\236\220\353\245\264\352\270\260.py" deleted file mode 100644 index f5fd1a5..0000000 --- "a/2805\353\202\230\353\254\264\354\236\220\353\245\264\352\270\260.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline - -def isPossible(mid): - M_cnt = 0 - for i in range(N): - if tree[i] - mid > 0: - M_cnt += tree[i]-mid - if M_cnt >=M: - return True - else: - return False - - - -# 나무M미터가 필요. -# 높이 H지정하면 한줄 나무 모두 절단. -# 잘린건 상근이가 들고감. -# 목표 M미터만큼. -# H의 최댓값 구하라. -N,M = map(int,input().split()) -tree = list(map(int,input().split())) - -# 최소 m을 가져가는 h를 이분탐색 해보자 -left = 0 -right = max(tree) -while left <= right: - mid = (left+right)//2 - if isPossible(mid): - left = mid+1 - H = mid - else: - right = mid-1 - -print(H) \ No newline at end of file diff --git "a/2812 \355\201\254\352\262\214\353\247\214\353\223\244\352\270\260.py" "b/2812 \355\201\254\352\262\214\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index fe97616..0000000 --- "a/2812 \355\201\254\352\262\214\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -N , K = map(int,input().split()) -nums = list(input().rstrip()) -answer = [] - -for i in range(N): - while K != 0 and answer: - if answer[-1] < nums[i]: - answer.pop() - K -= 1 - else: break - answer.append(nums[i]) -if K: answer = answer[:-K] -print(''.join(answer)) \ No newline at end of file diff --git a/2812.py b/2812.py deleted file mode 100644 index 399035e..0000000 --- a/2812.py +++ /dev/null @@ -1,20 +0,0 @@ - -N , K= map(int,input().split()) -number = list(input()) -ans = [] - -for i in range(N): - while K != 0 and ans: - if ans[-1] < number[i]: - ans.pop() - K -= 1 - else: - break - ans.append(number[i]) -# 전꺼보다 작은수는 안넣고 큰수면 전에꺼 빼고 내꺼 넣음. K양수일때까지 돌고 K남으면 남은K만큼 소모시킴. -# 아이디어는 큰수는 넣고 그 다음 숫자들이랑 비교시키는것. -# ans에 어떤 숫자를 넣을것인가? -for _ in range(K): - ans.pop() - -print(''.join(ans)) \ No newline at end of file diff --git "a/2812_\354\210\253\354\236\220 \354\240\234\354\231\270\354\213\234\354\274\234\354\204\234 \355\201\254\352\262\214\353\247\214\353\223\244\352\270\260.py" "b/2812_\354\210\253\354\236\220 \354\240\234\354\231\270\354\213\234\354\274\234\354\204\234 \355\201\254\352\262\214\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 4a01f50..0000000 --- "a/2812_\354\210\253\354\236\220 \354\240\234\354\231\270\354\213\234\354\274\234\354\204\234 \355\201\254\352\262\214\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,24 +0,0 @@ - -string_1 = list(input()) -string_2 = list(input()) -string_3 = list(input()) -max_cnt = [] - -for i in range(len(string_1)): - index2 = string_2.find(string_1[i]) - index3 = string_3.find(string_1[i]) - - if index2 != -1 and index3 != -1: - cnt=1 - j=1 - while 1: - if string_1[i+j] == string_2[index2+j] and string_2[index2+j] == string_3[index3+j]: - cnt+=1 - j+=1 - else: - max_cnt.append(cnt) - break - else: - continue - -print(max(max_cnt)) \ No newline at end of file diff --git "a/2839\354\204\244\355\203\225\353\260\260\353\213\254.py" "b/2839\354\204\244\355\203\225\353\260\260\353\213\254.py" index 5df55d1..d7bd2a7 100644 --- "a/2839\354\204\244\355\203\225\353\260\260\353\213\254.py" +++ "b/2839\354\204\244\355\203\225\353\260\260\353\213\254.py" @@ -1,9 +1,9 @@ -N = int(input()) -dp = [float('inf')]* 5001 - -dp[3] = 1 -dp[5] = 1 -for i in range(6,N+1): - dp[i] = min(dp[i],dp[i-3]+1,dp[i-5]+1) - +N = int(input()) +dp = [float('inf')]* 5001 + +dp[3] = 1 +dp[5] = 1 +for i in range(6,N+1): + dp[i] = min(dp[i],dp[i-3]+1,dp[i-5]+1) + print(dp[N] if dp[N] != float('inf') else -1) \ No newline at end of file diff --git "a/2876\352\267\270\353\236\230\355\224\275\354\212\244\355\200\264\354\246\210.py" "b/2876\352\267\270\353\236\230\355\224\275\354\212\244\355\200\264\354\246\210.py" deleted file mode 100644 index c4b50de..0000000 --- "a/2876\352\267\270\353\236\230\355\224\275\354\212\244\355\200\264\354\246\210.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = [list(map(int, input().split())) for _ in range(N)] -max_grade = {i:0 for i in range(1,6)} -seq_grade = {i:0 for i in range(1,6)} - -for i in range(2): - seq_grade[arr[0][i]] = 1 - max_grade[arr[0][i]] = 1 -for i in range(1,N): - if arr[i][0] == arr[i][1]: - arr[i].pop() - for num in arr[i]: - seq_grade[num] += 1 - if num not in arr[i-1]: - seq_grade[num] = 1 - max_grade[num] = max(max_grade[num],seq_grade[num]) - -max_cnt, max_num = 0, 0 -for check in max_grade: - if max_grade[check] > max_cnt: - max_cnt = max_grade[check] - max_num = check -print(max_cnt,max_num) \ No newline at end of file diff --git "a/2887 \355\226\211\354\204\261\355\204\260\353\204\220.py" "b/2887 \355\226\211\354\204\261\355\204\260\353\204\220.py" deleted file mode 100644 index 1966c4c..0000000 --- "a/2887 \355\226\211\354\204\261\355\204\260\353\204\220.py" +++ /dev/null @@ -1,45 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -def kruskal(): - min_dists = 0 - while dists: - dist,a,b = heappop(dists) - if find(a) != find(b): - union(a,b) - min_dists+=dist - return min_dists - -def find(x): - if parents[x] == x: - return x - parents[x] = find(parents[x]) - return parents[x] - -def union(a,b): - a = find(a) - b = find(b) - - if a 효율성 -x_zip = [0] * n -for x in x_list: - x_zip[x] += 1 - -# 배열을 구함 -dp = [x_zip[1]] * n # x=1 일때는 미리 빼둠 -dp_sum = [0] * (n+1) - -for x in range(2, n): - for i in range(0, n, x): - dp[i] += x_zip[x] - -# 배열의 부분합 구함 -dp_sum[1] = dp[0] -for i in range(1, n): - dp_sum[i+1] = dp_sum[i] + dp[i] - -# 출력 -for _ in range(q): - l,r = map(int,input().split()) - res = dp_sum[r+1]-dp_sum[l] - - print(res) - -# 큰 복잡도만 따지는게 아니라 n^2이 몇배까지 허용되는지 따져야 하는 효율성 관리 고난도 문제 +import sys +input = sys.stdin.readline + +n, k = map(int,input().split()) +x_list = list(map(int,input().split())) +q = int(input()) + +# x를 압축함 -> 효율성 +x_zip = [0] * n +for x in x_list: + x_zip[x] += 1 + +# 배열을 구함 +dp = [x_zip[1]] * n # x=1 일때는 미리 빼둠 +dp_sum = [0] * (n+1) + +for x in range(2, n): + for i in range(0, n, x): + dp[i] += x_zip[x] + +# 배열의 부분합 구함 +dp_sum[1] = dp[0] +for i in range(1, n): + dp_sum[i+1] = dp_sum[i] + dp[i] + +# 출력 +for _ in range(q): + l,r = map(int,input().split()) + res = dp_sum[r+1]-dp_sum[l] + + print(res) + +# 큰 복잡도만 따지는게 아니라 n^2이 몇배까지 허용되는지 따져야 하는 효율성 관리 고난도 문제 # 결국 x_list의 최적화가 핵심인듯 \ No newline at end of file diff --git a/2908.py b/2908.py deleted file mode 100644 index e4bbba7..0000000 --- a/2908.py +++ /dev/null @@ -1,43 +0,0 @@ -class Node: - def __init__(self, item, left, right): - self.item = item - self.left = left - self.right = right - - -def inorder(node): - if node.left !='.': - inorder(tree[node.left]) - print(node.item, end='') - if node.right!='.': - inorder(tree[node.right]) - -def postorder(node): - if node.left !='.': - postorder(tree[node.left]) - if node.right!='.': - postorder(tree[node.right]) - print(node.item, end='') - -def preorder(node): - print(node.item, end='') - if node.left !='.': - preorder(tree[node.left]) - if node.right!='.': - preorder(tree[node.right]) - - - -N = int(input()) -tree={} - -for _ in range(N): - node,left,right = map(str, input().split()) - tree[node] = Node(item=node, left=left, right=right) - - -preorder(tree['A']) -print() -inorder(tree['A']) -print() -postorder(tree['A']) \ No newline at end of file diff --git "a/2920 \354\235\214\352\263\204.py" "b/2920 \354\235\214\352\263\204.py" deleted file mode 100644 index fa131ab..0000000 --- "a/2920 \354\235\214\352\263\204.py" +++ /dev/null @@ -1,9 +0,0 @@ - -arr = list(map(int, input().split())) -pivot = [i for i in range(1, 9)] -if arr == pivot: - print('ascending') -elif arr == pivot[::-1]: - print('descending') -else: - print('mixed') \ No newline at end of file diff --git "a/2922\354\246\220\352\261\260\354\232\264\353\213\250\354\226\264.py" "b/2922\354\246\220\352\261\260\354\232\264\353\213\250\354\226\264.py" deleted file mode 100644 index 487a61b..0000000 --- "a/2922\354\246\220\352\261\260\354\232\264\353\213\250\354\226\264.py" +++ /dev/null @@ -1,9 +0,0 @@ -import sys -input = sys.stdin.readline - - -s = input().rstrip() -n = len(s) -for i in range(n): - if s[i] == '_': - pass \ No newline at end of file diff --git "a/2941 \355\201\254\353\241\234\354\225\204\355\213\260\354\225\204 \354\225\214\355\214\214\353\262\263..py" "b/2941 \355\201\254\353\241\234\354\225\204\355\213\260\354\225\204 \354\225\214\355\214\214\353\262\263..py" deleted file mode 100644 index 08de106..0000000 --- "a/2941 \355\201\254\353\241\234\354\225\204\355\213\260\354\225\204 \354\225\214\355\214\214\353\262\263..py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -s = input().rstrip() -n = len(s) -idx = 0 -cnt = 0 -dict_c = ['c=','c-','z=','d-','lj','nj','s=','z='] -while idx < n : - if idx+2 < n and s[idx:idx+3]=='dz=': - idx += 3 - cnt += 1 - continue - if idx+1 < n: - check = s[idx:idx+2] - if check in dict_c: - idx += 2 - cnt += 1 - continue - idx += 1 - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/3015 \354\230\244\354\225\204\354\213\234\354\212\244\354\236\254\352\262\260\355\225\251.py" "b/3015 \354\230\244\354\225\204\354\213\234\354\212\244\354\236\254\352\262\260\355\225\251.py" deleted file mode 100644 index 2591349..0000000 --- "a/3015 \354\230\244\354\225\204\354\213\234\354\212\244\354\236\254\352\262\260\355\225\251.py" +++ /dev/null @@ -1,33 +0,0 @@ -from sys import stdin - - -def solve(): - stack = [] - answer = 0 - - for h in height: - while stack and stack[-1][HEIGHT] < h: - answer += stack.pop()[CNT] - - if not stack: - stack.append((h, 1)) - else: - if stack[-1][HEIGHT] == h: - cnt = stack.pop()[CNT] - answer += cnt - - if stack: - answer += 1 - - stack.append((h, cnt + 1)) - else: - stack.append((h, 1)) - answer += 1 - return answer - - -if __name__ == '__main__': - HEIGHT, CNT = 0, 1 - n = int(stdin.readline()) - height = [int(stdin.readline()) for _ in range(n)] - print(solve()) \ No newline at end of file diff --git "a/3033\352\260\200\354\236\245 \352\270\264 \353\254\270\354\236\220\354\227\264_\353\235\274\353\271\210\354\271\264\355\224\204.py" "b/3033\352\260\200\354\236\245 \352\270\264 \353\254\270\354\236\220\354\227\264_\353\235\274\353\271\210\354\271\264\355\224\204.py" deleted file mode 100644 index 6507eb2..0000000 --- "a/3033\352\260\200\354\236\245 \352\270\264 \353\254\270\354\236\220\354\227\264_\353\235\274\353\271\210\354\271\264\355\224\204.py" +++ /dev/null @@ -1,210 +0,0 @@ -# Suffix array와 LCP -import sys -global n, texts, mod -n = int(sys.stdin.readline().rstrip()) -texts = sys.stdin.readline().rstrip() -mod = 999983 -base = 31 -n_table = [] -n_table.append(1) -for i in range(1,n): - n_table.append(n_table[i-1] * base % mod) - -def pattern_match(idx1, idx2, M): - global texts - for i in range(M): - if texts[idx1+i] != texts[idx2+i]: return False - return True - - -result = 0 -def check(length): - global n, texts, mod - hash_table = {} - num = n - length + 1 - h = 0 - for i in range(length): - h *= base - h += ord(texts[i]) - h %= mod - hash_table[h] = [0] - for i in range(1,num): - h -= ord(texts[i-1])*n_table[length-1] % mod - h = h % mod - h *= base - h += ord(texts[i+length-1]) - h %= mod - if hash_table.get(h): - for h_t in hash_table[h]: - if pattern_match(i,h_t,length): - return True - hash_table[h].append(i) - else: - temp_lst = [i] - hash_table[h] = temp_lst - return False - -low = 0 -high = n-1 -result = 0 -while low <= high: - mid = int((low+high)/2) - if check(mid): - result = mid - low = mid + 1 - else: - high = mid -1 - -print(result) - - - -############################################################################# -P = 31 -M = [1000000009, 1234567891] - -l = int(input()) -string = input() - -def powmod(a, b, m): - if b == 0: - return 1 - x = powmod(a, b//2, m) - return x*x*a%m if b%2 else x*x%m - -invs = [powmod(P, x-2, x) for x in M] - -s, e = 0, len(string)-1 -while s < e: - m = (s + e + 1) // 2 - hashset = set() - hasduplicate = False - - hashval, c = [0, 0], [1, 1] - for i in range(m): - for j in range(len(M)): - hashval[j] += (ord(string[i])-ord('a')) * c[j] - hashval[j] %= M[j] - c[j] *= P - c[j] %= M[j] - hashset.add(tuple(hashval)) - - for i in range(l-m): - for j in range(len(M)): - hashval[j] += (ord(string[i+m])-ord('a')) * c[j] - hashval[j] -= (ord(string[i])-ord('a')) - hashval[j] *= invs[j] - hashval[j] %= M[j] - if tuple(hashval) in hashset: - hasduplicate = True - break - hashset.add(tuple(hashval)) - - if hasduplicate: - s = m - else: - e = m - 1 - -print(s) - - - -############################################################################# -# Problem No.: 3033 -# Solver: Jinmin Goh -# Date: 20200621 -# URL: https://www.acmicpc.net/problem/3033 - -import sys -import collections - -def main(): - n = int(input()) - S = input() - - # appropriate prime - modVal = 2147483647 - powVal = 256 - - def RabinKarp() -> bool: - if pMid == 0: - return True - tempVal = 0 - for i in range(pMid): - tempVal = (tempVal * powVal + ord(S[i])) % modVal - - mulVal = (1 << (8 * (pMid - 1))) % modVal - - hashDict = collections.defaultdict(list) - hashDict[tempVal].append(0) - - for i in range(len(S) - pMid): - tempVal = ((tempVal - ord(S[i]) * mulVal) * powVal + ord(S[i + pMid])) % modVal - for j in hashDict[tempVal]: - if S[i + 1:i + pMid + 1] == S[j:j + pMid]: - return True - hashDict[tempVal].append(i + 1) - return False - - # binary search - pFront = 0 - pRear = len(S) - while pFront + 1 < pRear: - pMid = (pFront + pRear) // 2 - flag = RabinKarp() - if flag: - pFront = pMid - else: - pRear = pMid - print(pFront) - return - -if __name__ == "__main__": - main() - - - -############################################################################# -n = int(input()) -s = input() - -r = [ord(i) for i in s] -sa = [i for i in range(n)] -tmp = [0] * n -lcp = [-1] * n -f = lambda m: r[m] if m answer: - answer = cnt - - # 행 순회하면서 연속되는 숫자 세기 - cnt=1 - for j in range(1, n): - if arr[j][i] == arr[j-1][i]: - # 이전 것과 같다면 cnt에 1 더하기 - cnt += 1 - else: - # 이전과 다르다면 다시 1로 초기화 - cnt=1 - - # 비교해서 현재 cnt가 더 크다면 answer 갱신하기 - if cnt > answer: - answer = cnt - - return answer - -n=int(input()) -arr=[list(input()) for _ in range(n)] -answer=0 - -for i in range(n): - for j in range(n): - # 열 바꾸기 - if j+1 < n: - # 인점한 것과 바꾸기 - arr[i][j], arr[i][j+1] = arr[i][j+1], arr[i][j] - - # check는 arrd에서 인점한 것과 바꿨을 때 가장 긴 연속한 부분을 찾아내는 함수이다 - temp=check(arr) - - if temp > answer: - answer = temp - - # 바꿨던 것을 다시 원래대로 돌려놓기 - arr[i][j], arr[i][j+1] = arr[i][j+1], arr[i][j] - - # 행 바꾸기 - if i+1 < n: - # 인점한 것과 바꾸기 - arr[i][j], arr[i+1][j] = arr[i+1][j], arr[i][j] - - # check는 arrd에서 인점한 것과 바꿨을 때 가장 긴 연속한 부분을 찾아내는 함수이다 - temp=check(arr) - - if temp > answer: - answer = temp - - # 바꿨던 것을 다시 원래대로 돌려놓기 - arr[i][j], arr[i+1][j] = arr[i+1][j], arr[i][j] - +import sys +input=sys.stdin.readline + +def check(arr): + n=len(arr) + answer=1 + + for i in range(n): + # 열 순회하면서 연속되는 숫자 세기 + cnt=1 + for j in range(1, n): + if arr[i][j] == arr[i][j-1]: + # 이전 것과 같다면 cnt에 1 더하기 + cnt += 1 + else: + # 이전과 다르다면 다시 1로 초기화 + cnt=1 + + # 비교해서 현재 cnt가 더 크다면 answer 갱신하기 + if cnt > answer: + answer = cnt + + # 행 순회하면서 연속되는 숫자 세기 + cnt=1 + for j in range(1, n): + if arr[j][i] == arr[j-1][i]: + # 이전 것과 같다면 cnt에 1 더하기 + cnt += 1 + else: + # 이전과 다르다면 다시 1로 초기화 + cnt=1 + + # 비교해서 현재 cnt가 더 크다면 answer 갱신하기 + if cnt > answer: + answer = cnt + + return answer + +n=int(input()) +arr=[list(input()) for _ in range(n)] +answer=0 + +for i in range(n): + for j in range(n): + # 열 바꾸기 + if j+1 < n: + # 인점한 것과 바꾸기 + arr[i][j], arr[i][j+1] = arr[i][j+1], arr[i][j] + + # check는 arrd에서 인점한 것과 바꿨을 때 가장 긴 연속한 부분을 찾아내는 함수이다 + temp=check(arr) + + if temp > answer: + answer = temp + + # 바꿨던 것을 다시 원래대로 돌려놓기 + arr[i][j], arr[i][j+1] = arr[i][j+1], arr[i][j] + + # 행 바꾸기 + if i+1 < n: + # 인점한 것과 바꾸기 + arr[i][j], arr[i+1][j] = arr[i+1][j], arr[i][j] + + # check는 arrd에서 인점한 것과 바꿨을 때 가장 긴 연속한 부분을 찾아내는 함수이다 + temp=check(arr) + + if temp > answer: + answer = temp + + # 바꿨던 것을 다시 원래대로 돌려놓기 + arr[i][j], arr[i+1][j] = arr[i+1][j], arr[i][j] + print(answer) \ No newline at end of file diff --git "a/3090\354\260\250\354\235\264\353\245\274\354\265\234\354\206\214\353\241\234.py" "b/3090\354\260\250\354\235\264\353\245\274\354\265\234\354\206\214\353\241\234.py" deleted file mode 100644 index 7ecf6e9..0000000 --- "a/3090\354\260\250\354\235\264\353\245\274\354\265\234\354\206\214\353\241\234.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys, copy -input = sys.stdin.readline - - - - -def investigate(gap): - global tempArr - tempArr = copy.deepcopy(arr) - operCount = 0 - - # 인접한 수의 차이가 우리가 설정한 평균보다 크면 감소연산을 평균과 실제의 갭만큼 시킨다. - for i in range(N - 1): - if tempArr[i + 1] - tempArr[i] > gap: - operCount += tempArr[i + 1] - (tempArr[i] + gap) - tempArr[i + 1] = tempArr[i] + gap - # 이건 뒤가 앞이 뒤보다 큰거 - for i in range(N - 1, 0, -1): - if tempArr[i - 1] - tempArr[i] > gap: - operCount += tempArr[i - 1] - (tempArr[i] + gap) - tempArr[i - 1] = tempArr[i] + gap - # 연산끝나고 총 횟수가 T보다 작으면 성공 아니면 실패 - if operCount <= T: - return True - return False - -N, T = map(int, input().split()) -arr = list(map(int, input().split())) -left = 0 -right = 1e9 -result = [] - -# 성공하면 오른쪽을 쭉 당겨서 설정한 mid값을 줄이려고 해보고 -# 실패하면 왼쪼을 땡겨서 mid값을 키우고 연산횟수를 줄이려고 노력해본다. -while left <= right: - mid = (left + right) // 2 - if investigate(mid): - result = copy.deepcopy(tempArr) - right = mid - 1 - else: - left = mid + 1 -print(*result) \ No newline at end of file diff --git "a/3108\353\241\234\352\263\240.PY" "b/3108\353\241\234\352\263\240.PY" deleted file mode 100644 index f35c4fc..0000000 --- "a/3108\353\241\234\352\263\240.PY" +++ /dev/null @@ -1,45 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def remove(x,y): - q = deque() - q.append([x,y]) - matrix[x][y] = 0 - while q: - x, y = q.popleft() - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0<=nx<2001 and 0<=ny<2001 and matrix[nx][ny]: - q.append([nx,ny]) - matrix[nx][ny] = 0 - - -def paint(s_x,s_y,t_x,t_y): - # 윗변, 아랫변 - for y in range(s_y,t_y+1): - matrix[t_x][y] = 1 - matrix[s_x][y] = 1 - # 왼쪽, 오른쪽 - for x in range(s_x,t_x+1): - matrix[x][s_y] = 1 - matrix[x][t_y] = 1 - - -N = int(input()) -matrix = [[0]*2001 for _ in range(2001)] -for _ in range(N): - x1, y1, x2, y2 = map(int, input().split()) - paint(2*(x1+500),2*(y1+500),2*(x2+500),2*(y2+500)) - -dx = [0,1,0,-1] -dy = [-1,0,1,0] - -answer = -1 if matrix[1000][1000] else 0 -for i in range(2001): - for j in range(2001): - if matrix[i][j]==1: - remove(i,j) - answer += 1 -print(answer) \ No newline at end of file diff --git "a/3176\353\217\204\353\241\234 \353\204\244\355\212\270\354\233\214\355\201\254.py" "b/3176\353\217\204\353\241\234 \353\204\244\355\212\270\354\233\214\355\201\254.py" deleted file mode 100644 index 60a2462..0000000 --- "a/3176\353\217\204\353\241\234 \353\204\244\355\212\270\354\233\214\355\201\254.py" +++ /dev/null @@ -1,76 +0,0 @@ -import sys -from collections import deque -from math import log2 -input = sys.stdin.readline - -N = int(input()) -tree = [[] for _ in range(N+1)] -depth = [0 for _ in range(N+1)] -logN = int(log2(N) + 1) -for _ in range(N-1): - A, B, C = map(int, input().split()) - tree[A].append([B,C]) - tree[B].append([A,C]) - -#DFS -p_list = [[0,0] for _ in range(N+1)] -p_check = [True for _ in range(N+1)] -q = deque() -q.append(1) -p_check[1] = False -while q: - a = q.popleft() - for b,c in tree[a]: - if p_check[b]: - q.append(b) - depth[b] = depth[a] + 1 - p_check[b] = False - p_list[b][0] = a - p_list[b][1] = c -# 아무 노드나 루트로 잡고 부모 저장 - -# 2^k 번째 부모노드와 가장 짧은 도로 가장 긴 도로 구하기 -DP = [[[0,0,0] for _ in range(logN)] for _ in range(N+1)] -# 초기화 -for i in range(N+1): - DP[i][0][0] = p_list[i][0] - DP[i][0][1] = p_list[i][1] - DP[i][0][2] = p_list[i][1] - -#희소 테이블 완성하기 -for j in range(1,logN): - for i in range(1,N+1): - DP[i][j][0] = DP[DP[i][j-1][0]][j-1][0] - DP[i][j][1] = min(DP[i][j-1][1],DP[DP[i][j-1][0]][j-1][1]) - DP[i][j][2] = max(DP[i][j-1][2],DP[DP[i][j-1][0]][j-1][2]) - -K = int(input()) -for _ in range(K): - D, E = map(int, input().split()) - if depth[D] < depth[E]: - D,E=E,D - dif = depth[D]-depth[E] - shortest = float('inf') - longest = 0 - # 레벨 맞추기 - for i in range(logN): - if dif & 1 <0: - n-=7 - if n>=0: ansMin+='8' - else: n+=7; break - - small={6:6, 2:1, 5:2} - if n in small: ansMin=str(small[n])+ansMin - else: - if n==1: ansMin='10'+ansMin[1:] - elif n==3: ansMin='200'+ansMin[2:] - elif n==4: ansMin='20'+ansMin[1:] - +import sys +input=sys.stdin.readline + +t=int(input()) +for _ in range(t): + n=int(input()) + match=[6, 2, 5, 5, 4, 5, 6, 3, 7, 6] + ans=[0, 0, 1, 7, 4, 2, 6, 8, 10, 18, 22] + ansMax='7'*(n%2)+'1'*(n//2-(n%2)) + if n<=10: + print(ans[n], ansMax) + continue + + ansMin='' + while n>0: + n-=7 + if n>=0: ansMin+='8' + else: n+=7; break + + small={6:6, 2:1, 5:2} + if n in small: ansMin=str(small[n])+ansMin + else: + if n==1: ansMin='10'+ansMin[1:] + elif n==3: ansMin='200'+ansMin[2:] + elif n==4: ansMin='20'+ansMin[1:] + print(ansMin, ansMax) \ No newline at end of file diff --git a/3613 Java vs C++.py b/3613 Java vs C++.py deleted file mode 100644 index c4c4aa7..0000000 --- a/3613 Java vs C++.py +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - -var = input().rstrip() -if var[0]=='_': - print('Error!') - exit() -var_name = var.split('_') - -if len(var_name) > 1: - answer = '' - for char in var_name[0]: - if char.isupper(): - print('Error!') - exit() - answer += char - for var in var_name[1:]: - if var: - if var[0].isupper(): - print('Error!') - exit() - answer += var[0].upper() - for char in var[1:]: - if char.isupper(): - print('Error!') - exit() - answer += char - else: - print('Error!') - exit() -else: - answer = '' - if var[0].isupper(): - print('Error!') - exit() - answer += var[0] - for char in var[1:]: - if char.isupper(): - answer += '_' + char.lower() - else: - answer += char -print(answer) \ No newline at end of file diff --git "a/3653 \354\230\201\355\231\224\354\210\230\354\247\221.py" "b/3653 \354\230\201\355\231\224\354\210\230\354\247\221.py" deleted file mode 100644 index 198acf9..0000000 --- "a/3653 \354\230\201\355\231\224\354\210\230\354\247\221.py" +++ /dev/null @@ -1,50 +0,0 @@ -class FenwickTree: - def __init__(self, _movies, _tasks): - self.size, self.tree, self.movieIndex = _movies + _tasks, None, None - self._initialize( _movies, _tasks) - - def update(self, _idx, _diff): - while _idx <= self.size: - self.tree[ _idx] += _diff - _idx += (_idx & -_idx) - - def get_sum(self, _idx): - sum = 0 - while _idx > 0: - sum += self.tree[_idx] - _idx -= (_idx & -_idx) - return sum - - def _initialize(self, _movies, _tasks): - self.tree, self.movieIndex = [0 for _ in range( self.size + 1)], \ - [idx + _tasks for idx in range(0, _movies + 1)] - for number in range(1, _movies + 1): - self.update( number + _tasks, 1) - - def get_movie_index(self, _movie): - return self.movieIndex[ int(_movie)] - - def set_movie_index(self, _movie, _new): - self.movieIndex[ int(_movie)] = _new - -def data_in(): - movies, tasks = map( int, input().split()) - return movies, tasks, input().split() - -def solution( movies, tasks, taskList): - fenwickTree = FenwickTree( movies, tasks) - nextIdx = tasks - for task in taskList: - pos = fenwickTree.get_movie_index( task) - print(fenwickTree.get_sum( pos) - 1, end = ' ') - fenwickTree.update( pos, -1) - fenwickTree.set_movie_index(task, nextIdx) - fenwickTree.update( nextIdx, 1) - nextIdx -= 1 - print() - -if __name__ == '__main__': - testCase = int(input()) - for _ in range( testCase): - movies, tasks, taskList = data_in() - solution( movies, tasks, taskList) diff --git "a/3673\353\202\230\353\210\214 \354\210\230 \354\236\210\353\212\224 \353\266\200\353\266\204 \354\210\230\354\227\264.py" "b/3673\353\202\230\353\210\214 \354\210\230 \354\236\210\353\212\224 \353\266\200\353\266\204 \354\210\230\354\227\264.py" deleted file mode 100644 index 1cf50c2..0000000 --- "a/3673\353\202\230\353\210\214 \354\210\230 \354\236\210\353\212\224 \353\266\200\353\266\204 \354\210\230\354\227\264.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - - -for _ in range(int(input())): - d, n = map(int, input().split()) - arr = list(map(lambda x: int(x)%d, input().split())) - visited = [1] + [0] * 1000000 - sum_n = 0 - for num in arr: - sum_n = (sum_n + num) % d - visited[sum_n] += 1 - - # i가 나온 것들중 2개를 뽑는 조합의 수. - result = 0 - for i in range(d): - result += visited[i]*(visited[i]-1)//2 - print(result) diff --git a/369game.py b/369game.py index 8043f37..87f5833 100644 --- a/369game.py +++ b/369game.py @@ -1,22 +1,15 @@ -N = int(input()) - - -for i in range(1,N+1): - cnt = 0 - number = i - if i>100: - if i//100 ==3 or i//100 ==6 or i//100 ==9: - cnt +=1 - i = i - i//100 *100 - if i>10: - if i//10 ==3 or i//10 ==6 or i//10 ==9: - cnt +=1 - i = i - i//10 *10 - if i == 3 or i ==6 or i ==9: - cnt +=1 - if cnt !=0: - for _ in range(cnt): - print("-", end ="") - print(end = " ") - else: - print(number, end=" ") \ No newline at end of file +import itertools as it + +T = int(input()) +for test in range(T): + N = int(input()) + s = [] + print("#{}\n1".format(test+1)) + for i in range(N-1): + s.append(i) + + for j in range(i+2): + com = list(it.combinations(s,j)) + num = len(com) + print(num, end = " ") + print("") \ No newline at end of file diff --git "a/36\354\247\204\353\262\225_1036.py" "b/36\354\247\204\353\262\225_1036.py" deleted file mode 100644 index 15d5961..0000000 --- "a/36\354\247\204\353\262\225_1036.py" +++ /dev/null @@ -1,31 +0,0 @@ -def d(c): - if ord('0') <= ord(c) <= ord('9'): - return ord(c)-ord('0') - return ord(c)-ord('A')+10 -def to36(n): - if n == 0: - return "0" - S = "" - d = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] - while n > 0: - S += d[n%36] - n = n // 36 - return S[::-1] -N = int(input()) -val = [0]*36 -for _ in range(N): - S = input() - for i in range(len(S)): - val[d(S[i])] += 36**(len(S)-i-1) -K = int(input()) -arr = [[0]*2 for i in range(36)] -for i in range(36): - arr[i][0] = val[i]*(35-i) - arr[i][1] = i -arr.sort() -ans = 0 -for i in range(36-K): - ans += val[arr[i][1]]*arr[i][1] -for i in range(36-K, 36): - ans += val[arr[i][1]]*35 -print(to36(ans)) \ No newline at end of file diff --git "a/3780\353\204\244\355\201\254\355\211\210\355\201\254\354\227\260\352\262\260.py" "b/3780\353\204\244\355\201\254\355\211\210\355\201\254\354\227\260\352\262\260.py" deleted file mode 100644 index 0acbfeb..0000000 --- "a/3780\353\204\244\355\201\254\355\211\210\355\201\254\354\227\260\352\262\260.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def find(x): - if parent[x]==x: - return x - # 부모쪽 length모두 갱신 - tmp = find(parent[x]) - # 내 length 갱신 - length[x] += length[parent[x]] - # 부모값 저장 - parent[x] = tmp - # 반환. - return tmp - -def union(a,b): - length[a] = abs(a-b) % 1000 - parent[a] = b - -for test in range(1,int(input())+1): - N = int(input()) - parent = {i:i for i in range(1,N+1)} - length = {i:0 for i in range(1,N+1)} - while True: - command = input().split() - if command[0]=='E': - find(int(command[1])) - print(length[int(command[1])]) - elif command[0]=='I': - union(int(command[1]),int(command[2])) - else: - break \ No newline at end of file diff --git "a/3783\354\204\270\354\240\234\352\263\261\352\267\274.py" "b/3783\354\204\270\354\240\234\352\263\261\352\267\274.py" deleted file mode 100644 index 26ceaaf..0000000 --- "a/3783\354\204\270\354\240\234\352\263\261\352\267\274.py" +++ /dev/null @@ -1,18 +0,0 @@ -import decimal -# 천자리까지 정확도 주기 -decimal.getcontext().prec = 1000 - - -N = int(input()) -for _ in range(N): - # Decimal 객체를 만듬.(float, int같은) - # 자릿수 10자리까지 정확하게 입력해줌. - d = decimal.Decimal(input().rstrip() + '.0000000000') - pow = decimal.Decimal('1') / decimal.Decimal('3') - d = decimal.Decimal(d ** pow) - # decimal 파이썬 자체 내장 함수에 대응, 500자리에서 대충 올렸다. - d = round(d, 500) - # quantize(a,b) -> b의 지수를 가지는 자리 올림됨 x와 같은 값을 반환. - # d에 대해 a와 같은 자릿수에서 0을 향해 올림해서 값을 가져감 - d = decimal.Decimal(d).quantize(decimal.Decimal('.0000000001'), rounding=decimal.ROUND_DOWN) - print(d) \ No newline at end of file diff --git "a/4095\354\265\234\353\214\200\354\240\225\354\202\254\352\260\201\355\230\225.py" "b/4095\354\265\234\353\214\200\354\240\225\354\202\254\352\260\201\355\230\225.py" deleted file mode 100644 index aae6d9d..0000000 --- "a/4095\354\265\234\353\214\200\354\240\225\354\202\254\352\260\201\355\230\225.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - - -while 1: - N,M = map(int,input().split()) - if N==0 and M==0: break - square = [list(map(int,input().split())) for _ in range(N)] - dp = [[0]*(M+1) for _ in range(N+1)] - - # 위 왼 대각 왼쪽 위가 0이면 1부터 다시 시작함. - # 어디 하나라도 짧으면 그 길이가 최대길이로 저장됨.(정사각형을 만들수있는 최대길이.) - max_length = 0 - for i in range(1,N+1): - for j in range(1,M+1): - if square[i-1][j-1]: - dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1 - if dp[i][j] > max_length: - max_length = dp[i][j] - - print(max_length) \ No newline at end of file diff --git "a/4096\355\216\240\353\246\260\353\223\234\353\241\234\353\257\270\355\204\260.py" "b/4096\355\216\240\353\246\260\353\223\234\353\241\234\353\257\270\355\204\260.py" deleted file mode 100644 index 4421855..0000000 --- "a/4096\355\216\240\353\246\260\353\223\234\353\241\234\353\257\270\355\204\260.py" +++ /dev/null @@ -1,16 +0,0 @@ -case = input() - -while(int(case)): - length = len(case) - num = int(case) - answer = 0 - while(1): - if case == case[::-1]: - break - num = num + 1 - answer = answer + 1 - case = str(num).zfill(length) - print(answer) - case = input() - if case == '0': - break diff --git "a/4134 \353\213\244\354\235\214\354\206\214\354\210\230.py" "b/4134 \353\213\244\354\235\214\354\206\214\354\210\230.py" deleted file mode 100644 index 59287c8..0000000 --- "a/4134 \353\213\244\354\235\214\354\206\214\354\210\230.py" +++ /dev/null @@ -1,38 +0,0 @@ -import sys -input = sys.stdin.readline -from math import log2 - - -def make_ast_sieve(): - MAX = int(4e9) - m = int(MAX**0.5)+1 - sieve = [False,False] + [True] * m - for i in range(2,m): - if sieve[i]: - for j in range(i+i,m,i): - sieve[j] = False - return [num for num in range(2,m) if sieve[num]] - - -def prime_check(num): - - for prime in prime_nums: - if not num%prime and num//prime > 1: - return False - if prime > num: - return True - return True - - -prime_nums = make_ast_sieve() - -for test_case in range(int(input())): - n = int(input()) - MAX = int(4e9) - if n==0 or n==1: - print(2) - continue - for i in range(n,MAX+int(log2(MAX))): - if prime_check(i): - print(i) - break \ No newline at end of file diff --git "a/4386\353\263\204\354\236\220\353\246\254\353\247\214\353\223\244\352\270\260.py" "b/4386\353\263\204\354\236\220\353\246\254\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index 6afc8e7..0000000 --- "a/4386\353\263\204\354\236\220\353\246\254\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,44 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -def kruskal(): - answer = 0 - while dists: - ab_dists,star_a,star_b = heappop(dists) - - if find(star_a) !=find(star_b): - answer += ab_dists - union(star_a,star_b) - return answer - -def union(a,b): - a = find(a) - b = find(b) - - if a>b: - parent[b] = a - else: - parent[a] = b - -def find(x): - if parent[x] ==x: - return x - parent[x] = find(parent[x]) - return parent[x] - -n=int(input()) -# 거리가 최소가 되는 비용. -# 점을 다 연결한다.-> 간선 N-1 -> MST -matrix = [list(map(float,input().split())) for _ in range(n)] -parent = [i for i in range(n)] -dists = [] -for i in range(n): - for j in range(n): - if i != j: - heappush(dists,[round(((matrix[i][0] - matrix[j][0])**2 + (matrix[i][1] - matrix[j][1])**2)**0.5,2),i,j]) - - -min_star_set = kruskal() - -print(min_star_set) \ No newline at end of file diff --git "a/4396\354\247\200\353\242\260\354\260\276\352\270\260.py" "b/4396\354\247\200\353\242\260\354\260\276\352\270\260.py" deleted file mode 100644 index 881ddc6..0000000 --- "a/4396\354\247\200\353\242\260\354\260\276\352\270\260.py" +++ /dev/null @@ -1,33 +0,0 @@ -import sys -input = sys.stdin.readline - - -n = int(input()) - -mines = [list(input().rstrip()) for _ in range(n)] -maps = [list(input().rstrip()) for _ in range(n)] - -di = [0,0,-1,1,1,1,-1,-1] -dj = [1,-1,0,0,1,-1,1,-1] - -flag = False -for i in range(n): - for j in range(n): - if maps[i][j]=='x': - if mines[i][j]=='*': - flag = True - continue - cnt = 0 - for k in range(8): - if 0<= i+di[k] < n and 0 <= j+dj[k] < n and mines[i+di[k]][j+dj[k]]=='*': - cnt += 1 - maps[i][j] = str(cnt) - -if flag: - for i in range(n): - for j in range(n): - if mines[i][j]=='*': - maps[i][j] = '*' - -for row in maps: - print(''.join(row)) \ No newline at end of file diff --git a/4446ROT12.py b/4446ROT12.py index 6d51378..52117da 100644 --- a/4446ROT12.py +++ b/4446ROT12.py @@ -1,39 +1,39 @@ -moem = ['a','i','y','e','o','u'] -zaem = ['b','k','x','z','n','h','d','c','w','g','p','v','j','q','t','s','r','l','m','f'] - -# 무한입력. try except -while 1: - try: - S = input() - ans = "" - for i in range(len(S)): - if S[i].lower() in moem: - if S[i].isupper(): - k = S[i].lower() - for j in range(6): - if moem[j] == k: - a = moem[(j+3)%6] - ans += a.upper() - elif S[i].islower(): - for j in range(6): - if moem[j] == S[i]: - a = moem[(j+3)%6] - ans += a - elif S[i].lower() in zaem: - if S[i].isupper(): - k = S[i].lower() - for j in range(20): - if zaem[j] == k: - a = zaem[(j+10)%20] - ans += a.upper() - elif S[i].islower(): - for j in range(20): - if zaem[j] == S[i]: - a = zaem[(j+10)%20] - ans += a - else: - ans += S[i] - - print(ans) - except: +moem = ['a','i','y','e','o','u'] +zaem = ['b','k','x','z','n','h','d','c','w','g','p','v','j','q','t','s','r','l','m','f'] + +# 무한입력. try except +while 1: + try: + S = input() + ans = "" + for i in range(len(S)): + if S[i].lower() in moem: + if S[i].isupper(): + k = S[i].lower() + for j in range(6): + if moem[j] == k: + a = moem[(j+3)%6] + ans += a.upper() + elif S[i].islower(): + for j in range(6): + if moem[j] == S[i]: + a = moem[(j+3)%6] + ans += a + elif S[i].lower() in zaem: + if S[i].isupper(): + k = S[i].lower() + for j in range(20): + if zaem[j] == k: + a = zaem[(j+10)%20] + ans += a.upper() + elif S[i].islower(): + for j in range(20): + if zaem[j] == S[i]: + a = zaem[(j+10)%20] + ans += a + else: + ans += S[i] + + print(ans) + except: break \ No newline at end of file diff --git "a/4463\355\224\274\353\263\264\353\202\230\354\271\230 \354\210\230 \353\266\204\354\204\235_\355\233\204..\354\213\234\352\260\204\354\264\210\352\263\274.py" "b/4463\355\224\274\353\263\264\353\202\230\354\271\230 \354\210\230 \353\266\204\354\204\235_\355\233\204..\354\213\234\352\260\204\354\264\210\352\263\274.py" deleted file mode 100644 index 1e131c3..0000000 --- "a/4463\355\224\274\353\263\264\353\202\230\354\271\230 \354\210\230 \353\266\204\354\204\235_\355\233\204..\354\213\234\352\260\204\354\264\210\352\263\274.py" +++ /dev/null @@ -1,61 +0,0 @@ -from math import log2 -from collections import defaultdict - -def get_prime_factor(num): - dic=defaultdict(int) - d=2 - while d<=num: - if num%d==0: - dic[d]+=1 - num=num/d - else: - d+=1 - - primes=[] - for i in dic.keys(): - for j in range(dic[i]): - primes.append(str(i)) - return primes - -def print_fibo(n): - fibo_num = dp_fibo[i] - if not n: - print(f"Fib(0) = 0, lg does not exist") - else: - print(f"Fib({n}) = {fibo_num}, lg is {log2(fibo_num):.6f}") - primes = get_prime_factor(fibo_num) - if primes: - print("Prime factors: ", end="") - print(*primes) - else: - print("No prime factors") - -def make_fibo_dp(n): - i=0 - while dp_fibo[i] < n: - i+=1 - dp_fibo[i]=int(1/(5**(1/2))*(((1+(5**(1/2)))/2)**i-((1-(5**(1/2)))/2)**i)) - return - -while 1: - start,end = input().split() - start = int(start,16) - end = int(end,16) - dp_fibo = [0]*(10000) - if start>=end: - exit() - - print(f"Range {start} to {end}:") - - make_fibo_dp(end**2) - cnt=0 - for i in range(end+1): - if start<=dp_fibo[i]<=end: - print_fibo(i) - cnt+=1 - - if not cnt: - print("No Fibonacci numbers in the range") - print() - - diff --git "a/4659\353\271\204\353\260\200\353\262\210\355\230\270 \353\260\234\354\235\214\355\225\230\352\270\260.py" "b/4659\353\271\204\353\260\200\353\262\210\355\230\270 \353\260\234\354\235\214\355\225\230\352\270\260.py" deleted file mode 100644 index 83ccb29..0000000 --- "a/4659\353\271\204\353\260\200\353\262\210\355\230\270 \353\260\234\354\235\214\355\225\230\352\270\260.py" +++ /dev/null @@ -1,42 +0,0 @@ -import sys -input = sys.stdin.readline - - - -# 모음3개, 자음3개 연속 x -# 같은글자 연속 두번 x ee,oo는 허용 - -while 1: - good_pwd = input().strip() - if good_pwd == 'end': - break - N = len(good_pwd) - mom_chr = ['a','e','i','o','u'] - mom_cnt = 0 - child_cnt = 0 - answer = False - - for i in range(N): - if good_pwd[i] in mom_chr: - mom_cnt +=1 - answer = True - child_cnt = 0 - else: - child_cnt +=1 - mom_cnt = 0 - - if mom_cnt == 3 or child_cnt ==3: - answer = False - break - - if i>0 and good_pwd[i] ==good_pwd[i-1]: - if good_pwd[i]=='e' or good_pwd[i]=='o': - continue - else: - answer=False - break - - if answer: - print(f'<{good_pwd}> is acceptable.') - else: - print(f'<{good_pwd}> is not acceptable.') \ No newline at end of file diff --git "a/4963\354\204\254\354\235\230\352\260\234\354\210\230_bfs.py" "b/4963\354\204\254\354\235\230\352\260\234\354\210\230_bfs.py" index 831bbd6..19512af 100644 --- "a/4963\354\204\254\354\235\230\352\260\234\354\210\230_bfs.py" +++ "b/4963\354\204\254\354\235\230\352\260\234\354\210\230_bfs.py" @@ -1,35 +1,35 @@ -import sys -input = sys.stdin.readline -from collections import deque - -dx = [1, -1, 0, 0, 1, -1, 1, -1] -dy = [0, 0, -1, 1, -1, -1, 1, 1] - -# bfs이용 근처에 1인 육지들을 찾아다니며 전부 0으로 만들어버린다. -def bfs(i, j): - matrix[i][j] = 0 - queue = deque() - queue.append([i,j]) - while queue: - a, b = queue.popleft() - for k in range(8): - x = a + dx[k] - y = b + dy[k] - if 0 <= x < h and 0 <= y < w and matrix[x][y] == 1: - matrix[x][y] = 0 - queue.append([x, y]) - -# -while True: - w, h = map(int, input().split()) - if w == 0 and h == 0: - break - matrix = [list(map(int, input().split())) for _ in range(h)] - cnt = 0 - # 땅이면 팔방탐색하고 섬카운트 하나 늘려. - for i in range(h): - for j in range(w): - if matrix[i][j] == 1: - bfs(i, j) - cnt += 1 +import sys +input = sys.stdin.readline +from collections import deque + +dx = [1, -1, 0, 0, 1, -1, 1, -1] +dy = [0, 0, -1, 1, -1, -1, 1, 1] + +# bfs이용 근처에 1인 육지들을 찾아다니며 전부 0으로 만들어버린다. +def bfs(i, j): + matrix[i][j] = 0 + queue = deque() + queue.append([i,j]) + while queue: + a, b = queue.popleft() + for k in range(8): + x = a + dx[k] + y = b + dy[k] + if 0 <= x < h and 0 <= y < w and matrix[x][y] == 1: + matrix[x][y] = 0 + queue.append([x, y]) + +# +while True: + w, h = map(int, input().split()) + if w == 0 and h == 0: + break + matrix = [list(map(int, input().split())) for _ in range(h)] + cnt = 0 + # 땅이면 팔방탐색하고 섬카운트 하나 늘려. + for i in range(h): + for j in range(w): + if matrix[i][j] == 1: + bfs(i, j) + cnt += 1 print(cnt) \ No newline at end of file diff --git "a/4963\354\204\254\354\235\230\352\260\234\354\210\230_dfs.py" "b/4963\354\204\254\354\235\230\352\260\234\354\210\230_dfs.py" index c204e67..2a6bb8b 100644 --- "a/4963\354\204\254\354\235\230\352\260\234\354\210\230_dfs.py" +++ "b/4963\354\204\254\354\235\230\352\260\234\354\210\230_dfs.py" @@ -1,30 +1,30 @@ -import sys -read = sys.stdin.readline -sys.setrecursionlimit(10000) - -def dfs(x, y): - dx = [1, 1, -1, -1, 1, -1, 0, 0] - dy = [0, 1, 0, 1, -1, -1, 1, -1] - - field[x][y] = 0 - for i in range(8): - nx = x + dx[i] - ny = y + dy[i] - if 0 <= nx < h and 0 <= ny < w and field[nx][ny] == 1: - dfs(nx, ny) - -while True: - w, h = map(int, read().split()) - if w == 0 and h == 0: - break - field = [] - count = 0 - for _ in range(h): - field.append(list(map(int, read().split()))) - for i in range(h): - for j in range(w): - if field[i][j] == 1: - dfs(i, j) - count += 1 - +import sys +read = sys.stdin.readline +sys.setrecursionlimit(10000) + +def dfs(x, y): + dx = [1, 1, -1, -1, 1, -1, 0, 0] + dy = [0, 1, 0, 1, -1, -1, 1, -1] + + field[x][y] = 0 + for i in range(8): + nx = x + dx[i] + ny = y + dy[i] + if 0 <= nx < h and 0 <= ny < w and field[nx][ny] == 1: + dfs(nx, ny) + +while True: + w, h = map(int, read().split()) + if w == 0 and h == 0: + break + field = [] + count = 0 + for _ in range(h): + field.append(list(map(int, read().split()))) + for i in range(h): + for j in range(w): + if field[i][j] == 1: + dfs(i, j) + count += 1 + print(count) \ No newline at end of file diff --git "a/5014\354\212\244\355\203\200\355\212\270\353\247\201\355\201\254.py" "b/5014\354\212\244\355\203\200\355\212\270\353\247\201\355\201\254.py" deleted file mode 100644 index 03da39a..0000000 --- "a/5014\354\212\244\355\203\200\355\212\270\353\247\201\355\201\254.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -# 그냥 BFS로 위아래 움직이면 된다. 숨바꼭질문제보다 하위문제. -def BFS(F,S,G,U,D): - dp_count = {i:float('inf') for i in range(1,F+1)} - dp_count[S] = 0 - queue = deque() - queue.append(S) - while queue: - cur_stair = queue.popleft() - if cur_stair == G: - print(dp_count[G]) - return - for next_stair in (cur_stair+U,cur_stair-D): - if 1<=next_stair<=F and dp_count[next_stair] > dp_count[cur_stair]+1: - dp_count[next_stair] = dp_count[cur_stair]+1 - queue.append(next_stair) - if dp_count[G]==float('inf'): - print('use the stairs') - -F,S,G,U,D = map(int,input().split()) - - -BFS(F,S,G,U,D) \ No newline at end of file diff --git a/5052.py b/5052.py deleted file mode 100644 index f386042..0000000 --- a/5052.py +++ /dev/null @@ -1,20 +0,0 @@ -t = int(input()) -for test in range(t): - n= int(input()) - numbers = [] - - for _ in range(n): - numbers.append(input()) - - numbers.sort() - ans = 0 - for i in range(n-1): - if numbers[i+1].find(numbers[i]) == 0: - ans = 1 - break - - if ans == 1: - print("NO") - else: - print("YES") - diff --git a/5347LCM.py b/5347LCM.py deleted file mode 100644 index 0a014b8..0000000 --- a/5347LCM.py +++ /dev/null @@ -1,8 +0,0 @@ -import sys -input = sys.stdin.readline -from math import gcd - - -for _ in range(int(input())): - a, b = map(int,input().split()) - print(a*b//gcd(a,b)) \ No newline at end of file diff --git "a/5373\355\201\220\353\271\231_\352\263\265\353\266\200.py" "b/5373\355\201\220\353\271\231_\352\263\265\353\266\200.py" deleted file mode 100644 index c4693f4..0000000 --- "a/5373\355\201\220\353\271\231_\352\263\265\353\266\200.py" +++ /dev/null @@ -1,72 +0,0 @@ -# [BOJ 5573] 큐빙 : https://www.acmicpc.net/problem/5373 -# tag : 구현, 기하 -# solution by @subinium - -# ufl : 큐브별로 UFL 회전시 각면이 바라보는 방향 변화 -# cw : 시계방향으로 돌리는 경우 3 * 3에서 변화되는 내용 -ufl, cw = ['015423', '452310', '320145'], '258147036' - -# 3 * 3 * 3에서 한 변을 뽑는 방법 -# 한 변의 숫자는 반드시 순서대로 등차수열임을 활용 -def side_(ith, st, a, b): - return [st+a*(i % 3)+b*(i//3)-1 for i in range(9)] - -# UDFBLR 순서에서 각 변을 얻기 위한 상수값 사용 -side = [side_(i, *stab) for i, stab in enumerate([(1, 1, 3),(19, 3, 1), (7, 1, 9), (1, 9, 1), (1, 3, 9), (3, 9, 3)])] - -# 기존의 배치에서 바뀐 부분만 재배치 -# a, st, ed : 배열, 기존위치, 바뀐위치 -def realign(a, st, ed): - ret = a[:] - for s, e in zip(st, ed): - ret[int(e)] = a[int(s)] - return ret - -# 한 변을 돌리는 함수 / 큐브의 위치와 상태 변경 -# 시계방향 또는 반시계방향 중 하나만 정의 => 반시계 == 시계*3 -def rotate(op, pos, state): - idx, ccw = 'UDFBLR'.index(op[0]), op[1] # 변확인 및 시계/반시계 방향 확인 - blocks = side[idx] # 볼 변의 번호들만 선택 - # 큐브의 위치 변경 - for i in range(1+(ccw == '+')*2): - blocks = realign(blocks, range(9), cw) - pos = realign(pos, side[idx], blocks) - - # 큐브의 상태 변경 - for i in range(1+((ccw == '+') ^ (idx % 2))*2): - for j in range(9): # 한변당 큐브의 개수 9개 - state[pos[blocks[j]]] = realign( - state[pos[blocks[j]]], range(6), ufl[idx//2]) - - return pos, state - -# 초기 상태 pos, state 정의 -# pos[i] : 매 상태에서 3 * 3 * 3에서 순서대로 넘버링했을 때, i번쨰 큐브의 번호 -# state[i] : 초기 i번 큐브의 상태 -def init(): - pos, state = [i for i in range(27)], [ - [0 for _ in range(6)] for i in range(27)] - for idx, col in enumerate('wyrogb'): - for block in side[idx]: - state[block][idx] = col - return pos, state - -# 각 과정별 함수 -def process(): - N = input() - # 회전 별로 pos, state 변경 - pos, state = init() # 초기화 - for order in input().split(): - pos, state = rotate(order, pos, state) - - # 윗면 큐브들에서 위만 출력 - for i, idx in enumerate(side[0]): - print(state[pos[idx]][0], end=''+(i % 3 == 2)*'\n') - - -# Main 함수 -if __name__ == '__main__': - # 테스트 케이스 별 과정 진행 - TC = int(input()) - for _ in range(TC): - process() \ No newline at end of file diff --git "a/5397\355\202\244\353\241\234\352\261\260.py" "b/5397\355\202\244\353\241\234\352\261\260.py" deleted file mode 100644 index 6c4659c..0000000 --- "a/5397\355\202\244\353\241\234\352\261\260.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -T = int(input()) -for test in range(T): - L = input().rstrip() - left,right = [],[] - for chr in L: - if chr=="<": - if left: - right.append(left.pop()) - elif chr==">": - if right: - left.append(right.pop()) - elif chr=="-": - if left: - left.pop() - else: - left.append(chr) - answer = left + right[::-1] - print("".join(answer)) \ No newline at end of file diff --git "a/5419\353\266\201\354\204\234\355\222\215.py" "b/5419\353\266\201\354\204\234\355\222\215.py" deleted file mode 100644 index 0ca02c4..0000000 --- "a/5419\353\266\201\354\204\234\355\222\215.py" +++ /dev/null @@ -1,8 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - n = int(input()) - for i in range(n): - x, y = map(int, input().split()) - \ No newline at end of file diff --git a/5430AC.py b/5430AC.py deleted file mode 100644 index 67ab52f..0000000 --- a/5430AC.py +++ /dev/null @@ -1,49 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -# R 뒤집기, D 버리기함수 - -# 비어있을때 D쓰면 에러. - -T = int(input()) - -for test in range(T): - p = input().rstrip() - n = int(input()) - xi = input().rstrip().rstrip(']').lstrip('[').split(',') - Xi = deque() - if not n: - xi.pop() - flag=0 - switch = 0 - for x in xi: - Xi.append(x) - for command in p: - if command == 'R': - if flag: - flag=0 - else: - flag=1 - else: - if Xi: - if flag: - Xi.pop() - else: - Xi.popleft() - else: - print('error') - switch = 1 - break - if switch: - continue - else: - if flag: - ans = '' - while Xi: - ans+=(Xi.pop())+',' - ans = ans[:-1] - print(f"[{ans}]") - else: - ans = ",".join(Xi) - print(f"[{ans}]") \ No newline at end of file diff --git a/5430AC_re.py b/5430AC_re.py deleted file mode 100644 index f454a5e..0000000 --- a/5430AC_re.py +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - p = input().rstrip() - n = int(input()) - xi = input().rstrip()[1:-1].split(',') - if not n and 'D' in p: - print('error') - continue - reverse_x = 0 - left = 0 - right = len(xi)-1 - for command in p: - if command == 'R': - reverse_x ^= 1 - else: - if left <= right: - if reverse_x: - right -= 1 - else: - left += 1 - else: - print('error') - break - else: - if reverse_x: - print(f"[{','.join(xi[left:right+1][::-1])}]") - else: - print(f"[{','.join(xi[left:right+1])}]") \ No newline at end of file diff --git a/5525IOIOI.py b/5525IOIOI.py deleted file mode 100644 index bb90c45..0000000 --- a/5525IOIOI.py +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -M = int(input()) -S = input().rstrip().replace('IO','*') + 'F' -flag = 0 -cnt = 0 -ans = 0 -for char in S: - if flag: - if char=='*': - cnt += 1 - else: - if cnt >= N: - if char=='I': - ans += 1 - ans += cnt - N - cnt = 0 - flag = 0 - else: - if char=='*': - flag = 1 - cnt += 1 -print(ans) \ No newline at end of file diff --git "a/5534\352\260\204\355\214\220.py" "b/5534\352\260\204\355\214\220.py" deleted file mode 100644 index d5b599c..0000000 --- "a/5534\352\260\204\355\214\220.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline - -def check(string): - l = len(string) - for start_idx in range(l): - if string[start_idx] == name[0]: - for end_idx in range(start_idx,l): - if string[end_idx]==name[-1]: - avg_gap = (end_idx-start_idx)//(n-1) - cnt = 0 - while cnt < n: - if string[start_idx+avg_gap*cnt]==name[cnt]: - cnt += 1 - continue - break - else: - return 1 - return 0 - -N = int(input()) -name = input().rstrip() -n = len(name) -kanbans = list(input().rstrip() for _ in range(N)) -cnt = 0 -for kanban in kanbans: - cnt += check(kanban) -print(cnt) \ No newline at end of file diff --git "a/5549\355\226\211\354\204\261\355\203\220\354\202\254.py" "b/5549\355\226\211\354\204\261\355\203\220\354\202\254.py" deleted file mode 100644 index 512f01a..0000000 --- "a/5549\355\226\211\354\204\261\355\203\220\354\202\254.py" +++ /dev/null @@ -1,65 +0,0 @@ -import sys -input = sys.stdin.readline - -# 세로 M 가로 M -M,N = map(int,input().split()) -K = int(input()) -maps = [list(input().rstrip()) for _ in range(M)] - -dp = [[[0,0,0] for _ in range(N)] for _ in range(M)] - -# 정글 J 바다 O 얼음 I -for i in range(M): - for j in range(N): - if i and j: - for k in range(3): - dp[i][j][k] = dp[i][j-1][k]+dp[i-1][j][k]-dp[i-1][j-1][k] - if maps[i][j] =='J': - dp[i][j][0] += 1 - elif maps[i][j] =='O': - dp[i][j][1] += 1 - elif maps[i][j] == 'I': - dp[i][j][2] += 1 - elif not i and j: - for k in range(3): - dp[i][j][k] = dp[i][j-1][k] - if maps[i][j] =='J': - dp[i][j][0] += 1 - elif maps[i][j] =='O': - dp[i][j][1] += 1 - elif maps[i][j] == 'I': - dp[i][j][2] += 1 - elif i and not j: - for k in range(3): - dp[i][j][k] = dp[i-1][j][k] - if maps[i][j] =='J': - dp[i][j][0] +=1 - elif maps[i][j] =='O': - dp[i][j][1] +=1 - elif maps[i][j] == 'I': - dp[i][j][2] +=1 - elif not i and not j: - if maps[i][j] =='J': - dp[i][j][0]=1 - elif maps[i][j] =='O': - dp[i][j][1]=1 - elif maps[i][j] == 'I': - dp[i][j][2]=1 - -# 출력범위 조절. -for _ in range(K): - x1,y1,x2,y2 = map(int,input().split()) - answer = [] - if x1 !=1 and y1 != 1: - for k in range(3): - answer.append(dp[x2-1][y2-1][k] - dp[x1-2][y2-1][k] - dp[x2-1][y1-2][k] + dp[x1-2][y1-2][k]) - elif x1 !=1 and y1==1: - for k in range(3): - answer.append(dp[x2-1][y2-1][k] - dp[x1-2][y2-1][k]) - elif x1 ==1 and y1!=1: - for k in range(3): - answer.append(dp[x2-1][y2-1][k] - dp[x2-1][y1-2][k]) - elif x1==1 and y1==1: - for k in range(3): - answer.append(dp[x2-1][y2-1][k]) - print(*answer) \ No newline at end of file diff --git "a/5557_1\355\225\231\353\205\204.py" "b/5557_1\355\225\231\353\205\204.py" deleted file mode 100644 index d54ff0e..0000000 --- "a/5557_1\355\225\231\353\205\204.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline -N = int(input()) -arr = list(map(int, input().split())) -dp = [[0] * 21 for _ in range(N)] -dp[0][arr[0]] = 1 -for i in range(1, N - 1): - for pre_value in range(21): - if dp[i - 1][pre_value]: - if 0 <= pre_value + arr[i] <= 20: - dp[i][pre_value + arr[i]] += dp[i - 1][pre_value] - if 0 <= pre_value - arr[i] <= 20: - dp[i][pre_value - arr[i]] += dp[i - 1][pre_value] -print(dp[N - 2][arr[-1]]) \ No newline at end of file diff --git "a/5568\354\271\264\353\223\234\353\206\223\352\270\260.py" "b/5568\354\271\264\353\223\234\353\206\223\352\270\260.py" deleted file mode 100644 index bc676d3..0000000 --- "a/5568\354\271\264\353\223\234\353\206\223\352\270\260.py" +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline -from itertools import permutations - -n = int(input()) -k = int(input()) -cards = [input().rstrip() for _ in range(n)] -# 같은 조합이라도 순서에 따라 다른 수 -> 순열 -nums = set() -for num_set in permutations(cards,k): - nums.add(''.join(num_set)) -print(len(nums)) \ No newline at end of file diff --git "a/5569\354\266\234\352\267\274\352\262\275\353\241\234.py" "b/5569\354\266\234\352\267\274\352\262\275\353\241\234.py" deleted file mode 100644 index 0534095..0000000 --- "a/5569\354\266\234\352\267\274\352\262\275\353\241\234.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -input = sys.stdin.readline - -# 남북 w 동서도로 h개 -# 남북방향 도로는 왼쪽부터 1,2,...w개 동서도로는 아래부터 1,2,.,..h개 -# 서쪽 i번째에서 남북 남쪽j번째도로가 만나는 교차로는 i,j이다. -# (1,1) (w,h) 가는방법. 방향전환은 최소2칸이상. -# 상태값(x과표, y좌표, x방향전환가능, y방향전환 가능) -w,h = map(int,input().split()) -dp = [[[[0 for _ in range(2)] for _ in range(2)] for _ in range(101)] for _ in range(101)] - -# 앞의 0,1은 방향전환이 가능하냐, 불가능하냐? 뒤의 0,1은 북쪽 방향,동쪽 방향 어딜 일직선으로 통과하냐? -for i in range(2,h+1): - dp[i][1][0][0] = 1 -for i in range(2,w+1): - dp[1][i][0][1] = 1 - -for i in range(2,h+1): - for j in range(2,w+1): - # 방향전환이 가능하고 북쪽 방향을 보는 애들은 남쪽에서 쭉 온 애들이랑 남족에서 왔는데 방향전환 불가능하던 애들. - dp[i][j][0][0] = (dp[i-1][j][0][0] + dp[i-1][j][1][0])%100000 - # 방향전환 가능하고 동쪽 보는애드은 동쪽에서 쭉왔거나 동쪽에서 왔는데 방향전환 불가능해서 쭉온애들 - dp[i][j][0][1] = (dp[i][j-1][0][1] + dp[i][j-1][1][1])%100000 - # 방향전환 불가능한데 북쪽보는 애들은 남쪽에서 올라온 애들중에 동쪽 보고 있던 애들 - dp[i][j][1][0] = (dp[i-1][j][0][1])%100000 - # 방향전환 불가능한데 동쪽보는 애들은 동쪽에서 왔는데 원래 북쪽 보던애들. - dp[i][j][1][1] = (dp[i][j-1][0][0])%100000 - -print((dp[h][w][0][0] + dp[h][w][1][0] + dp[h][w][0][1] + dp[h][w][1][1])%100000) \ No newline at end of file diff --git "a/5582 \352\263\265\355\206\265 \353\266\200\353\266\204 \353\254\270\354\236\220\354\227\264.py" "b/5582 \352\263\265\355\206\265 \353\266\200\353\266\204 \353\254\270\354\236\220\354\227\264.py" deleted file mode 100644 index ec44aab..0000000 --- "a/5582 \352\263\265\355\206\265 \353\266\200\353\266\204 \353\254\270\354\236\220\354\227\264.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - -str1, str2 = (input().rstrip() for _ in range(2)) -n, m = len(str1), len(str2) -dp = [[0]*(m+1) for _ in range(n+1)] -max_v = 0 -for i in range(1,n+1): - for j in range(1,m+1): - if str1[i-1] == str2[j-1]: - dp[i][j] = dp[i-1][j-1] + 1 - if dp[i][j] > max_v: - max_v = dp[i][j] -print(max_v) \ No newline at end of file diff --git "a/5624\354\242\213\354\235\200\354\210\230.py" "b/5624\354\242\213\354\235\200\354\210\230.py" deleted file mode 100644 index 4860214..0000000 --- "a/5624\354\242\213\354\235\200\354\210\230.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = list(map(int,input().split())) -dp = [0]*400003 -tmp = 200001 - -answer = 0 -for i in range(N): - for j in range(i): - if dp[arr[i] - arr[j]+tmp]==1: - answer+=1 - break - for k in range(i+1): - dp[arr[i]+arr[k]+tmp] = 1 - -print(answer) \ No newline at end of file diff --git "a/5624\354\242\213\354\235\200\354\210\230_\353\251\224\353\252\250\353\246\254\354\264\210\352\263\274.py" "b/5624\354\242\213\354\235\200\354\210\230_\353\251\224\353\252\250\353\246\254\354\264\210\352\263\274.py" deleted file mode 100644 index cb169bc..0000000 --- "a/5624\354\242\213\354\235\200\354\210\230_\353\251\224\353\252\250\353\246\254\354\264\210\352\263\274.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = list(map(int,input().split())) - -sums=[[],[],[]] -# 앞의 모든 수를 더하는 집합 set을 만들어보자. -for i in range(N-1): - sums[0].append(arr[i]) - for sum_num in sums[0]: - sums[1].append(sum_num+arr[i]) - for sum_num in sums[1]: - sums[2].append(sum_num+arr[i]) -cnt=0 -for i in range(1,N): - if arr[i] in sums[2]: - cnt+=1 - -print(cnt) diff --git "a/5624\354\242\213\354\235\200\354\210\230_\354\213\234\352\260\204\354\264\210\352\263\274.py" "b/5624\354\242\213\354\235\200\354\210\230_\354\213\234\352\260\204\354\264\210\352\263\274.py" deleted file mode 100644 index 367ff04..0000000 --- "a/5624\354\242\213\354\235\200\354\210\230_\354\213\234\352\260\204\354\264\210\352\263\274.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -def DFS(depth,start,sum_t): - if depth==3: - if arr[start]==sum_t: - return True - return - for pre_num in arr[:start]: - if DFS(depth+1,start,sum_t+pre_num): - return True - -N = int(input()) -arr = list(map(int,input().split())) - -# 앞에있는 수 3개의 합. DFS(중복가능) depth 3까지. -cnt=0 -for i in range(1,N): - if DFS(0,i,0): - cnt+=1 -print(cnt) - \ No newline at end of file diff --git "a/5670\355\234\264\353\214\200\355\217\260\354\236\220\355\214\220.py" "b/5670\355\234\264\353\214\200\355\217\260\354\236\220\355\214\220.py" deleted file mode 100644 index de4c06b..0000000 --- "a/5670\355\234\264\353\214\200\355\217\260\354\236\220\355\214\220.py" +++ /dev/null @@ -1,169 +0,0 @@ -import sys - -class Node: - def __init__(self,chr): - self.chr = chr - self.child = {} - self.check = False - -class Trie: - def __init__(self): - self.root = Node('') - - def insert(self, word): - node = self.root - for w in word: - if w not in node.child: - new = Node(w) - node.child[w] = new - node = new - else: - node = node.child[w] - node.check = True - - def contains(self, word): - cnt = 0 - cur = self.root - for w in word: - cur = cur.child[w] - if len(cur.child) > 1 or cur.check: - cnt+=1 - return cnt - -while 1: - t = Trie() - words = [] - try: N = int(sys.stdin.readline()) - except: break - - for _ in range(N): - s = sys.stdin.readline().rstrip() - t.insert(s) - words.append(s) - result = 0 - for word in words: - result += t.contains(word) - - print("%.2f" % (result/N)) - -# 풀이2 -import sys - -DEBUG = False -def log(message): - if DEBUG: - print(message) - -class Node(): - def __init__(self): - self.is_terminated = False - # self.key = key - # self.data = data - self.children = {} - -class Trie(): - - def __init__(self): - self.head = Node() - - def insert(self, value): - curr_node = self.head - for char in value: - if char not in curr_node.children: - curr_node.children[char] = Node() - curr_node = curr_node.children[char] - curr_node.is_terminated = True - - def search(self, value): - curr_node = self.head - curr_node = curr_node.children[value[0]] - search_num = 1 - for char in value[1:]: - log(char) - log(("curr_node.childen: ", curr_node.children)) - if (len(curr_node.children) != 1) or curr_node.is_terminated: - search_num += 1 - else: - pass - curr_node = curr_node.children[char] - log(("search_num:", search_num)) - return search_num - -# keyb = Trie() - -while 1: - keyb = Trie() - conti = sys.stdin.readline() - # try: - # num_op = int(sys.stdin.readline()) - # except: - # break - - if (conti == ''): - break - num_op = int(conti) - - key_press_num = 0 - press_list = [] - - - for num in range(num_op): - press_list.append(sys.stdin.readline().rstrip()) - keyb.insert(press_list[num]) - for num2 in range(num_op): - key_press_num += keyb.search(press_list[num2]) - print("%.2f" %(key_press_num / num_op)) - - - -# 리스트 트라이? -import sys - -lst_tri = list(map(str, range(ord('a'), ord('z') + 1))) -tri_t = [0] + [-1 for _ in range(len(lst_tri))] - - -def idx(chr_): - return ord(chr_) - ord('a') + 1 - - -def add(tri_, str_): - idx_curr = 0 - for each_ in str_: - idx_temp = idx(each_) - if tri_[idx_curr][idx_temp] == -1: - tri_[idx_curr][idx_temp] = len(tri_) - tri_.append(tri_t.copy()) - tri_[idx_curr][0] += 1 - idx_curr = tri_[idx_curr][idx_temp] - tri_[idx_curr][0] += 1 - - -def find(tri_, str_): - cnt_ = 1 - idx_curr = tri_[0][idx(str_[0])] - for each_ in str_[1:]: - if tri_[idx_curr][0] != 1: - cnt_ += 1 - idx_temp = idx(each_) - idx_curr = tri_[idx_curr][idx_temp] - return cnt_ - - -input_ = sys.stdin.readline() -while input_: - N_ = int(input_) - lst_ = [] - tri_ = [tri_t.copy()] - for _ in range(N_): - str_input = sys.stdin.readline().rstrip() - lst_.append(str_input) - add(tri_, str_input) - cnt_ = 0 - for each_ in lst_: - cnt_ += find(tri_, each_) - print(format(cnt_ / N_, '.2f')) - - input_ = sys.stdin.readline() - -exit() \ No newline at end of file diff --git "a/5671 \355\230\270\355\205\224 \353\260\251 \353\262\210\355\230\270.py" "b/5671 \355\230\270\355\205\224 \353\260\251 \353\262\210\355\230\270.py" deleted file mode 100644 index 64c6239..0000000 --- "a/5671 \355\230\270\355\205\224 \353\260\251 \353\262\210\355\230\270.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - -while 1: - try: - N, M = map(int, input().split()) - except: - break - ans = 0 - for num in range(N,M+1): - cnt = set() - s_num = str(num) - for char in s_num: - cnt.add(char) - if len(s_num) == len(cnt): - ans += 1 - print(ans) diff --git "a/5719\352\261\260\354\235\230 \354\265\234\353\213\250\352\262\275\353\241\234.py" "b/5719\352\261\260\354\235\230 \354\265\234\353\213\250\352\262\275\353\241\234.py" deleted file mode 100644 index 73f9de7..0000000 --- "a/5719\352\261\260\354\235\230 \354\265\234\353\213\250\352\262\275\353\241\234.py" +++ /dev/null @@ -1,71 +0,0 @@ -from collections import deque -import sys -import heapq - -INF = 1e9 - - -def dijkstra(): - q = [] - heapq.heappush(q, (0, s)) - distance[s] = 0 # 출발지 - - while q: # 큐가 비어있지 않다면 - dist, now = heapq.heappop(q) - # 현재 노드가 이미 처리된 적이 있는 노드라면 무시 - if distance[now] < dist: - continue - # 현재 노드와 연결된 다른 인접한 노드들을 확인하면서 거리 업데이트 - for i in graph[now]: - cost = dist + graph[now][i] - if cost < distance[i]: # 해당 지점을 거치는 것이 거리가 짧은 경우 - distance[i] = cost - heapq.heappush(q, (cost, i)) - - -def bfs(): - q = deque() - q.append(d) - while q: - v = q.popleft() - if v == s: # 시작점 도달 - continue # break하면 다른 최단 경로를 확인할 수 없다. - for pre_v, pre_c in r_graph[v]: - if distance[pre_v] + graph[pre_v][v] == distance[v]: - if (pre_v, v) not in remove_List: - remove_List.append((pre_v, v)) - q.append(pre_v) - - -if __name__ == "__main__": - while True: - n, m = map(int, sys.stdin.readline().split()) - if n == 0 and m == 0: # n과 m이 0이면 종료 - break - s, d = map(int, sys.stdin.readline().split()) # 출발지, 도착지 - graph = [dict() for _ in range(n)] - r_graph = [[] for _ in range(n)] - for _ in range(m): - u, v, p = map(int, sys.stdin.readline().split()) # 도로 정보 입력 - graph[u][v] = p - r_graph[v].append((u, p)) # 경로를 추적하기 위해서 역순 저장 - - # 다익스트라 알고리즘을 사용하여 최단 거리 찾기 - distance = [INF] * n - dijkstra() - - # BFS를 사용하여 최단 경로 추적 - remove_List = list() - bfs() - - # 최단 경로 제거 - for u, v in remove_List: - del graph[u][v] - - # 다익스트라 알고리즘을 사용하여 최종 최단 경로 찾기 - distance = [INF] * n - dijkstra() - if distance[d] == INF: # 거의 최단 경로가 없는 경우 - print(-1) - else: - print(distance[d]) \ No newline at end of file diff --git "a/5766 \355\225\240\354\225\204\353\262\204\354\247\200\353\212\224 \354\234\240\353\252\205\355\225\264.py" "b/5766 \355\225\240\354\225\204\353\262\204\354\247\200\353\212\224 \354\234\240\353\252\205\355\225\264.py" deleted file mode 100644 index 046ae31..0000000 --- "a/5766 \355\225\240\354\225\204\353\262\204\354\247\200\353\212\224 \354\234\240\353\252\205\355\225\264.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -while 1: - N, M = map(int, input().split()) - if not N and not M: break - rankers = defaultdict(int) - answer = [] - max_cnt = 0 - for _ in range(N): - a = list(map(int, input().split())) - for num in a: - rankers[num] += 1 - if rankers[num] > max_cnt: - max_cnt = rankers[num] - answer = [num] - elif rankers[num] == max_cnt: - answer.append(num) - for first in answer: - del rankers[first] - answer = [] - max_cnt = 0 - for num in rankers: - if rankers[num] > max_cnt: - max_cnt = rankers[num] - answer = [num] - elif rankers[num] == max_cnt: - answer.append(num) - print(*sorted(answer)) \ No newline at end of file diff --git "a/5972\355\203\235\353\260\260\353\260\260\354\206\241.py" "b/5972\355\203\235\353\260\260\353\260\260\354\206\241.py" deleted file mode 100644 index 5b4a081..0000000 --- "a/5972\355\203\235\353\260\260\353\260\260\354\206\241.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop,heappush - -def dijkstra(start): - min_dists[start] = 0 - heap = [] - heappush(heap,[0,start]) - while heap: - cur_dists, cur_node = heappop(heap) - for next_node,next_dist in graph[cur_node]: - if min_dists[next_node] > cur_dists + next_dist: - min_dists[next_node] = cur_dists + next_dist - heappush(heap,[min_dists[next_node],next_node]) - - -N,M = map(int,input().split()) -graph = {i:[] for i in range(1,N+1)} -min_dists = {i:float('inf') for i in range(1,N+1)} -for _ in range(M): - a,b,c = map(int,input().split()) - graph[a].append((b,c)) - graph[b].append((a,c)) - -dijkstra(1) - -print(min_dists[N]) \ No newline at end of file diff --git "a/6064\354\271\264\354\236\211\353\213\254\353\240\245.py" "b/6064\354\271\264\354\236\211\353\213\254\353\240\245.py" deleted file mode 100644 index 0315b32..0000000 --- "a/6064\354\271\264\354\236\211\353\213\254\353\240\245.py" +++ /dev/null @@ -1,13 +0,0 @@ -def num(m, n, x, y): - while x <= m * n: - if (x - y) % n == 0: - return x - x += m - return -1 - -t = int(input()) -for i in range(t): - m, n, x, y = map(int, input().split()) - print(num(m, n, x, y)) - - diff --git "a/6068 \354\213\234\352\260\204\352\264\200\353\246\254\355\225\230\352\270\260.py" "b/6068 \354\213\234\352\260\204\352\264\200\353\246\254\355\225\230\352\270\260.py" deleted file mode 100644 index 0e1f825..0000000 --- "a/6068 \354\213\234\352\260\204\352\264\200\353\246\254\355\225\230\352\270\260.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -works = [list(map(int, input().split())) for _ in range(N)] -works = sorted(works,key = lambda x: x[1]) -total_time = 0 -min_rest = float('inf') -for time, limit in works: - total_time += time - min_rest = min(min_rest, limit-total_time) - if limit < total_time: - print(-1) - exit() -print(min_rest) \ No newline at end of file diff --git "a/6118\354\210\250\353\260\224\352\274\255\354\247\210.py" "b/6118\354\210\250\353\260\224\352\274\255\354\247\210.py" deleted file mode 100644 index 6d22479..0000000 --- "a/6118\354\210\250\353\260\224\352\274\255\354\247\210.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def BFS(start): - queue = deque() - queue.append(start) - dp_dists[start] = 0 - while queue: - cur_node = queue.popleft() - for next_node in graph[cur_node]: - if dp_dists[next_node]==-1: - dp_dists[next_node] = dp_dists[cur_node] + 1 - queue.append(next_node) - -# 헛간 N개 -# 모든 헛간은 M개의 양방향 길. -# 1번 헛간에서 거리(가장 멀리있는)노드. - -N,M = map(int,input().split()) -graph = {i:[] for i in range(1,N+1)} -dp_dists = {i:-1 for i in range(1,N+1)} -for _ in range(M): - a,b = map(int,input().split()) - graph[a] += [b] - graph[b] += [a] - -# 1부터 bfs방문한곳은 안들르고 dp하나씩 늘려가며. -BFS(1) - -max_dists = 0 -for dist in dp_dists: - if max_dists and max_dists==dp_dists[dist]: - cnt+=1 - if dp_dists[dist] > max_dists: - max_dists = dp_dists[dist] - max_node = dist - cnt=1 - - -print(max_node,max_dists,cnt) \ No newline at end of file diff --git "a/6286\353\246\254\353\262\244\354\247\200 \354\230\244\353\270\214 \355\224\274\353\263\264\353\202\230\354\271\230.py" "b/6286\353\246\254\353\262\244\354\247\200 \354\230\244\353\270\214 \355\224\274\353\263\264\353\202\230\354\271\230.py" deleted file mode 100644 index f280229..0000000 --- "a/6286\353\246\254\353\262\244\354\247\200 \354\230\244\353\270\214 \355\224\274\353\263\264\353\202\230\354\271\230.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(1,int(input())+1): - N = input() - - - i=0 - ans = 0 - while str(ans)[:len(N)] != N: - i+=1 - ans = int(1/(5**(1/2))*(((1+(5**(1/2)))/2)**i-((1-(5**(1/2)))/2)**i)) - - - - print(f"Case #{test}: {i}") \ No newline at end of file diff --git "a/6549\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250\354\227\220\354\204\234 \352\260\200\354\236\245 \355\201\260 \354\247\201\354\202\254\352\260\201\355\230\225.py" "b/6549\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250\354\227\220\354\204\234 \352\260\200\354\236\245 \355\201\260 \354\247\201\354\202\254\352\260\201\355\230\225.py" deleted file mode 100644 index f87a0dc..0000000 --- "a/6549\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250\354\227\220\354\204\234 \352\260\200\354\236\245 \355\201\260 \354\247\201\354\202\254\352\260\201\355\230\225.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -read=sys.stdin.readline - -def maxSize(): - max_size = 0 #최대 넓이 저장 - stack = [] - - for now in range(N): - #왼쪽으로 이어질 수 있는 index - left = now - while stack and stack[-1][0] >= heights[now]: - #pop되었다는 것은 추가 될 직사각형보다 높이가 높다는 의미이다. - #따라서 추가될 직사각형은 pop되는 직사각형의 point값까지 넓어질 수 있다! - #pop된 사각형의 point값으로 left를 업데이트 - h, left = stack.pop() - tmp_size = h * (now-left) - max_size = max(max_size, tmp_size) - stack.append([heights[now],left]) - #탐색이 끝나고 아직 Stack에 남은 직사각형 정보로 maxSize 갱신(남았다는건 얘들이 제일 높이가 낮다는 뜻.) - for h, point in stack: - max_size = max(max_size, (N-point)*h) - - return max_size - -while True: - N, *heights = map(int,read().split()) - if N == 0: - break - print(maxSize()) \ No newline at end of file diff --git "a/6568 \352\267\200\353\217\204 \353\260\230 \353\241\234\354\215\270\354\235\200 \355\201\254\353\246\254\354\212\244\353\247\210\354\212\244\353\202\240 \354\213\254\354\213\254\355\225\230\353\213\244\352\263\240 \355\214\214\354\235\264\354\215\254\354\235\204 \353\247\214\353\223\244\354\227\210\353\213\244.py" "b/6568 \352\267\200\353\217\204 \353\260\230 \353\241\234\354\215\270\354\235\200 \355\201\254\353\246\254\354\212\244\353\247\210\354\212\244\353\202\240 \354\213\254\354\213\254\355\225\230\353\213\244\352\263\240 \355\214\214\354\235\264\354\215\254\354\235\204 \353\247\214\353\223\244\354\227\210\353\213\244.py" deleted file mode 100644 index 926666f..0000000 --- "a/6568 \352\267\200\353\217\204 \353\260\230 \353\241\234\354\215\270\354\235\200 \355\201\254\353\246\254\354\212\244\353\247\210\354\212\244\353\202\240 \354\213\254\354\213\254\355\225\230\353\213\244\352\263\240 \355\214\214\354\235\264\354\215\254\354\235\204 \353\247\214\353\223\244\354\227\210\353\213\244.py" +++ /dev/null @@ -1,109 +0,0 @@ -import sys -input = sys.stdin.readline - -while True: - memory = [0 for _ in range(32)] - cal = 0 - pc = 0 - for i in range(32): - try: - memory[i] = int(input().rstrip(),2) - except EOFError: - exit() - while True: - adress = memory[pc] - cmd = adress//32 - value = adress%32 - pc = (pc + 1)%32 - if cmd == 0: - memory[value] = cal - elif cmd == 1: - cal = memory[value] - elif cmd == 2: - if not cal: - pc = value - elif cmd == 4: - cal = (cal-1)%256 - elif cmd == 5: - cal = (cal+1)%256 - elif cmd == 6: - pc = value - elif cmd == 7: - break - print(bin(cal)[2:].zfill(8)) - -##다른사람 -import sys -i,b,f=int,bin,'%08d' -while 1: - p,a,m=0,0,list(map(lambda x:i(next(sys.stdin),2),range(32))) - if len(m)!=32:break - while 1: - o,x=(lambda s:(lambda s:[i(s[:3],2),i(s[3:],2)])((lambda s:f%(i(b(s)[2:])))(s)))(m[p]) - p=(p+1)%32 - if o==0:m[x]=a - if o==1:a=m[x] - if o==2 and a==0:p=x - if o==4:a=(a+255)%256 - if o==5:a=(a+1)%256 - if o==6:p=x - if o==7:break - print(f%(i(b(a)[2:]))) - - -# 다른사람 - import sys -while 1: - M=[] - for i in range(32): - s=sys.stdin.readline() - if not s: exit() - M.append(s) - p=0;a=0 - while p<32: - i=int(M[p][:3],2);x=int(M[p][3:],2) - p=(p+1)%32 - if i==0: M[x]=format(a,'08b') - elif i==1: a=int(M[x],2) - elif i==2: - if a==0: p=x - elif i==4: a=(a-1)%256 - elif i==5: a=(a+1)%256 - elif i==6: p=x - elif i==7: break - print(format(a,'08b')) - - -# 다른사람 -import sys -input = sys.stdin.readline - -while 1: - m, p, a = [0 for _ in range(32)], 0, 0 - - for i in range(32): - try: - m[i] = int(input().rstrip(), 2) - except: - exit() - - while 1: - o, v = m[p] // 32, m[p] % 32 - p = (p + 1) % 32 - - if o == 0: - m[v] = a - elif o == 1: - a = m[v] - elif o == 2: - p = v if a == 0 else p - elif o == 4: - a = (a - 1) % 256 - elif o == 5: - a = (a + 1) % 256 - elif o == 6: - p = v - elif o == 7: - break - - print(bin(a)[2:].zfill(8)) \ No newline at end of file diff --git "a/6588\352\263\250\353\223\234\353\260\224\355\235\220.py" "b/6588\352\263\250\353\223\234\353\260\224\355\235\220.py" index e1c358f..7fc9d36 100644 --- "a/6588\352\263\250\353\223\234\353\260\224\355\235\220.py" +++ "b/6588\352\263\250\353\223\234\353\260\224\355\235\220.py" @@ -1,23 +1,23 @@ -def isPrime(num): - if num==1: - return False - else: - for i in range(2, int(num**0.5)+1): - if num%i == 0: - return False - return True - - - -while 1: - N = int(input()) - if N==0: - break - else: - for i in range(1, N+1): - if isPrime(i): - A = N-i - if isPrime(A): - print(f'{N} = {i} + {A}') - break +def isPrime(num): + if num==1: + return False + else: + for i in range(2, int(num**0.5)+1): + if num%i == 0: + return False + return True + + + +while 1: + N = int(input()) + if N==0: + break + else: + for i in range(1, N+1): + if isPrime(i): + A = N-i + if isPrime(A): + print(f'{N} = {i} + {A}') + break \ No newline at end of file diff --git "a/6603\353\241\234\353\230\220.py" "b/6603\353\241\234\353\230\220.py" index da5ea2c..77c6052 100644 --- "a/6603\353\241\234\353\230\220.py" +++ "b/6603\353\241\234\353\230\220.py" @@ -1,17 +1,17 @@ -import sys -input = sys.stdin.readline -from itertools import combinations - - -while 1: - k_lists = list(map(int,input().split())) - k = k_lists[0] - - if k ==0: - break - - coms = combinations(k_lists[1:],6) - - for nums in coms: - print(*nums) +import sys +input = sys.stdin.readline +from itertools import combinations + + +while 1: + k_lists = list(map(int,input().split())) + k = k_lists[0] + + if k ==0: + break + + coms = combinations(k_lists[1:],6) + + for nums in coms: + print(*nums) print("") \ No newline at end of file diff --git "a/6603\353\241\234\353\230\220_DFS.py" "b/6603\353\241\234\353\230\220_DFS.py" index 5eac70b..555b1ef 100644 --- "a/6603\353\241\234\353\230\220_DFS.py" +++ "b/6603\353\241\234\353\230\220_DFS.py" @@ -1,19 +1,21 @@ -def dfs(start, depth): - if depth == 6: - for i in range(6): - print(combi[i], end=' ') - print() - return - for i in range(start, len(s)): - combi[depth] = s[i] - dfs(i + 1, depth + 1) - -combi = [0 for i in range(13)] - -while True: - s = list(map(int, input().split())) - if s[0] == 0: - break - del s[0] - dfs(0, 0) +def dfs(start, depth): + if depth == 6: + for i in range(6): + print(combi[i], end=' ') + print() + return + # s[0]을 첫번째에 넣고 s[1]을 두번째에 넣고...dfs로 파고들면서 depth가 완성되면 하나 출력, 줄바꾸고 s[i]가 쭉쭉 밀리다가 depth 6을 더이상 + # 유지 하지 못할 순간이 오면 (dfs마다 start가 점점 늘어나기 때문에 남은 숫자가 6개 미만이 되면 답을 낼 수 없다.) 더이상 출력없이 dfs가 종료. + for i in range(start, len(s)): + combi[depth] = s[i] + dfs(i + 1, depth + 1) + +combi = [0 for _ in range(13)] + +while True: + s = list(map(int, input().split())) + if s[0] == 0: + break + del s[0] + dfs(0, 0) print() \ No newline at end of file diff --git "a/6996\354\227\220\353\204\210\352\267\270\353\236\250.py" "b/6996\354\227\220\353\204\210\352\267\270\353\236\250.py" deleted file mode 100644 index 893e3da..0000000 --- "a/6996\354\227\220\353\204\210\352\267\270\353\236\250.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - - -# chr count해서 charset의 숫자가 전부 0이어야 통과. -for test in range(int(input())): - A,B = input().split() - chrSet = [0]*26 - for chr in A: - chrSet[ord(chr) - 97] +=1 - for chr in B: - chrSet[ord(chr) - 97] -=1 - - print(f'{A} & {B} are anagrams.' if not any(chrSet) else f'{A} & {B} are NOT anagrams.') diff --git "a/7469 K\353\262\210\354\247\270 \354\210\230 _3.py" "b/7469 K\353\262\210\354\247\270 \354\210\230 _3.py" deleted file mode 100644 index 0c70bdd..0000000 --- "a/7469 K\353\262\210\354\247\270 \354\210\230 _3.py" +++ /dev/null @@ -1,96 +0,0 @@ -import sys -from math import ceil, log2 -from bisect import bisect_left - - -# 머지소트 트리 생성 -def infalte_tree(nodes): - height = ceil(log2(len(nodes))) - tree = [list() for _ in range(2 << height)] - end_layer = 1 << height - - for seq, num in enumerate(nodes): - tree[end_layer + seq] = [num] - - end_layer >>= 1 - while end_layer: - for i in range(end_layer): - # 병합정렬 - arr1_idx = arr2_idx = 0 - - while arr1_idx < len(tree[(end_layer + i) * 2]) and arr2_idx < len(tree[(end_layer + i) * 2 + 1]): - if tree[(end_layer + i) * 2][arr1_idx] < tree[(end_layer + i) * 2 + 1][arr2_idx]: - tree[(end_layer + i)].append(tree[(end_layer + i) * 2][arr1_idx]) - arr1_idx += 1 - else: - tree[(end_layer + i)].append(tree[(end_layer + i) * 2 + 1][arr2_idx]) - arr2_idx += 1 - - # 남은 원소 넣어주기 - if arr1_idx != len(tree[(end_layer + i) * 2]): - for e in range(arr1_idx, len(tree[(end_layer + i) * 2])): - tree[(end_layer + i)].append(tree[(end_layer + i) * 2][e]) - - # 남은 원소 넣어주기 - if arr2_idx != len(tree[(end_layer + i) * 2 + 1]): - for e in range(arr2_idx, len(tree[(end_layer + i) * 2 + 1])): - tree[(end_layer + i)].append(tree[(end_layer + i) * 2 + 1][e]) - - end_layer >>= 1 - - return tree - - -def search(tree, tree_len, query_start, query_end): - result = [] - - # bottom-up 방식 - node_start = tree_len + query_start - 1 - node_end = tree_len + query_end - - while node_start < node_end: - if node_start & 1: - result.append(tree[node_start]) - node_start += 1 - if node_end & 1: - result.append(tree[node_end - 1]) - node_end -= 1 - - node_start >>= 1 - node_end >>= 1 - - return result - - -if __name__ == '__main__': - n_node, n_query = map(int, sys.stdin.readline().split()) - nodes = [*map(int, sys.stdin.readline().split())] - tree = infalte_tree(nodes) - tree_len = 1 << ceil(log2(len(nodes))) - - for _ in range(n_query): - src, dst, nth_node = map(int, sys.stdin.readline().split()) - - # 이분탐색 시작 - # 최대값 구하기 - max_val = 1000000001 - # 최소값 구하기 - min_val = -1000000001 - - while min_val < max_val: - middle = (max_val + min_val) >> 1 - cnt = 0 - - # middle 보다 작은 숫자 카운트 - for portion in search(tree, tree_len, src, dst): - cnt += bisect_left(portion, middle) - - # middle 이 너무 큼 - if cnt >= nth_node: - max_val = middle - - # middle 이 너무 작음 - else: - min_val = middle + 1 - - print(max_val - 1) \ No newline at end of file diff --git "a/7469 K\353\262\210\354\247\270 \354\210\230.py" "b/7469 K\353\262\210\354\247\270 \354\210\230.py" deleted file mode 100644 index e04b99c..0000000 --- "a/7469 K\353\262\210\354\247\270 \354\210\230.py" +++ /dev/null @@ -1,40 +0,0 @@ -import bisect -import operator -import sys - - -class MergeSortTreeForKthElem: - def __init__(self, values): - l = [[i] for i, value - in sorted(enumerate(values), key=operator.itemgetter(1))] - self._values = values - self._size = 1 << (len(l) - 1).bit_length() - self._tree = ([[] for _ in range(self._size)] - + l + [[]] * (self._size - len(l))) - for i in range(self._size - 1, 0, -1): - self._tree[i] = self._tree[i * 2] + self._tree[i * 2 + 1] - self._tree[i].sort() - - def kth(self, beg: int, end: int, k: int) -> int: - i = 1 - while i < self._size: - i += i - node = self._tree[i] - t = bisect.bisect_left(node, end) - bisect.bisect_left(node, beg) - if t < k: - k -= t - i += 1 - return self._values[self._tree[i][0]] - - -def main(): - n, m = [int(x) for x in sys.stdin.readline().split()] - nums = [int(x) for x in sys.stdin.readline().split()] - mst = MergeSortTreeForKthElem(nums) - for _ in range(m): - i, j, k = [int(x) for x in sys.stdin.readline().split()] - print(mst.kth(i - 1, j, k)) - - -if __name__ == '__main__': - main() diff --git "a/7469 K\353\262\210\354\247\270 \354\210\230_2.py" "b/7469 K\353\262\210\354\247\270 \354\210\230_2.py" deleted file mode 100644 index c39ef18..0000000 --- "a/7469 K\353\262\210\354\247\270 \354\210\230_2.py" +++ /dev/null @@ -1,63 +0,0 @@ -import bisect -from sys import stdin -input = stdin.readline - -class MergesortTree(): - - def __init__(self, n): - self.n = 2 ** (n - 1).bit_length() - self.data = [[] for _ in range(2 * self.n)] - - def set(self, k, v): - self.data[k + self.n - 1].append(v) - - def build(self): - for k in reversed(range(self.n - 1)): - A, B = self.data[k * 2 + 1], self.data[k * 2 + 2] - i = j = 0 - while i < len(A) and j < len(B): - if A[i] < B[j]: self.data[k].append(A[i]); i += 1 - else: self.data[k].append(B[j]); j += 1 - while i < len(A): self.data[k].append(A[i]); i += 1 - while j < len(B): self.data[k].append(B[j]); j += 1 - - def greater(self, l, r, k): - L = l + self.n - R = r + self.n - ret = 0 - while L < R: - if R & 1: - R -= 1 - ret += bisect.bisect(self.data[R - 1], k) - if L & 1: - ret += bisect.bisect(self.data[L - 1], k) - L += 1 - L >>= 1 - R >>= 1 - return ret - -if __name__ == '__main__': - # input - N, Q = map(int, input().split()) - A = list(map(int, input().split())) - - # construct - mergesort_tree = MergesortTree(N) - for i, s in enumerate(A): - mergesort_tree.set(i, s) - mergesort_tree.build() - - # query - for _ in range(Q): - i, j, k = map(int, input().split()) - # parametric search - L = -1000000001 - R = 1000000000 - while L + 1 < R: - mid = (L + R) // 2 - k_i = mergesort_tree.greater(i - 1, j, mid) - if k_i >= k: - R = mid - else: - L = mid - print(R) \ No newline at end of file diff --git "a/7469K\353\262\210\354\247\270 \354\210\230_short.py" "b/7469K\353\262\210\354\247\270 \354\210\230_short.py" deleted file mode 100644 index 24931ee..0000000 --- "a/7469K\353\262\210\354\247\270 \354\210\230_short.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys - -input = sys.stdin.readline -n, m = map(int, input().split()) -a = list(map(int, input().split())) -arr = sorted((v, i + 1) for i, v in enumerate(a)) -ans = '' -for _ in range(m): - i, j, k = map(int, input().split()) - cnt = 0 - for v, idx in arr: - if i <= idx <= j: - cnt += 1 - - if cnt == k: - ans += str(v) + '\n' - break - -print(ans) \ No newline at end of file diff --git "a/7469K\353\262\210\354\247\270\354\210\230_seg.py" "b/7469K\353\262\210\354\247\270\354\210\230_seg.py" deleted file mode 100644 index fc350d4..0000000 --- "a/7469K\353\262\210\354\247\270\354\210\230_seg.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys; INP = sys.stdin.readline -import heapq -import bisect -import math - -# segment -def init(l, r, node): - if l == r: - tree[node].append(nums[l][1]) - return - mid = (l+r)//2 - init(l, mid, node*2) - init(mid+1, r, node*2+1) - tree[node] = list(heapq.merge(tree[node*2], tree[node*2+1])) - -def query(ql, qr, k, node, nl, nr): - if nl==nr: - return tree[node][0] - mid = (nl+nr)//2 - cnt = bisect.bisect_right(tree[node*2], qr) - bisect.bisect_left(tree[node*2], ql) - - if cnt >= k: - return query(ql, qr, k, node*2, nl, mid) - else: - return query(ql, qr, k-cnt, node*2+1, mid+1, nr) - - -N, M = map(int, INP().split()) -a = list(map(int, INP().split())) -nums = [] -for i in range(N): - nums.append((a[i], i)) -nums.sort() -h = int(math.ceil(math.log2(N))) -tree = [[] for _ in range(1 << (h+1))] -init(0, N-1, 1) - -for i in range(M): - s, e, k = map(int, INP().split()) - print(a[query(s-1,e-1,k,1,0,N-1)]) \ No newline at end of file diff --git "a/7511\354\206\214\354\205\234\353\204\244\355\212\270\354\233\214\355\202\271App.py" "b/7511\354\206\214\354\205\234\353\204\244\355\212\270\354\233\214\355\202\271App.py" deleted file mode 100644 index c201a46..0000000 --- "a/7511\354\206\214\354\205\234\353\204\244\355\212\270\354\233\214\355\202\271App.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - -def union(a,b): #집합이 다를경우 합침 - a=find(a) - b=find(b) - if a= (n-1): - if window_sum in primes: - prime_common[i].add(window_sum) - window_start += 1 - window_sum -= primes[window_start] - print(prime_common) \ No newline at end of file diff --git "a/7562\353\202\230\354\235\264\355\212\270\354\235\230\354\235\264\353\217\231.py" "b/7562\353\202\230\354\235\264\355\212\270\354\235\230\354\235\264\353\217\231.py" index a3ae2f4..294cc88 100644 --- "a/7562\353\202\230\354\235\264\355\212\270\354\235\230\354\235\264\353\217\231.py" +++ "b/7562\353\202\230\354\235\264\355\212\270\354\235\230\354\235\264\353\217\231.py" @@ -1,33 +1,33 @@ -import sys -input = sys.stdin.readline -from collections import deque - -T = int(input()) - -dx = [1,2,1,2,-1,-2,-1,-2] -dy = [-2,-1,2,1,2,1,-2,-1] -queue = deque() - -def BFS(x,y): - queue.append([x,y]) - while queue: - x,y = queue.popleft() - for i in range(8): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx 0: - res += tree[i] - i -= (i & -i) - return res -def update(i, x): - while i < len(tree): - tree[i] += x - i += (i & -i) -result = 0 -for b in B: - update(b, 1) - result += sum(N) - sum(b) -print(result) - - - -########################### -import sys - -def sum(idx): - ans = 0 - while idx > 0: - ans += tree[idx] - idx -= (idx & -idx) - return ans - -def update(idx, val): - while idx < len(a): - tree[idx] += val - idx += (idx & -idx) - -N = int(sys.stdin.readline()) -a = [0] + list(map(int, sys.stdin.readline().split())) -b = [0] + list(map(int, sys.stdin.readline().split())) -tree = [0] * (N+1) -rev_a = [-1] * (1000001) -for i in range(1, len(a)): - rev_a[a[i]] = i - -ans = 0 -for i in range(1, len(b)): - idx = rev_a[b[i]] - ans += sum(N) - sum(idx) - update(idx, 1) - -print(ans) - - - -############################### -import sys -input = sys.stdin.readline -mis = lambda: map(int, input().split()) - -def update(idx, val): - idx = idx + L - 1 - seg[idx] = val - idx //= 2 - while idx: - seg[idx] = seg[idx*2] + seg[idx*2+1] - idx //= 2 - -def query(l, r): - l, r = l + L - 1, r + L - 1 - ret = 0 - while l <= r: - if l%2 == 1: - ret += seg[l] - l += 1 - if r%2 == 0: - ret += seg[r] - r -= 1 - l//=2; r//=2 - return ret - -N = int(input()) -L = 2 ** N.bit_length() -seg = [0] * (2*L) -d = [-1] * 1000001 -org = list(mis()) -for i in range(N): - d[org[i]] = i -ans = 0 -nxt = list(mis()) -for i in range(N): - ans += query(d[nxt[i]], N-1) - update(d[nxt[i]], 1) -print(ans) - - diff --git "a/7662\354\235\264\354\244\221\354\232\260\354\204\240\354\210\234\354\234\204\355\201\220.py" "b/7662\354\235\264\354\244\221\354\232\260\354\204\240\354\210\234\354\234\204\355\201\220.py" deleted file mode 100644 index 2a29600..0000000 --- "a/7662\354\235\264\354\244\221\354\232\260\354\204\240\354\210\234\354\234\204\355\201\220.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappush,heappop - -# key값 관리를 통해 어떤 수를 삽입하면 True 삭제하면 그 키값을 False로 바꿔서 반대편 힙에서 맨앞에 삭제한 수가 나왔을때 미리 -# 삭제를 해주고 삭제연산을 시작한다. -T = int(input()) -for test in range(T): - k = int(input()) - max_heap=[] - min_heap=[] - visited = [False] * 1000001 - for i in range(k): - command,n = input().split() - n=int(n) - if command=='D': - if n==1: - while max_heap and not visited[max_heap[0][1]]: - heappop(max_heap) - if max_heap: - visited[max_heap[0][1]] = False - heappop(max_heap) - else: - while min_heap and not visited[min_heap[0][1]]: - heappop(min_heap) - if min_heap: - visited[min_heap[0][1]] = False - heappop(min_heap) - else: - heappush(max_heap,(-n,i)) - heappush(min_heap,(n,i)) - visited[i] = True - while max_heap and not visited[max_heap[0][1]]: - heappop(max_heap) - while min_heap and not visited[min_heap[0][1]]: - heappop(min_heap) - - if max_heap and min_heap: - print(-max_heap[0][0],min_heap[0][0]) - else: - print("EMPTY") diff --git "a/7795\353\250\271\354\235\204\352\262\203\354\235\270\352\260\200 \353\250\271\355\236\220\352\262\203\354\235\270\352\260\200.py" "b/7795\353\250\271\354\235\204\352\262\203\354\235\270\352\260\200 \353\250\271\355\236\220\352\262\203\354\235\270\352\260\200.py" deleted file mode 100644 index 24f062d..0000000 --- "a/7795\353\250\271\354\235\204\352\262\203\354\235\270\352\260\200 \353\250\271\355\236\220\352\262\203\354\235\270\352\260\200.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_right - -T = int(input()) -for test in range(T): - N,M = map(int,input().split()) - A = list(map(int,input().split())) - B = list(map(int,input().split())) - A.sort() - sum = 0 - for i in B: - sum += len(A)-bisect_right(A,i) - print(sum) \ No newline at end of file diff --git "a/7869\353\221\220\354\233\220.py" "b/7869\353\221\220\354\233\220.py" deleted file mode 100644 index bb0a446..0000000 --- "a/7869\353\221\220\354\233\220.py" +++ /dev/null @@ -1,31 +0,0 @@ -from math import sin,acos,pi,sqrt - -x0, y0, r0, x1, y1, r1 = map(float, input().split()) - - -def area(x0, y0, r0, x1, y1, r1): - d = sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2) - rr0 = r0 * r0 - rr1 = r1 * r1 - # 겹치지 않을 때 - if (d > r1 + r0): - return 0 - # 외접할때 - elif (d <= abs(r0 - r1) and r0 >= r1): - return pi * rr1 - # 내접할때 - elif (d <= abs(r0 - r1) and r0 < r1): - # 작은 원의 영역을 출력 - return pi * rr0 - # 겹치는 부분 계산 / 부채꼴 - 삼각형 - else: - phi = (acos((rr0 + (d * d) - rr1) / (2 * r0 * d))) * 2 - theta = (acos((rr1 + (d * d) - rr0) / (2 * r1 * d))) * 2 - area1 = 0.5 * theta * rr1 - 0.5 * rr1 * sin(theta) - area2 = 0.5 * phi * rr0 - 0.5 * rr0 * sin(phi) - - return area1 + area2 - - -answer = float(round(1000 * area(x0, y0, r0, x1, y1, r1)) / 1000) -print('%.3f' % answer) \ No newline at end of file diff --git a/788_A.py b/788_A.py deleted file mode 100644 index 717e743..0000000 --- a/788_A.py +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - flag = False - left, right = 0, n - 1 - while left < right: - if arr[left] > 0: - while arr[right] > 0 and left < right: - right -= 1 - if left < right: - arr[left] *= -1 - arr[right] *= -1 - else: - break - left += 1 - for i in range(n - 1): - if arr[i] > arr[i + 1]: - print("NO") - break - else: - print("YES") - diff --git a/788_B.py b/788_B.py deleted file mode 100644 index 629f691..0000000 --- a/788_B.py +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - n = int(input()) - s = input() - k, *c = input().split() - c = set(c) - pre, life = 0, 0 - for i in range(n - 1): - if s[i] in c: - if not pre: - pre = i - else: - diff --git a/793_A b/793_A deleted file mode 100644 index 61b2fb0..0000000 --- a/793_A +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - n = int(input()) - s = input().rstrip() - answer = 0 - for i in range(n): - n_s = s[:i] + s[i + 1:] - if n_s == n_s[::-1]: - answer += 1 - print(answer) diff --git a/793_B b/793_B deleted file mode 100644 index f2a875f..0000000 --- a/793_B +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - n = int(input()) - p = list(map(int, input().split())) - index = {i:i for i in range(n)} - for i in range(n): - index[p[i]] = i - for i in range(n): - if p[i] != i: - print(p[i] & p[index[i]]) - break diff --git a/8068water.py b/8068water.py index 12e3aa1..368da53 100644 --- a/8068water.py +++ b/8068water.py @@ -1,41 +1,41 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def BFS(x,y,h): - global result - queue = deque() - queue.append([x,y]) - dx = [0,0,1,-1] - dy = [1,-1,0,0] - out_rain = False - cnt = 1 - visited[x][y] = True - while queue: - x,y = queue.popleft() - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx 3 or y < 0 or y > 3 : - continue - if bfs[x][y] != 0 : - continue - if board[x][y] in st.next : - self.findWord(board, x,y,bfs,word, st.next[board[x][y]]) - bfs[x][y] = 0 - - - def printAnswer(self) : - point = str(self.checkPoint()) - maxWord = self.checkMaxWord() - cnt = str(len(self.result)) - answer = point + " " + maxWord + " " + cnt - return answer - - def checkMaxWord(self) : - temp = sorted(self.result, key= lambda x: (-len(x), x) ) - return temp[0] - - def checkPoint(self) : - point = 0 - for i in self.result : - if len(i) < 3 : - continue - elif len(i) < 5 : - point += 1 - elif len(i) == 5 : - point += 2 - elif len(i) == 6 : - point += 3 - elif len(i) == 7 : - point += 5 - elif len(i) == 8 : - point += 11 - return point - - def solution(self) : - board = self.myBoard() - self.result.clear() - for i in range(4) : - for j in range(4) : - bfs = [[0 for _ in range(4)] for _ in range(4)] - if board[i][j] in self.wordDict : - st = self.wordDict[board[i][j]] - self.findWord(board, i,j, bfs, '' , st) - print(self.printAnswer()) - -if __name__ == "__main__": - N = int(input()) - test = Boggle(N) - test.wordInput() - input().rstrip() - K = int(input()) - test.solution() - for _ in range(K-1) : - input() - test.solution() \ No newline at end of file diff --git "a/9242\355\217\255\355\203\204\355\225\264\354\262\264.py" "b/9242\355\217\255\355\203\204\355\225\264\354\262\264.py" index 1ccda8d..85b6c44 100644 --- "a/9242\355\217\255\355\203\204\355\225\264\354\262\264.py" +++ "b/9242\355\217\255\355\203\204\355\225\264\354\262\264.py" @@ -1,45 +1,45 @@ - -matrix = [input() for _ in range(5)] -N = (len(matrix[0])//4)+1 - -zero = ['***','* *','* *','* *','***'] -one = [' *',' *',' *',' *',' *'] -two = ['***',' *','***','* ','***'] -three = ['***',' *','***',' *','***'] -four = ['* *','* *','***',' *',' *'] -five = ['***','* ','***',' *','***'] -six = ['***','* ','***','* *','***'] -seven = ['***',' *',' *',' *',' *'] -eight = ['***','* *','***','* *','***'] -nine = ['***','* *','***',' *','***'] -nums = [zero,one,two,three,four,five,six,seven,eight,nine] -check = [False]*5 -check_all = [False]*10 -ans_list = [] - -for i in range(N): - for n in range(10): - for j in range(5): - if matrix[j][i*4:i*4+3] == nums[n][j]: - check[j] = True - if all(check): - check_all[n] = True - ans_list.append(n) - check = [False]*5 - if any(check_all): - check_all = [False]*10 - continue - else: - print("BOOM!!") - exit() -ans = 0 -for i in range(1,N+1): - ans += ans_list[-i]*(10**(i-1)) -if ans%6==0: - print("BEER!!") -else: - print("BOOM!!") - - - - + +matrix = [input() for _ in range(5)] +N = (len(matrix[0])//4)+1 + +zero = ['***','* *','* *','* *','***'] +one = [' *',' *',' *',' *',' *'] +two = ['***',' *','***','* ','***'] +three = ['***',' *','***',' *','***'] +four = ['* *','* *','***',' *',' *'] +five = ['***','* ','***',' *','***'] +six = ['***','* ','***','* *','***'] +seven = ['***',' *',' *',' *',' *'] +eight = ['***','* *','***','* *','***'] +nine = ['***','* *','***',' *','***'] +nums = [zero,one,two,three,four,five,six,seven,eight,nine] +check = [False]*5 +check_all = [False]*10 +ans_list = [] + +for i in range(N): + for n in range(10): + for j in range(5): + if matrix[j][i*4:i*4+3] == nums[n][j]: + check[j] = True + if all(check): + check_all[n] = True + ans_list.append(n) + check = [False]*5 + if any(check_all): + check_all = [False]*10 + continue + else: + print("BOOM!!") + exit() +ans = 0 +for i in range(1,N+1): + ans += ans_list[-i]*(10**(i-1)) +if ans%6==0: + print("BEER!!") +else: + print("BOOM!!") + + + + diff --git a/9248 suffix array.py b/9248 suffix array.py deleted file mode 100644 index 55b1167..0000000 --- a/9248 suffix array.py +++ /dev/null @@ -1,480 +0,0 @@ -def suffix_array_IS(str, str_o:int, str_n:int, str_k:int, suffix): - t = [False] * str_n - t[str_n-2] = False - t[str_n-1] = True - - for i in range(str_n-3, -1, -1): - t[i] = str[str_o+i] < str[str_o+i+1] or t[i+1] and str[str_o+i] == str[str_o+i+1] - - bkt = [False] * (str_k+1) - suffix_array_get_buckets(str, str_o, str_n, str_k, bkt, True) - - for i in range(str_n): suffix[i] = -1 - for i in range(1, str_n): - if t[i] and not t[i-1]: - bkt[str[str_o+i]] -= 1 - suffix[bkt[str[str_o+i]]] = i - - suffix_array_induce_suffix_L(t, suffix, str, str_o, str_n, str_k, bkt, False) - suffix_array_induce_suffix_R(t, suffix, str, str_o, str_n, str_k, bkt, True) - - n1 = 0 - for i in range(str_n): - si = suffix[i] - if si > 0 and t[si] and not t[si-1]: - suffix[n1] = suffix[i] - n1 += 1 - - for i in range(n1, str_n): suffix[i] = -1 - name, prev = 0, -1 - for i in range(n1): - pos = suffix[i] - diff = False - for d in range(str_n): - if prev == -1 or str[str_o+pos+d] != str[str_o+prev+d] or t[pos+d] != t[prev+d]: - diff = True - break - elif d > 0: - pd = pos+d - if pd > 0 and t[pd] and not t[pd-1]: break - pd = prev+d - if pd > 0 and t[pd] and not t[pd-1]: break - if diff: - name += 1 - prev = pos - pos //= 2 - suffix[n1+pos] = name-1 - j = str_n-1 - for i in range(str_n-1, n1-1, -1): - if suffix[i] >= 0: - suffix[j] = suffix[i] - j -= 1 - if name < n1: - suffix_array_IS(suffix, str_n-n1, n1, name-1, suffix) - else: - for i in range(n1): - suffix[suffix[str_n-n1+i]] = i - - suffix_array_get_buckets(str, str_o, str_n, str_k, bkt, True) - j = 0 - for i in range(1, str_n): - if t[i] and not t[i-1]: - suffix[str_n-n1+j] = i - j += 1 - for i in range(n1): suffix[i] = suffix[str_n-n1+suffix[i]] - for i in range(n1, str_n): suffix[i] = -1 - for i in range(n1-1, -1, -1): - j = suffix[i] - suffix[i] = -1 - bkt[str[str_o+j]] -= 1 - suffix[bkt[str[str_o+j]]] = j - - suffix_array_induce_suffix_L(t, suffix, str, str_o, str_n, str_k, bkt, False) - suffix_array_induce_suffix_R(t, suffix, str, str_o, str_n, str_k, bkt, True) - -def suffix_array_get_buckets(str, str_o:int, str_n:int, str_k:int, bkt, end:bool): - for i in range(str_k+1): bkt[i] = 0 - for i in range(str_n): bkt[str[str_o+i]] += 1 - s = 0 - for i in range(str_k+1): - s += bkt[i] - if end: bkt[i] = s - else: bkt[i] = s - bkt[i] - -def suffix_array_induce_suffix_L(t, suffix, str, str_o:int, str_n:int, str_k:int, bkt, end:bool): - suffix_array_get_buckets(str, str_o, str_n, str_k, bkt, end) - for i in range(str_n): - j = suffix[i] - 1 - if j >= 0 and not t[j]: - suffix[bkt[str[str_o+j]]] = j - bkt[str[str_o+j]] += 1 - -def suffix_array_induce_suffix_R(t, suffix, str, str_o:int, str_n:int, str_k:int, bkt, end:bool): - suffix_array_get_buckets(str, str_o, str_n, str_k, bkt, end) - for i in range(str_n-1, -1, -1): - j = suffix[i] - 1 - if j >= 0 and t[j]: - bkt[str[str_o+j]] -= 1 - suffix[bkt[str[str_o+j]]] = j - -class SuffixArray: - """ 주어진 문자열 s에 대한 접미사 배열과 LCP 배열을 계산한다. """ - - str = [] - - suffix = [] - """ 접미사 배열. 접미사의 시작 지점을 비교하여 문자열이 앞선 순으로 저장되어 있음. 맨 처음은 항상 빈 문자열임. """ - suffix_pos = [] - """ 접미사의 시작 지점이 주어졌을 때, suffix 배열의 몇 번째 원소인지를 저장하고 있음. `suffix_pos[suffix[i]] == i` """ - lcp = [] - """ `suffix[i]`와 `suffix[i+1]` 사이 공통된 접두사의 길이를 저장하고 있음. """ - - def __init__(self, s:str): - self._alphabets = [''] + sorted(list(set(c for c in s))) - self._alphabets_lookup = dict() - for (i, c) in enumerate(self._alphabets): self._alphabets_lookup[c] = i - - self.str = [self._alphabets_lookup[c] for c in s] + [0] - l = len(self.str) - - self._len = l - - if l > 0: - self._compute_suffix_array() - - self.suffix_pos = [0] * l - self.lcp = [0] * l - - for i in range(l): self.suffix_pos[self.suffix[i]] = i - self._compute_lcp_array() - - def __len__(self): - return self._len-1 - - def _compute_suffix_array(self): - self.suffix = [-1] * self._len - suffix_array_IS(self.str, 0, self._len, len(self._alphabets), self.suffix) - - def _compute_lcp_array(self): - k = 0 - l = self._len - for i in range(l): - if self.suffix_pos[i] == l-1: continue - j = self.suffix[self.suffix_pos[i]+1] - max_k = l - max(i, j) - while k < max_k and self.str[i+k] == self.str[j+k]: k += 1 - self.lcp[self.suffix_pos[i]] = k - k = max(k-1, 0) - -# main code - -arr = SuffixArray(input()) -print(' '.join((str(i + 1) for i in arr.suffix[1:]))) -print('x', ' '.join((str(i) for i in arr.lcp[1:-1]))) - - -# 풀이2 -import sys -sys.setrecursionlimit(9990000) -import collections - -def merge_sort(list): - if len(list) <= 1: - return list - mid = len(list) // 2 - print(mid) - leftList = list[:mid] - rightList = list[mid:] - leftList = merge_sort(leftList) - rightList = merge_sort(rightList) - return merge(leftList, rightList) - - -def merge(left, right): - result = [] - while len(left) > 0 or len(right) > 0: - if len(left) > 0 and len(right) > 0: - if cmp(left[0], right[0]): - result.append(left[0]) - left = left[1:] - else: - result.append(right[0]) - right = right[1:] - elif len(left) > 0: - result.append(left[0]) - left = left[1:] - elif len(right) > 0: - result.append(right[0]) - right = right[1:] - return result - - -def cmp(i,j): - if pos[i] != pos[j]: - return pos[i] < pos[j] - i+=d - j+=d - if ij - - -def quick_sort(arr): - if len(arr) <= 1: - return arr - pivot = arr[len(arr) // 2] - pos_pivot = pos[pivot] - lesser_arr, equal_arr, greater_arr = [], [], [] - for num in arr: - if pos[num] < pos_pivot: - lesser_arr.append(num) - elif pos[num] > pos_pivot: - greater_arr.append(num) - else: - if num+d pos[pivot+d]: - greater_arr.append(num) - else: - equal_arr.append(num) - elif num+d > pivot+d : - lesser_arr.append(num) - elif pivot+d > num+d: - greater_arr.append(num) - else: - equal_arr.append(num) - return quick_sort(lesser_arr) + equal_arr + quick_sort(greater_arr) - -s = sys.stdin.readline().replace('\n','') -l = len(s) -#pos = collections.deque([-1]*l) -#sa = collections.deque([-1]*l) -pos = [-1]*l -sa = [-1]*l - - -for i in range(l): - sa[i] = i - pos[i] = s[i] - -d = 1 -while d<=l: - sa = quick_sort(sa) - #print(sa) - temp=[0]*l - for i in range(l-1): - temp[i+1] = temp[i] + cmp(sa[i], sa[i+1]) - for i in range(l): - pos[sa[i]] = temp[i] - if temp[l-1]==l-1: break - d*=2 - -lcp = ['x']*l - -k = 0 -#print(sa, pos) - -for i in range(l): - k = max(k-1, 0) - if pos[i] == l-1: continue - j = sa[pos[i]+1] - #print(i, j, pos[i], pos[j], sa[i], sa[j]) - while i+k < l and j+k < l and s[i+k] == s[j+k]: - #print(s[i+k], s[j+k]) - k += 1 - lcp[pos[i]] = k - #print(k) - -for i in range(l): - sa[i]=sa[i]+1 -print(' '.join(map(str, sa))) -#print(*sa) -#print(' '.join(map(str, pos))) -print('x '+' '.join(map(str, lcp[:-1]))) - - - -# 3 -from sys import stdin -import time -from functools import cmp_to_key - -def compare_sa(): - for i in range(n-1): - for j in range(0,n-i-1): - swap = False - if pos[sa[j]] != pos[sa[j+1]]: - if pos[sa[j]] > pos[sa[j+1]]: - swap =True - else: - if sa[j]+d pos[sa[j+1]+d]: - swap =True - else: - if sa[j] < sa[j+1]: - swap =True - if swap: - sa[j],sa[j+1] = sa[j+1],sa[j] - -def cmp(i,j): - if pos[i] != pos[j]: - return pos[i] - pos[j] - i += d - j += d - if i len(dp[i][j - 1]): - dp[i][j] = dp[i - 1][j] - else: - dp[i][j] = dp[i][j - 1] -print(len(dp[len_a - 1][len_b - 1])) -print(dp[len_a - 1][len_b - 1]) -# LCS는 2차원 dp를 만들고 같은 문자를 만날경우 대각선 위 dp+1을 해준다. 같은 문자가 아닐경우 왼쪽이나 위쪽거 물려받아 가져온다. \ No newline at end of file diff --git "a/9372\354\203\201\352\267\274\354\235\264\354\235\230 \354\227\254\355\226\211.py" "b/9372\354\203\201\352\267\274\354\235\264\354\235\230 \354\227\254\355\226\211.py" deleted file mode 100644 index 6796b6f..0000000 --- "a/9372\354\203\201\352\267\274\354\235\264\354\235\230 \354\227\254\355\226\211.py" +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.rewadline - -def DFS(v,cnt): - for next_node in graph[v]: - if not visited[next_node]: - visited[next_node] = True - cnt = DFS(next_node,cnt+1) - return cnt - -for test in range(1, int(input())+1): - N, M = map(int, input().split()) - graph = {i:[] for i in range(1, N+1)} - visited = {i:False for i in range(1, N+1)} - for _ in range(M): - a, b = map(int,input().split()) - graph[a] += [b] - graph[b] += [a] - - answer = DFS(1,0) - print(answer) - - # 사실 연결그래프라 최소갯수는 n-1 최대갯수는 n(n-1)이다. \ No newline at end of file diff --git "a/9375\355\214\250\354\205\230\354\231\225 \354\213\240\355\225\264\353\271\210.py" "b/9375\355\214\250\354\205\230\354\231\225 \354\213\240\355\225\264\353\271\210.py" deleted file mode 100644 index 9ce2396..0000000 --- "a/9375\355\214\250\354\205\230\354\231\225 \354\213\240\355\225\264\353\271\210.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -for _ in range(int(input())): - n = int(input()) - clothes = defaultdict(int) - ans = 1 - for _ in range(n): - name, type_c = input().split() - clothes[type_c] += 1 - for cloth in clothes: - ans *= clothes[cloth]+1 - print(ans-1) \ No newline at end of file diff --git "a/9465\354\212\244\355\213\260\354\273\244.py" "b/9465\354\212\244\355\213\260\354\273\244.py" index c7c5a5e..45f8339 100644 --- "a/9465\354\212\244\355\213\260\354\273\244.py" +++ "b/9465\354\212\244\355\213\260\354\273\244.py" @@ -1,16 +1,16 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - value = [list(map(int,input().split())) for _ in range(2)] - dp = [[0]*n for _ in range(2)] - dp[0][0] = value[0][0] - dp[1][0] = value[1][0] - dp[0][1] = dp[1][0] + value[0][1] - dp[1][1] = dp[0][0] + value[1][1] - for j in range(n): - for i in range(2): - dp[i][j] = max(dp[(i+1)%2][j-2],dp[(i+1)%2][j-1])+value[i][j] +import sys +input = sys.stdin.readline + + +for test in range(int(input())): + n = int(input()) + value = [list(map(int,input().split())) for _ in range(2)] + dp = [[0]*n for _ in range(2)] + dp[0][0] = value[0][0] + dp[1][0] = value[1][0] + dp[0][1] = dp[1][0] + value[0][1] + dp[1][1] = dp[0][0] + value[1][1] + for j in range(n): + for i in range(2): + dp[i][j] = max(dp[(i+1)%2][j-2],dp[(i+1)%2][j-1])+value[i][j] print(max(dp[0] + dp[1])) \ No newline at end of file diff --git "a/9466\355\214\200\355\224\204\353\241\234\354\240\235\355\212\270.py" "b/9466\355\214\200\355\224\204\353\241\234\354\240\235\355\212\270.py" deleted file mode 100644 index da61947..0000000 --- "a/9466\355\214\200\355\224\204\353\241\234\354\240\235\355\212\270.py" +++ /dev/null @@ -1,30 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(1000000) - -def find_cycle(cur_node): - global cnt - check_cycle[cur_node] = True - cycle_stack.append(cur_node) - next_node = choices[cur_node] - if not check_cycle[next_node]: - find_cycle(next_node) - else: - if next_node in cycle_stack: - cnt -= len(cycle_stack[cycle_stack.index(next_node):]) -# 프로젝트 팀원 수 제한 없음 팀 하나만 만들어질수도 있음, -# 모든 학생은 1명씩 함께 하고픈 팀원 선택. 자기자신 선택 가능(혼자하고프면) -# 선택지가 사이클을 이루면 한팀. -> 사이클을 이루지 못하는 학생의 수. - -for test in range(int(input())): - n = int(input()) - choices = [0] + list(map(int,input().split())) - check_cycle = {i:False for i in range(1,n+1)} - - cnt=n - for i in range(1,n+1): - if not check_cycle[i]: - cycle_stack=[] - find_cycle(i) - - print(cnt) \ No newline at end of file diff --git "a/9489\354\202\254\354\264\214.py" "b/9489\354\202\254\354\264\214.py" deleted file mode 100644 index 06c82ca..0000000 --- "a/9489\354\202\254\354\264\214.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict,deque - -def BFS(v): - queue=deque() - queue.append(v) - while queue: - N = len(queue) - for _ in range(N): - cur_node = queue.popleft() - if cur_node==k: - return N - for next_node in parents[cur_node]: - queue.append(next_node) - -while 1: - n,k = map(int,input().split()) - if not n and not k: - break - arr = list(map(int,input().split())) - parents = defaultdict(list) - if k==arr[0]: - print(0) - else: - idx=0 - for i in range(1,n): - parents[arr[idx]].append(arr[i]) - if arr[i]==k: - parent_k=arr[idx] - if i k: - x = nodes[x].l - if nodes[x].l != -1: - k -= nodes[nodes[x].l].cnt - if k == 0: - break - k -= 1 - x = nodes[x].r - splay(x) - -def interval(l, r): - global nodes - global root - find_k(l - 1) - x = root - root = nodes[x].r - nodes[root].p = -1 - find_k(r - l) - nodes[root].p = x - nodes[x].r = root - root = x - -def init(): - global nodes - global root - del nodes - nodes = [] - nodes.append(Item()) - nodes.append(Item()) - l = len(nodes) - nodes[l - 2].r = l - 1 - nodes[l - 1].p = l - 2 - nodes[l - 2].cnt = 2 - root = l - 2 - -nodes = [] -init() -t = int(sys.stdin.readline()) -if t > 1: - exit(0) -i = 0 -while i < t: - s = sys.stdin.readline().rstrip() - l = len(s) - init() - find_k(0) - x = nodes[root].l - nodes.append(Item()) - y = len(nodes) - 1 - nodes[root].l = y - nodes[x].p = y - nodes[y].p = root - nodes[y].l = x - nodes[y].it = s[0] - nodes[y].cnt = l + nodes[x].cnt - j = 1 - while j < l: - nodes.append(Item()) - x = len(nodes) - 1 - nodes[x].p = y - nodes[y].r = x - nodes[x].it = s[j] - nodes[x].cnt = l - j; - y = x - j += 1 - update(root) - while 1: - q = sys.stdin.readline() - if q[0] == 'E': - break - if q[0] == 'I': - a, b, c = q.split() - c = int(c) - l = len(b) - find_k(c); - x = nodes[root].l - nodes.append(Item()) - y = len(nodes) - 1 - nodes[root].l = y - nodes[x].p = y - nodes[y].p = root - nodes[y].l = x - nodes[y].it = b[0] - nodes[y].cnt = l + nodes[x].cnt - j = 1 - while j < l: - nodes.append(Item()) - x = len(nodes) - 1 - nodes[x].p = y - nodes[y].r = x - nodes[x].it = b[j] - nodes[x].cnt = l - j; - y = x - j += 1 - update(root) - else: - a, b, c = q.split() - b = int(b) - c = int(c) - j = b - while j <= c: - find_k(j) - print(nodes[root].it, end = '') - j += 1 - print(''); - i += 1 \ No newline at end of file diff --git a/9613GCD.py b/9613GCD.py index f360367..938fac5 100644 --- a/9613GCD.py +++ b/9613GCD.py @@ -1,18 +1,18 @@ -def GCD(i,j): - a, b = i,j - - - while b != 0: - a = a % b - a, b = b, a - return a - -t = int(input()) - -for test in range(t): - n = list(map(int,input().split())) - ans = 0 - for i in range(1,n[0]): - for j in range(i+1,n[0]+1): - ans += GCD(n[i],n[j]) +def GCD(i,j): + a, b = i,j + + + while b != 0: + a = a % b + a, b = b, a + return a + +t = int(input()) + +for test in range(t): + n = list(map(int,input().split())) + ans = 0 + for i in range(1,n[0]): + for j in range(i+1,n[0]+1): + ans += GCD(n[i],n[j]) print(ans) \ No newline at end of file diff --git "a/9655\353\217\214\352\262\214\354\236\204.py" "b/9655\353\217\214\352\262\214\354\236\204.py" deleted file mode 100644 index 1c75b91..0000000 --- "a/9655\353\217\214\352\262\214\354\236\204.py" +++ /dev/null @@ -1,5 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -print('CY' if not N%2 else 'SK') \ No newline at end of file diff --git a/9663N-Queen.py b/9663N-Queen.py deleted file mode 100644 index a6a6d9e..0000000 --- a/9663N-Queen.py +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -check_row = [0 for _ in range(16)] -result = 0 - -# 진입한 cnt값의 check[cnt]값은 지금 검사하는 열의 번호. -# 이 열에 check_row[i]즉 같은 열에 퀸이있거나 -# 열의 차이=행의차이 즉 대각선 상에 퀸이 있으면 false반환. -def isTrue(x): - for i in range(1, x): - if check_row[x] == check_row[i] or abs(check_row[x] - check_row[i]) == x - i: - return False - return True - -def dfs(cnt): - global result - if cnt > n: - result += 1 - else: - # 퀸을 행의 1번부터 n번칸까지 놔보며 놓을 수 있나 확인해본다. 놓을 수 있으면 cnt+1 다음행으로 진입. - for i in range(1, n + 1): - check_row[cnt] = i - if isTrue(cnt): - dfs(cnt + 1) -dfs(1) -print(result) diff --git "a/9933\353\257\274\352\267\240\354\235\264\354\235\230 \353\271\204\353\260\200\353\262\210\355\230\270.py" "b/9933\353\257\274\352\267\240\354\235\264\354\235\230 \353\271\204\353\260\200\353\262\210\355\230\270.py" index 0692672..08c4c4d 100644 --- "a/9933\353\257\274\352\267\240\354\235\264\354\235\230 \353\271\204\353\260\200\353\262\210\355\230\270.py" +++ "b/9933\353\257\274\352\267\240\354\235\264\354\235\230 \353\271\204\353\260\200\353\262\210\355\230\270.py" @@ -1,11 +1,11 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -files = [input().rstrip() for _ in range(N)] - -for i in range(N-1): - for j in range(i,N): - if files[i][::-1] == files[j]: - print(len(files[i]), files[i][len(files[i])//2]) +import sys +input = sys.stdin.readline + +N = int(input()) +files = [input().rstrip() for _ in range(N)] + +for i in range(N-1): + for j in range(i,N): + if files[i][::-1] == files[j]: + print(len(files[i]), files[i][len(files[i])//2]) exit() \ No newline at end of file diff --git a/A.py b/A.py deleted file mode 100644 index d7036d9..0000000 --- a/A.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -t = int(input()) -for _ in range(t): - n = int(input()) - arr = list(map(int, input().split())) - dic = defaultdict(int) - check = False - for num in arr: - if num not in dic: - dic[num] += 1 - else: - check = True - - if 0 in dic: - print(n - dic[0]) - else: - if check: - print(n) - else: - print(n + 1) \ No newline at end of file diff --git a/ATM_beakjooon11399.py b/ATM_beakjooon11399.py index efcdec7..966f5b8 100644 --- a/ATM_beakjooon11399.py +++ b/ATM_beakjooon11399.py @@ -1,23 +1,23 @@ -""" -N개의 회의 -ST, FT 주어짐. -회의실 사용 최대로. -""" - -N = int(input()) -meetings = [[0]*2 for _ in range(N)] - -for i in range(N): - st, ft = map(int, input().split()) - meetings[i][1] = st - meetings[i][0] = ft - -minsort = sorted(meetings) -minft = minsort[0][0] -cnt=1 -for i in range(N): - if minft <= minsort[i][1]: - cnt+=1 - minft = minsort[i][0] - -print(minsort) +""" +N개의 회의 +ST, FT 주어짐. +회의실 사용 최대로. +""" + +N = int(input()) +meetings = [[0]*2 for _ in range(N)] + +for i in range(N): + st, ft = map(int, input().split()) + meetings[i][1] = st + meetings[i][0] = ft + +minsort = sorted(meetings) +minft = minsort[0][0] +cnt=1 +for i in range(N): + if minft <= minsort[i][1]: + cnt+=1 + minft = minsort[i][0] + +print(minsort) diff --git a/B.py b/B.py deleted file mode 100644 index 295b455..0000000 --- a/B.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - n = int(input()) - s = list(input()) - answer = 0 - tmp = 1 - for i in range(len(s) - 1): - if s[i + 1] == s[i]: - tmp += 1 - else: - if tmp & 1: - s[i] = str(int(s[i]) ^ 1) - answer += 1 - tmp = 2 - else: - tmp = 1 - print(answer) diff --git a/B2.py b/B2.py deleted file mode 100644 index 3900e72..0000000 --- a/B2.py +++ /dev/null @@ -1,26 +0,0 @@ -import sys -input = sys.stdin.readline - -for _ in range(int(input())): - n = int(input()) - s = list(input()) - answer = 0 - section = 1 - tmp = 1 - for i in range(len(s) - 1): - if s[i + 1] == s[i]: - tmp += 1 - else: - if i == 0: - s[i], s[i + 1] = s[i + 2], s[i + 2] - answer += 1 - tmp += 1 - elif tmp & 1: - s[i] = str(int(s[i]) ^ 1) - answer += 1 - tmp = 2 - else: - tmp = 1 - section += 1 - - print(answer, section) diff --git "a/BFS\355\203\220\354\203\211.cpp" "b/BFS\355\203\220\354\203\211.cpp" deleted file mode 100644 index 9c1d918..0000000 --- "a/BFS\355\203\220\354\203\211.cpp" +++ /dev/null @@ -1,164 +0,0 @@ -#include - - -#define LIMITL 256 -#define TRUE 1 -#define START 1 -#define GOAL 999 - -struct node { - int nodeid; - int parentid; -}; - -struct node openlist[LIMITL]; -int openlistep = 0; -struct node closedlist[LIMITL]; -int closedlistep = 0; - -void initlist(); - -void printlist(); - -void expand(int id); - -void movetofirst(); - -int check(int id); - -void printroute(int id); - -int main() { - - initlist(); - - printlist(); - - while (TRUE) { - if (openlistep == 0) { - - printf("ǥ 带 ã ϴ\n"); - break; - } - - - if (openlist[0].nodeid == GOAL) { - printf("\nǥ 带 ãҽϴ\n"); - printf("%d[%d]", openlist[0].nodeid, - openlist[0].parentid); - printroute(openlist[0].parentid); - break; - } - - expand(openlist[0].nodeid); - - movetofirst(); - - printlist(); - - } - - return 0; -} - - -void printroute(int id) -{ - int i; - for(i = 0;i < closedlistep; ++i) - if (closedlist[i].nodeid == id) { - printf("<-%d[%d]", closedlist[i].nodeid, - closedlist[i].parentid); - break; - } - - if (closedlist[i].parentid != 0) - printroute(closedlist[i].parentid); - printf("\n"); -} - -int check(int id) -{ - int i; - int res = 0; - - for (i = 0;i < openlistep;++i) - if (openlist[i].nodeid == id) - res = TRUE; - - for (i = 0; i < closedlistep; ++i) - if (closedlist[i].nodeid == id) - res = TRUE; - return res; -} - -void removefirst() { - int i; - for (i = 0;i < openlistep;++i) - openlist[i] = openlist[i + 1]; - --openlistep; -} - - -void movetofirst() -{ - closedlist[closedlistep++] = openlist[0]; - removefirst(); -} - -void expand(int id) -{ - - int tree[][5] = { - {1,2,3,5}, - {2,4}, - {3,6,7}, - {5,4,8}, - {6,5,7}, - {8,7,999}, - {0} - }; - int i = 0; - int j; - - while (tree[i][0] != 0){ - if (tree[i][0] == id) { - - for (j = 1; tree[i][j] != 0; ++j) { - if (check(tree[i][j]) != TRUE) { - openlist[openlistep].nodeid = tree[i][j]; - openlist[openlistep++].parentid = id; - } - } - break; - } - ++i; - } -} - -void initlist() -{ - openlist[0].nodeid = START; - openlist[0].parentid = 0; - ++openlistep; -} - - -void printlist() -{ - - int i; - - printf("\n¸Ʈ "); - for (i = 0;i< openlistep; ++i) - printf("%d[%d]", openlist[i].nodeid, - openlist[i].parentid); - - printf("\n"); - - printf("Ŭ Ʈ "); - for ( i=0; i < closedlistep; ++i) - printf("%d[%d]", closedlist[i].nodeid, - closedlist[i].parentid); - printf("\n"); -} \ No newline at end of file diff --git "a/BOJ/1283 \353\213\250\354\266\225\355\202\244\354\247\200\354\240\225/1283 \353\213\250\354\266\225\355\202\244\354\247\200\354\240\225.py" "b/BOJ/1283 \353\213\250\354\266\225\355\202\244\354\247\200\354\240\225/1283 \353\213\250\354\266\225\355\202\244\354\247\200\354\240\225.py" deleted file mode 100644 index 9fad887..0000000 --- "a/BOJ/1283 \353\213\250\354\266\225\355\202\244\354\247\200\354\240\225/1283 \353\213\250\354\266\225\355\202\244\354\247\200\354\240\225.py" +++ /dev/null @@ -1,43 +0,0 @@ -import sys -from collections import defaultdict -input = sys.stdin.readline -dab = [] -dic = defaultdict(int) -for _ in range(int(input())): - s = input().split() - tmp = [] - cnt = 0 - tf = False - for i in s: - if tf: - tmp.append(i) - continue - if i[0].upper() in dic: - cnt += 1 - tmp.append(i) - elif i[0].upper() not in dic and not tf: - tmp.append(i.replace(i[0], '['+i[0]+']', 1)) - dic[i[0].upper()] += 1 - tf = True - - if cnt == len(s): - tmp = [] - for i in s: - cnt = 0 - if tf: - tmp.append(i) - continue - for j in i: - if j.upper() in dic: - cnt += 1 - if cnt == len(i): - tmp.append(i) - elif not tf and j.upper() not in dic: - tf = True - dic[j.upper()] += 1 - tmp.append(i.replace(j, '['+j+']', 1)) - continue - dab.append(' '.join(tmp)) - -for i in dab: - print(i) \ No newline at end of file diff --git "a/BOJ/FFT/13575 \353\263\264\354\204\235\352\260\200\352\262\214/13575 \353\263\264\354\204\235\352\260\200\352\262\214.cpp" "b/BOJ/FFT/13575 \353\263\264\354\204\235\352\260\200\352\262\214/13575 \353\263\264\354\204\235\352\260\200\352\262\214.cpp" deleted file mode 100644 index cb165eb..0000000 --- "a/BOJ/FFT/13575 \353\263\264\354\204\235\352\260\200\352\262\214/13575 \353\263\264\354\204\235\352\260\200\352\262\214.cpp" +++ /dev/null @@ -1,86 +0,0 @@ -#define _USE_MATH_DEFINES -#include -#include -#include -#include -using namespace std; - -typedef complex cpx; -typedef vector vec; - -const double pi = acos(-1); - -void fft(vec &a, bool inv){ - int n = a.size(); - for(int i=1, j=0; i> 1; - for(; bit<=j; bit>>=1) j -= bit; - j += bit; - if(i < j) swap(a[i],a[j]); - } - for(int len=2; len<=n; len<<=1){ - double ang = 2 * M_PI / len; - if(inv) ang = -ang; - cpx w(cos(ang), sin(ang)); - for(int i=0; i mul(const vector &a, const vector &b){ - vec aa(a.begin(), a.end()), bb(b.begin(), b.end()); - int n = 1; while(n <= max(a.size(), b.size())) n <<= 1; - aa.resize(n), bb.resize(n); - fft(aa, 0), fft(bb, 0); - for(int i=0; i ret(n); - for (int i = 0; i < n; i++){ - ret[i] = round(aa[i].real()); - if(ret[i]) ret[i] = 1; - } - //while(ret.size() > 10 && ret.back() == 0) ret.pop_back(); - return ret; -} - -vector ori(1024); - -vector pw(vector a, int b){ - /*vector ret = ori; - for(int i=1; i ret = ori; b--; - while(b){ - if(b & 1) ret = mul(ret, a); - b >>= 1; a = mul(a, a); - } - return ret; -} - -int main(){ - ios_base::sync_with_stdio(0); cin.tie(0); - int n, k; cin >> n >> k; - for (int i = 1; i <= n; i++){ - int t; cin >> t; - ori[t] = 1; - } - vector res = pw(ori, k); - for (int i = 0; i < res.size(); i++){ - if (res[i]) cout << i << " "; - } -} \ No newline at end of file diff --git "a/BOJ/FFT/13575 \353\263\264\354\204\235\352\260\200\352\262\214/13575 \353\263\264\354\204\235\352\260\200\352\262\214.py" "b/BOJ/FFT/13575 \353\263\264\354\204\235\352\260\200\352\262\214/13575 \353\263\264\354\204\235\352\260\200\352\262\214.py" deleted file mode 100644 index 8febe43..0000000 --- "a/BOJ/FFT/13575 \353\263\264\354\204\235\352\260\200\352\262\214/13575 \353\263\264\354\204\235\352\260\200\352\262\214.py" +++ /dev/null @@ -1,69 +0,0 @@ -def power(a, b, mod): - result = 1 - while b: - if b % 2: - result *= a - result %= mod - b //= 2 - a *= a - a %= mod - return result - - -def fft(a, inv=False): - n = len(a) - y = 0 - for x in range(1, n): - rev = n // 2 - while y >= rev: - y -= rev - rev //= 2 - y += rev - if x < y: - a[x], a[y] = a[y], a[x] - step = 2 - while step <= n: - half = step // 2 - u = power(3, div // step, div) - if inv: - u = power(u, div - 2, div) - for x in range(0, n, step): - w = 1 - for y in range(x, x + half): - v = a[y + half] * w - a[y + half] = (a[y] - v) % div - a[y] += v - a[y] %= div - w *= u - w %= div - step *= 2 - if inv: - c = div - (div - 1) // n - for idx in range(n): - a[idx] = (a[idx] * c) % div - - -div = 469762049 -nn = 1 << 20 -arr = [0] * nn -n, k = map(int, input().split()) -for i in map(int, input().split()): - arr[i] = 1 -k -= 1 -fft(arr) -ans = arr[:] -while k: - if k % 2: - for i in range(nn): - ans[i] *= arr[i] - ans[i] %= div - k //= 2 - for i in range(nn): - arr[i] *= arr[i] - arr[i] %= div -fft(ans, inv=True) -res = [] -for i in range(1, nn): - if ans[i]: - res.append(i) -print(*res) diff --git "a/BOJ/bfs/1022 \354\206\214\354\232\251\353\217\214\354\235\264 \354\235\264\354\201\230\352\262\214 \354\266\234\353\240\245\355\225\230\352\270\260/1022 \354\206\214\354\232\251\353\217\214\354\235\264 \354\230\210\354\201\230\352\262\214 \354\266\234\353\240\245\355\225\230\352\270\260.py" "b/BOJ/bfs/1022 \354\206\214\354\232\251\353\217\214\354\235\264 \354\235\264\354\201\230\352\262\214 \354\266\234\353\240\245\355\225\230\352\270\260/1022 \354\206\214\354\232\251\353\217\214\354\235\264 \354\230\210\354\201\230\352\262\214 \354\266\234\353\240\245\355\225\230\352\270\260.py" deleted file mode 100644 index abe1be8..0000000 --- "a/BOJ/bfs/1022 \354\206\214\354\232\251\353\217\214\354\235\264 \354\235\264\354\201\230\352\262\214 \354\266\234\353\240\245\355\225\230\352\270\260/1022 \354\206\214\354\232\251\353\217\214\354\235\264 \354\230\210\354\201\230\352\262\214 \354\266\234\353\240\245\355\225\230\352\270\260.py" +++ /dev/null @@ -1,86 +0,0 @@ -import sys -read = sys.stdin.readline -maxAns = -1 -def selectRegion(r, c): - if r > 0 and c > 0: - return 0 - if r > 0 and c <= 0: - return 1 - if r <= 0 and c <= 0: - return 2 - if r <=0 and c > 0: - return 3 - -def cornerVal(n): - temp = [] - m = (2*n+1)**2 - for i in range(4): - temp.append(m - 2 * n * i) - return temp - -def cal(r, c): - global maxAns - - case = selectRegion(r, c) - bigger = max(abs(r), abs(c)) - corners = cornerVal(bigger) - - if case == 0: - if abs(r) == bigger: # (3,2) - diff = bigger - abs(c) - ans = corners[0] - diff - else: # (2,3) - diff = bigger - abs(r) - ans = corners[3] - (2 * bigger) + diff - - elif case == 1: - if abs(r) == bigger: # (3,-2) - diff = bigger - abs(c) - ans = corners[1] + diff - else: # (2,-3) - diff = bigger - abs(r) - ans = corners[1] - diff - - elif case == 2: - if abs(r) == bigger: # (-3,-2) - diff = bigger - abs(c) - ans = corners[2] - diff - else: # (-2,-3) - diff = bigger - abs(r) - ans = corners[2] + diff - - else: - if abs(r) == bigger: # (-3,2) - diff = bigger - abs(c) - ans = corners[3] + diff - else: # (-2,3) - diff = bigger - abs(r) - ans = corners[3] - diff - if ans > maxAns: - maxAns = ans - return ans - -r1, c1, r2, c2 = map(int, read().split()) - -R = r2-r1+1 -C = c2-c1+1 -D = [[0 for _ in range(C)] for _ in range(R)] - - - -for i in range(R): - for j in range(C): - D[i][j] = str(cal(r1 + i, c1 + j)) -strLen = len(str(maxAns)) - - -for i in range(R): - for j in range(C): - temp = D[i][j] - D[i][j] = ' ' * (strLen - len(temp)) - D[i][j] += temp - -for d in D: - for i in d: - print(i, end = ' ') - print() diff --git "a/BOJ/bfs/10711 \353\252\250\353\236\230\354\204\261/10711 \353\252\250\353\236\230\354\204\261.py" "b/BOJ/bfs/10711 \353\252\250\353\236\230\354\204\261/10711 \353\252\250\353\236\230\354\204\261.py" deleted file mode 100644 index 8b4f9b0..0000000 --- "a/BOJ/bfs/10711 \353\252\250\353\236\230\354\204\261/10711 \353\252\250\353\236\230\354\204\261.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def make_water(H, W): - waters = deque() - for i in range(H): - for j in range(W): - if sands[i][j].isnumeric(): - sands[i][j] = int(sands[i][j]) - else: - sands[i][j] = 0 - waters.append((i, j)) - - return waters - - -H, W = map(int, input().split()) -sands = [list(map(str, input())) for _ in range(H)] -waters = make_water(H, W) - -answer = 0 -cnts = [[0] * W for _ in range(H)] -delta = ((-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)) - -while waters: - x, y = waters.popleft() - for dx, dy in delta: - nx = x + dx - ny = y + dy - if 0 <= nx < H and 0 <= ny < W: - if sands[nx][ny]: - sands[nx][ny] -= 1 - if not sands[nx][ny]: - waters.append((nx, ny)) - cnts[nx][ny] = cnts[x][y] + 1 - answer = max(answer, cnts[nx][ny]) - -print(answer) \ No newline at end of file diff --git "a/BOJ/bfs/1162 \353\217\204\353\241\234\355\217\254\354\236\245/1162 \353\217\204\353\241\234\355\217\254\354\236\245.py" "b/BOJ/bfs/1162 \353\217\204\353\241\234\355\217\254\354\236\245/1162 \353\217\204\353\241\234\355\217\254\354\236\245.py" deleted file mode 100644 index 5103ad6..0000000 --- "a/BOJ/bfs/1162 \353\217\204\353\241\234\355\217\254\354\236\245/1162 \353\217\204\353\241\234\355\217\254\354\236\245.py" +++ /dev/null @@ -1,47 +0,0 @@ -import sys -import heapq - -INF = sys.maxsize -input = sys.stdin.readline -N, M, K = map(int, input().split()) -K += 1 - -# N * K 배열로 만듦 -vstd = [[False] * K for _ in range(N)] -dist = [[INF] * K for _ in range(N)] - -adj = [[] for _ in range(N)] - -# 양방향 도로이기 때문에 u -> v, v -> u로 도로를 추가 -for _ in range(M): - u, v, w = map(int, input().split()) - adj[u - 1].append((v - 1, w)) - adj[v - 1].append((u - 1, w)) - -h = [] -heapq.heappush(h, (0, 0, K - 1)) - -# 서울에서의 모든 시간은 0으로 초기화 -for i in range(K): - dist[0][i] = 0 - -while h: - _, curr, k = heapq.heappop(h) - - #현재 도시에서 k번 포장한 최단거리를 이미 방문했다면 continue - if vstd[curr][k]: - continue - vstd[curr][k] = True - - for nxt, d in adj[curr]: - if dist[curr][k] + d < dist[nxt][k]: - dist[nxt][k] = dist[curr][k] + d - heapq.heappush(h, (dist[nxt][k], nxt, k)) - # 포장을 할 수 있고 다음 도로보다 시간이 짧다면 포장해줌 - if k > 0: - if dist[nxt][k - 1] > dist[curr][k]: - dist[nxt][k - 1] = dist[curr][k] - heapq.heappush(h, (dist[nxt][k - 1], nxt, k - 1)) - -# 포천에서의 1-k번 사용했을 때의 최소 시간 중 최소값이 결과값 -print(min(dist[-1])) \ No newline at end of file diff --git "a/BOJ/bfs/1219 \354\230\244\353\257\274\354\213\235\354\235\230 \352\263\240\353\257\274/1219 \354\230\244\353\257\274\354\213\235\354\235\230 \352\263\240\353\257\274.py" "b/BOJ/bfs/1219 \354\230\244\353\257\274\354\213\235\354\235\230 \352\263\240\353\257\274/1219 \354\230\244\353\257\274\354\213\235\354\235\230 \352\263\240\353\257\274.py" deleted file mode 100644 index 66309fd..0000000 --- "a/BOJ/bfs/1219 \354\230\244\353\257\274\354\213\235\354\235\230 \352\263\240\353\257\274/1219 \354\230\244\353\257\274\354\213\235\354\235\230 \352\263\240\353\257\274.py" +++ /dev/null @@ -1,48 +0,0 @@ -def check(E): - visit = [0] * N - q = [E] - while q: - a = q.pop() - if a == End: - return True - visit[a] = 1 - for b, c in network[a]: - if visit[b] == 0: - q.append(b) - return False - - -def BF(): - for i in range(N+1): - if sections[End] == -float('inf') and i == N: - print('gg') - return - for j in range(N): - if sections[j] == -float('inf'): - continue - for E, T in network[j]: - if sections[j] + T > sections[E]: - sections[E] = sections[j] + T - if i == N: - if check(E): - print('Gee') - return False - return True - - -N, Start, End, M = map(int, input().split()) -sections = [-float('inf')] * N -network = [[] for i in range(N)] -for i in range(M): - S, E, T = map(int, input().split()) - network[S].append([E, T]) -salary = list(map(int, input().split())) -sections[Start] = salary[Start] -for i in range(len(salary)): - for j in range(len(network[i])): - for k in range(len(salary)): - if network[i][j][0] == k: - network[i][j][1] = salary[k] - network[i][j][1] - -if BF(): - print(sections[End]) \ No newline at end of file diff --git "a/BOJ/bfs/1260 BFS DFS/1260 DFS\354\231\200 BFS.py" "b/BOJ/bfs/1260 BFS DFS/1260 DFS\354\231\200 BFS.py" deleted file mode 100644 index 2d1e885..0000000 --- "a/BOJ/bfs/1260 BFS DFS/1260 DFS\354\231\200 BFS.py" +++ /dev/null @@ -1,46 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - - -def DFS(v): - path.append(v) - check[v] = True - for i in graph[v]: - if check[i]==False: - DFS(i) - - -def BFS(v): - queue = [v] - path.append(v) - check[v] = True - while queue: - v = queue.pop(0) - for i in graph[v]: - if check[i] ==False: - queue.append(i) - path.append(i) - check[i] = True - - -N,M,V = list(map(int,input().split())) -graph = defaultdict(list) - -for _ in range(M): - a,b = map(int,input().split()) - graph[a] += [b] - graph[b] += [a] - -for i in range(1,N+1): - graph[i].sort() - -path = [] -check = [True] +[False]*(N) -DFS(V) -print(*path) - -check = [True] +[False]*(N) -path.clear() -BFS(V) -print(*path) \ No newline at end of file diff --git "a/BOJ/bfs/18404 \355\230\204\353\252\205\355\225\234 \353\202\230\354\235\264\355\212\270/18404 \355\230\204\353\252\205\355\225\234 \353\202\230\354\235\264\355\212\270.py" "b/BOJ/bfs/18404 \355\230\204\353\252\205\355\225\234 \353\202\230\354\235\264\355\212\270/18404 \355\230\204\353\252\205\355\225\234 \353\202\230\354\235\264\355\212\270.py" deleted file mode 100644 index d3ea681..0000000 --- "a/BOJ/bfs/18404 \355\230\204\353\252\205\355\225\234 \353\202\230\354\235\264\355\212\270/18404 \355\230\204\353\252\205\355\225\234 \353\202\230\354\235\264\355\212\270.py" +++ /dev/null @@ -1,23 +0,0 @@ -from collections import deque - -def bfs(y, x): - q = deque() - q.append((y, x)) - graph[y][x] = 0 - while q: - y, x = q.popleft() - for dy, dx in d: - Y, X = y+dy, x+dx - if 0 <= Y < N and 0 <= X < N and graph[Y][X] == -1: - q.append((Y, X)) - graph[Y][X] = graph[y][x]+1 - -N, M = map(int, input().split()) -graph = [[-1]*N for _ in range(N)] -sy, sx = map(int, input().split()) -e_li = [list(map(int, input().split())) for _ in range(M)] -d = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)] -bfs(sy-1, sx-1) -for y, x in e_li: - print(graph[y-1][x-1], end=' ') -print() \ No newline at end of file diff --git "a/BOJ/bfs/1848 \353\217\231\352\265\264\355\203\220\355\227\230/1848 \353\217\231\352\265\264\355\203\220\355\227\230.cpp" "b/BOJ/bfs/1848 \353\217\231\352\265\264\355\203\220\355\227\230/1848 \353\217\231\352\265\264\355\203\220\355\227\230.cpp" deleted file mode 100644 index 8f091b2..0000000 --- "a/BOJ/bfs/1848 \353\217\231\352\265\264\355\203\220\355\227\230/1848 \353\217\231\352\265\264\355\203\220\355\227\230.cpp" +++ /dev/null @@ -1,91 +0,0 @@ -#include -using namespace std; -typedef long long int ll; -typedef pair pii; -#define ff first -#define ss second - -vector edg[20202]; -ll dis[303030]; -ll inf=1e18; - -ll in[303030]; -ll out[303030]; - -vector lnk; -ll ans=1e18; - -void dijk1(ll bit){ - priority_queue,greater> pq; - for(auto x : lnk) - if(x&(1 << bit)){ - pq.push({in[x],x}); - dis[x]=in[x]; - } - while(!pq.empty()){ - auto x = pq.top(); pq.pop(); - if(dis[x.ss],greater> pq; - for(auto x : lnk) - if( ! (x&(1 << bit))){ - pq.push({in[x],x}); - dis[x]=in[x]; - } - - while(!pq.empty()){ - auto x = pq.top(); pq.pop(); - if(dis[x.ss] d + w: - dis[v] = d + w - heapq.heappush(q, (dis[v], v)) - -def dijkstra2(bit): - q = [] - for l in lnk: - node, _in, _ = l - if not (node & (1 << bit)): - heapq.heappush(q, (_in, node)) - dis[node] = _in - - while q: - d, u = heapq.heappop(q) - if dis[u] < d: - continue - for v, w in graph[u]: - if dis[v] > d + w: - dis[v] = d + w - heapq.heappush(q, (dis[v], v)) - -if __name__ == '__main__': - n, m = map(int, input().split()) - graph = [[] for _ in range(n+1)] - lnk = [] - for _ in range(m): - a, b, c, d = map(int, input().split()) - - if a != 1 and b != 1: - graph[a].append((b, c)) - graph[b].append((a, d)) - - if a == 1 and b != 1: - lnk.append((b, c, d)) # (node, in, out) - if a != 1 and b == 1: - lnk.append((a, d, c)) - - ans = float('inf') - for i in range(13): - dis = [float('inf') for _ in range(n+1)] - dijkstra(i) - for l in lnk: - node, _, _out = l - if not (node & (1 << i)): - ans = min(ans, _out + dis[node]) - - dis = [float('inf') for _ in range(n+1)] - dijkstra2(i) - for l in lnk: - node, _, _out = l - if node & (1 << i): - ans = min(ans, _out + dis[node]) - - print(ans) \ No newline at end of file diff --git "a/BOJ/bfs/2573 \353\271\231\354\202\260/2573 \353\271\231\354\202\260.py" "b/BOJ/bfs/2573 \353\271\231\354\202\260/2573 \353\271\231\354\202\260.py" deleted file mode 100644 index df0e4b1..0000000 --- "a/BOJ/bfs/2573 \353\271\231\354\202\260/2573 \353\271\231\354\202\260.py" +++ /dev/null @@ -1,57 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -dx = [1, -1, 0, 0] -dy = [0, 0, 1, -1] - - -def bfs(x, y): - queue = deque() - queue.append((x, y)) - visited[x][y] = 1 - - while queue: - x, y = queue.popleft() - temp = 0 - - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - - if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny]: - if arr[nx][ny] != 0: - queue.append((nx, ny)) - visited[nx][ny] = 1 - else: - temp += 1 - - new_arr[x][y] -= temp - new_arr[x][y] = max(0, new_arr[x][y]) - return - - -n, m = map(int, input().split()) -arr = [list(map(int, input().split())) for _ in range(n)] -time = 0 - -while True: - visited = [[0 for _ in range(m)] for _ in range(n)] - new_arr = [row[:] for row in arr] - cnt = 0 - - for i in range(n): - for j in range(m): - if arr[i][j] != 0 and not visited[i][j]: - bfs(i, j) - cnt += 1 - if cnt >= 2: - break - elif cnt == 0: - time = 0 - break - - arr = new_arr - time += 1 - -print(time) \ No newline at end of file diff --git "a/BOJ/bfs/2583 \354\230\201\354\227\255\352\265\254\355\225\230\352\270\260/2583 \354\230\201\354\227\255\352\265\254\355\225\230\352\270\260.py" "b/BOJ/bfs/2583 \354\230\201\354\227\255\352\265\254\355\225\230\352\270\260/2583 \354\230\201\354\227\255\352\265\254\355\225\230\352\270\260.py" deleted file mode 100644 index efc20db..0000000 --- "a/BOJ/bfs/2583 \354\230\201\354\227\255\352\265\254\355\225\230\352\270\260/2583 \354\230\201\354\227\255\352\265\254\355\225\230\352\270\260.py" +++ /dev/null @@ -1,31 +0,0 @@ -m, n, k = map(int, input().split()) -s = [[0] * n for i in range(m)] -dx = [0, 0, -1, 1] -dy = [-1, 1, 0, 0] -cnt = [] -for i in range(k): - x1, y1, x2, y2 = map(int, input().split()) - for j in range(y1, y2): - for k in range(x1, x2): - s[j][k] = 1 -for i in range(m): - for j in range(n): - if s[i][j] == 0: - count = 1 - s[i][j] = 1 - queue = [[i, j]] - while queue: - x, y = queue[0][0], queue[0][1] - del queue[0] - for k in range(4): - x1 = x + dx[k] - y1 = y + dy[k] - if 0 <= x1 < m and 0 <= y1 < n and s[x1][y1] == 0: - s[x1][y1] = 1 - count += 1 - queue.append([x1, y1]) - cnt.append(count) -print(len(cnt)) -cnt.sort() -for i in cnt: - print(i, end=' ') \ No newline at end of file diff --git "a/BOJ/bfs/2589 \353\263\264\353\254\274\354\204\254/2589 \353\263\264\353\254\274\354\204\254.py" "b/BOJ/bfs/2589 \353\263\264\353\254\274\354\204\254/2589 \353\263\264\353\254\274\354\204\254.py" deleted file mode 100644 index a486977..0000000 --- "a/BOJ/bfs/2589 \353\263\264\353\254\274\354\204\254/2589 \353\263\264\353\254\274\354\204\254.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def bfs(i, j): - q = deque() - q.append([i, j]) - max_n = 0 - while q: - a, b = q.popleft() - for k in range(4): - x = a + dx[k] - y = b + dy[k] - if 0 <= x < n and 0 <= y < m and visit[x][y] == 0 and matrix[x][y] != "W": - visit[x][y] = 1 - matrix[x][y] = matrix[a][b] + 1 - max_n = max(max_n, matrix[x][y]) - q.append([x, y]) - return max_n - - -n, m = map(int, input().split()) -matrix = [list(input().strip()) for _ in range(n)] - -dx = [1, -1, 0, 0] -dy = [0, 0, -1, 1] - -answer = 0 -for i in range(n): - for j in range(m): - if matrix[i][j] != "W": - visit = [[0] * m for _ in range(n)] - matrix[i][j] = 0 - visit[i][j] = 1 - answer = max(answer, bfs(i, j)) - -print(answer) \ No newline at end of file diff --git "a/BOJ/bfs/9376 \355\203\210\354\230\245/9376 \355\203\210\354\230\245.py" "b/BOJ/bfs/9376 \355\203\210\354\230\245/9376 \355\203\210\354\230\245.py" deleted file mode 100644 index 3b10eb3..0000000 --- "a/BOJ/bfs/9376 \355\203\210\354\230\245/9376 \355\203\210\354\230\245.py" +++ /dev/null @@ -1,59 +0,0 @@ -import sys -from collections import deque - -input = sys.stdin.readline - -d = [[-1, 0], [0, -1], [1, 0], [0, 1]] -T = int(input().strip()) - - -def BFS(y, x): - q = deque() - cnt = [[-1] * (w + 2) for _ in range(h + 2)] - q.append([y, x]) - cnt[y][x] = 0 - - while q: - y, x = q.popleft() - for dy, dx in d: - ty = y + dy - tx = x + dx - if 0 <= ty < h + 2 and 0 <= tx < w + 2: - if cnt[ty][tx] == -1: - if prison[ty][tx] == '.': - q.appendleft([ty, tx]) - cnt[ty][tx] = cnt[y][x] - elif prison[ty][tx] == '#': - q.append([ty, tx]) - cnt[ty][tx] = cnt[y][x] + 1 - - return cnt - - -for _ in range(T): - h, w = map(int, input().split()) - prison = [['.'] * (w + 2)] - for i in range(h): - prison.append(list('.' + input().strip() + '.')) - prison.append(['.'] * (w + 2)) - start = [] - - for i in range(1, h + 1): - for j in range(1, w + 1): - if prison[i][j] == '$': - start.append([i, j]) - prison[i][j] = '.' - - cnt1 = BFS(start[0][0], start[0][1]) - cnt2 = BFS(start[1][0], start[1][1]) - cnt3 = BFS(0, 0) - - ans = float('inf') - for i in range(1, h + 1): - for j in range(1, w + 1): - if cnt1[i][j] != -1 and cnt2[i][j] != -1 and cnt3[i][j] != -1: - if prison[i][j] == '.': - ans = min(ans, cnt1[i][j] + cnt2[i][j] + cnt3[i][j]) - elif prison[i][j] == '#': - ans = min(ans, cnt1[i][j] + cnt2[i][j] + cnt3[i][j] - 2) - print(ans) \ No newline at end of file diff --git "a/BOJ/brouteforce/1487 \353\254\274\352\261\264\355\214\224\352\270\260/1487 \353\254\274\352\261\264\355\214\224\352\270\260.py" "b/BOJ/brouteforce/1487 \353\254\274\352\261\264\355\214\224\352\270\260/1487 \353\254\274\352\261\264\355\214\224\352\270\260.py" deleted file mode 100644 index 551c4c2..0000000 --- "a/BOJ/brouteforce/1487 \353\254\274\352\261\264\355\214\224\352\270\260/1487 \353\254\274\352\261\264\355\214\224\352\270\260.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -costs = [list(map(int, input().split())) for _ in range(N)] -costs.sort() - -dp = [0] * N -max_profit = 0 -answers = [] -for i in range(N): - for j in range(i, N): - tmp = costs[i][0] - costs[j][1] - if tmp > 0: - dp[i] += tmp - if max_profit <= dp[i]: - if max_profit < dp[i]: - answers = [] - max_profit = dp[i] - answers.append(costs[i][0]) -print(min(answers) if answers else 0) \ No newline at end of file diff --git "a/BOJ/brouteforce/18111 \353\247\210\354\235\270\355\201\254\353\236\230\355\224\204\355\212\270/18111 \353\247\210\354\235\270\355\201\254\353\236\230\355\224\204\355\212\270.py" "b/BOJ/brouteforce/18111 \353\247\210\354\235\270\355\201\254\353\236\230\355\224\204\355\212\270/18111 \353\247\210\354\235\270\355\201\254\353\236\230\355\224\204\355\212\270.py" deleted file mode 100644 index 3795717..0000000 --- "a/BOJ/brouteforce/18111 \353\247\210\354\235\270\355\201\254\353\236\230\355\224\204\355\212\270/18111 \353\247\210\354\235\270\355\201\254\353\236\230\355\224\204\355\212\270.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -n, m, b = map(int, sys.stdin.readline().split()) -table = [list(map(int, sys.stdin.readline().split())) for _ in range(n)] -height = 0 -ans = 1000000000000000000000000000000 -for i in range(257): - max = 0 - min = 0 - for j in range(n): - for k in range(m): - if table[j][k] < i: - min += (i - table[j][k]) - else: - max += (table[j][k] - i) - inventory = max + b - if inventory < min: - continue - time = 2 * max + min - if time <= ans: - # 시간이 같을 때는 높이가 높은 순으로 출력하라는 조건에 맞게 - # for i in range(257)은 항상 i가 오름차순으로 돌기 때문에 - # 시간이 같아도 최종적으로는 높이가 높은 순으로 나오게 된다 - ans = time - height = i -print(ans, height) \ No newline at end of file diff --git "a/BOJ/brouteforce/5883 \354\225\204\354\235\264\355\217\260 9S/5883 \354\225\204\354\235\264\355\217\260 9S.py" "b/BOJ/brouteforce/5883 \354\225\204\354\235\264\355\217\260 9S/5883 \354\225\204\354\235\264\355\217\260 9S.py" deleted file mode 100644 index e235c26..0000000 --- "a/BOJ/brouteforce/5883 \354\225\204\354\235\264\355\217\260 9S/5883 \354\225\204\354\235\264\355\217\260 9S.py" +++ /dev/null @@ -1,6 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input().split()) -B = [int(input()) for _ in range(N)] - diff --git "a/BOJ/dfs/1103 \352\262\214\354\236\204/1103 \352\262\214\354\236\204.py" "b/BOJ/dfs/1103 \352\262\214\354\236\204/1103 \352\262\214\354\236\204.py" deleted file mode 100644 index 294a197..0000000 --- "a/BOJ/dfs/1103 \352\262\214\354\236\204/1103 \352\262\214\354\236\204.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -sys.setrecursionlimit(10**6) - -dr = [0, 1, 0,-1] -dc = [1, 0,-1, 0] - -def dfs(r ,c): - global state, visited - if not(0<=r -#include -#define NMAX 105 -#define MOD 1000000 - -int N; -int dp[NMAX][NMAX][NMAX][2]; - -long long int ret; - -// l: 왼쪽에 남아있는 수 / r: 오른쪽에 남아있는 수 / s: 현재 골라야하는 방향 -int sv(int idx, int l, int r, int s) { - // 메모이제이션 - if(dp[idx][l][r][s] >= 0) return dp[idx][l][r][s]; - - // 종료조건 - if(idx == N) { - if(!l and !r) return dp[idx][l][r][s] = 1; - else return dp[idx][l][r][s] = 0; - } - else { - long long int ret=0; - - // 작은 수 고르는 단계 - if(s == 0) { - for(int i=l-1;i>=0;i--) { - ret = ( ret+sv(idx+1, i, r+(l-i-1), 1) )%MOD; - } - } - - // 큰 수 고르는 단계 - else { - for(int i=r-1;i>=0;i--) { - ret = ( ret+sv(idx+1, l+(r-i-1), i, 0) )%MOD; - } - } - - return dp[idx][l][r][s] = ret; - } -} - -int main() { - // input - scanf("%d", &N); - - if(N == 1) printf("1"); - else { - // dp - memset(dp, -1, sizeof(dp)); - for (int i=1;i<=N;i++) { - for (int s=0;s<2;s++) { - ret = ( ret+sv(1, i - 1, N - i, s) )%MOD; - } - } - - // print - printf("%lld", ret); - } -} \ No newline at end of file diff --git "a/BOJ/dfs/1146 \354\247\200\352\267\270\354\236\254\352\267\270 \354\204\234\352\270\260/1146 \354\247\200\352\267\270\354\236\254\352\267\270\354\204\234\352\270\260.py" "b/BOJ/dfs/1146 \354\247\200\352\267\270\354\236\254\352\267\270 \354\204\234\352\270\260/1146 \354\247\200\352\267\270\354\236\254\352\267\270\354\204\234\352\270\260.py" deleted file mode 100644 index 7ab8689..0000000 --- "a/BOJ/dfs/1146 \354\247\200\352\267\270\354\236\254\352\267\270 \354\204\234\352\270\260/1146 \354\247\200\352\267\270\354\236\254\352\267\270\354\204\234\352\270\260.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys;sys.setrecursionlimit(100000000) -m=1000000 -def z(n,k): - if k==0: - if n==0:return 1 - else:return 0 - r=d[n][k] - if r!=-1:return r - d[n][k]=(z(n,k-1)+z(n-1,n-k))%m - return d[n][k] -d=[[-1]*101 for _ in range(101)] -d[0][0]=1 -n=int(input()) -print(1 if n==1 else 2*z(n,n)%m) \ No newline at end of file diff --git "a/BOJ/dfs/1405 \353\257\270\354\271\234\353\241\234\353\264\207/1405 \353\257\270\354\271\234\353\241\234\353\264\207.py" "b/BOJ/dfs/1405 \353\257\270\354\271\234\353\241\234\353\264\207/1405 \353\257\270\354\271\234\353\241\234\353\264\207.py" deleted file mode 100644 index 4a0f589..0000000 --- "a/BOJ/dfs/1405 \353\257\270\354\271\234\353\241\234\353\264\207/1405 \353\257\270\354\271\234\353\241\234\353\264\207.py" +++ /dev/null @@ -1,21 +0,0 @@ -d = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 4방향 탐색 - -def dfs(r, c, visited, total): - global answer - if len(visited) == N+1: - answer += total - return - for idx in range(4): - nr = r + d[idx][0] - nc = c + d[idx][1] - if (nr, nc) not in visited: - visited.append((nr, nc)) - dfs(nr, nc, visited, total*probability[idx]) - visited.pop() - -N, ep, wp, sp, np = map(int, input().split()) -probability = [ep, wp, sp, np] -answer = 0 - -dfs(0, 0, [(0, 0)], 1) -print(answer * (0.01 ** N)) \ No newline at end of file diff --git "a/BOJ/dfs/15271 \354\271\234\352\265\254\355\216\240\353\246\260\353\223\234\353\241\254/15271 \354\271\234\352\265\254\355\216\240\353\246\260\353\223\234\353\241\254.py" "b/BOJ/dfs/15271 \354\271\234\352\265\254\355\216\240\353\246\260\353\223\234\353\241\254/15271 \354\271\234\352\265\254\355\216\240\353\246\260\353\223\234\353\241\254.py" deleted file mode 100644 index e243cb8..0000000 --- "a/BOJ/dfs/15271 \354\271\234\352\265\254\355\216\240\353\246\260\353\223\234\353\241\254/15271 \354\271\234\352\265\254\355\216\240\353\246\260\353\223\234\353\241\254.py" +++ /dev/null @@ -1,78 +0,0 @@ -import sys -input = sys.stdin.readline -n, m = map(int, input().split()) -path = [[] for _ in range(n + 1)] -for _ in range(m): - a, b = map(int, input().split()) - if (a + b) % 2: - path[a].append(b) - path[b].append(a) - -match = [-1]*(n+1) -def dfs(n): - if n == -1: - return 2 - for j in path[n]: - if avail[j]: - avail[j] = False - if dfs(match[j]): - match[j] = n - return 2 - return 0 - -ans = 0 -for i in range(1, n+1, 2): - avail = [True] * (n + 1) - ans += dfs(i) - -if ans != n: - ans += 1 -print(ans) - - - -# 2 -from sys import setrecursionlimit as SRL -SRL(15000) -from collections import deque -def BFS(ssize, tsize, adj, pairu, pairv, dist): - Q = deque() - for u in range(1, ssize+1): - if pairu[u] == 0: dist[u] = 0; Q.append(u) - else: dist[u] = float('inf') - dist[0] = float('inf') - while len(Q) > 0: - u = Q.popleft() - if dist[u] >= dist[0]: continue - for v in adj[u]: - if dist[pairv[v]] == float('inf'): - dist[pairv[v]] = dist[u] + 1 - Q.append(pairv[v]) - return dist[0] != float('inf') - -def DFS(ssize, tsize, adj, pairu, pairv, dist, u): - if u == 0: return True - for v in adj[u]: - if dist[pairv[v]] == dist[u] + 1 and DFS(ssize, tsize, adj, pairu, pairv, dist, pairv[v]): - pairv[v] = u; pairu[u] = v; return True - dist[u] = float('inf'); return False - -def HopcroftKarp(ssize, tsize, adj): - pairu = [0]*(ssize+1); pairv = [0]*(tsize+1); dist = [-1]*(ssize+1) - match = 0 - while BFS(ssize, tsize, adj, pairu, pairv, dist): - for u in range(1, ssize+1): - if pairu[u] == 0: match+= DFS(ssize, tsize, adj, pairu, pairv, dist, u) - return match - -from sys import stdin -input = stdin.readline -n, m = map(int,input().split()) -adj = [[] for i in range(n+1)] -for i in range(m): - a, b = map(int,input().split()) - if a%2 == b%2: continue - if a%2: a,b = b,a - adj[a].append(b) -match = HopcroftKarp(n, n, adj) -print(min(2*match+1, n)) \ No newline at end of file diff --git "a/BOJ/dijkstra/1162 \353\217\204\353\241\234\355\217\254\354\236\245/1162 \353\217\204\353\241\234\355\217\254\354\236\245.py" "b/BOJ/dijkstra/1162 \353\217\204\353\241\234\355\217\254\354\236\245/1162 \353\217\204\353\241\234\355\217\254\354\236\245.py" deleted file mode 100644 index f256cf6..0000000 --- "a/BOJ/dijkstra/1162 \353\217\204\353\241\234\355\217\254\354\236\245/1162 \353\217\204\353\241\234\355\217\254\354\236\245.py" +++ /dev/null @@ -1,39 +0,0 @@ -import heapq -import sys -input = sys.stdin.readline -INF = sys.maxsize -n, m, k = map(int, input().split()) - -graph = [[] for _ in range(n+1)] -distance = [[INF for _ in range(k+1)] for _ in range(n+1)] # 도로를 몇개 포장했는지 확인하기 위해서 이중리스트로 만든다. -for i in range(m): - x,y,z = map(int,input().split()) - graph[x].append((z,y)) - graph[y].append((z,x)) - -def dijkstra(start): - queue = [] - cnt = 0 - distance[start][cnt] = 0 - heapq.heappush(queue, (0, start, cnt)) - - while queue: - wei, now, cnt = heapq.heappop(queue) - if distance[now][cnt] < wei: - continue - for w, next_node in graph[now]: - next_wei = w + wei - if distance[next_node][cnt] > next_wei: - distance[next_node][cnt] = next_wei - heapq.heappush(queue, (next_wei, next_node,cnt)) - - # elif로 안하고 if로 하는 이유는 모든곳을 돌아 도로포장을 했을때 가장 작은 값을 찾기 위해서이다. - if cnt < k and distance[next_node][cnt+1] > wei: - # 도로포장 횟수가 남았고 현재까지 distance[next_node][cnt+1](next_node 까지 가중치)가 wei(now 노드까지 가중치)보다 크다면 - # next_node까지 움직이는 w(now에서 next_node까지 가중치)를 무시하고 wei를 넣어준다. - distance[next_node][cnt+1] = wei - heapq.heappush(queue, (wei, next_node, cnt+1)) - - -dijkstra(1) -print(min(distance[n])) \ No newline at end of file diff --git "a/BOJ/dp/1006 \354\212\265\352\262\251\354\236\220 \354\264\210\353\235\274\352\270\260/1006 \354\212\265\352\262\251\354\236\220 \354\264\210\353\235\274\352\270\260.py" "b/BOJ/dp/1006 \354\212\265\352\262\251\354\236\220 \354\264\210\353\235\274\352\270\260/1006 \354\212\265\352\262\251\354\236\220 \354\264\210\353\235\274\352\270\260.py" deleted file mode 100644 index 82038fa..0000000 --- "a/BOJ/dp/1006 \354\212\265\352\262\251\354\236\220 \354\264\210\353\235\274\352\270\260/1006 \354\212\265\352\262\251\354\236\220 \354\264\210\353\235\274\352\270\260.py" +++ /dev/null @@ -1,79 +0,0 @@ -import sys -# import random -T = int(sys.stdin.readline()) -results = [] - -def recur(start, a, b, c): - for i in range(start, N): - # i 열까지 최소 - a[i+1] = min(b[i]+1, c[i]+1) - if zone1[i] + zone2[i] <= W: a[i+1] = min(a[i+1], a[i]+1) - if i > 0 and zone1[i-1] + zone1[i] <= W and zone2[i-1] + zone2[i] <= W: a[i+1] = min(a[i+1], a[i-1]+2) - - if i < N-1: - # 1행은 i+1열, 2행은 i열까지 최소 소대 수 - b[i+1] = a[i+1] + 1 - if zone1[i+1] + zone1[i] <= W: b[i+1] = min(b[i+1], c[i] + 1) - - # 1행은 i열, 2행은 i+1열까지 최소 소대 수 - c[i+1] = a[i+1]+1 - if zone2[i+1] + zone2[i] <= W: c[i+1] = min(c[i+1], b[i] + 1) - - return a, b, c - - -for _ in range(T): - N, W = map(int, sys.stdin.readline().split()) - # 윗줄 적의 수 - zone1 = list(map(int, sys.stdin.readline().split())) - # 아랫줄 적의 수 - zone2 = list(map(int, sys.stdin.readline().split())) - - # 1행과 2행 모두 i-1열까지 채울 때 최소 소대 수 - a = [0 for _ in range(N+1)] - # 1행은 i열까지, 2행은 i-1열까지 채울 때 최소 소대 수 - b = [0 for _ in range(N+1)] - # 1행은 i-1열까지, 2행은 i열까지 채울 때 최소 소대 수 - c = [0 for _ in range(N+1)] - a[0] = 0 - b[0] = 1 - c[0] = 1 - a, b, c = recur(0, a, b, c) - res = a[N] - - # 윗줄의 0번 열과 끝 열이 쌍을 이룰 수 있을 때 다시 한 번 계산 후 최솟값 갱신 - # 윗줄의 0번 열이 이미 채워졌다고 생각 - if N > 1 and zone1[0] + zone1[N-1] <= W: - a[1] = 1 - b[1] = 2 # 아랫줄의 0번열, 윗줄의 1번열을 쌍을 이룰 수 없는 채로 2개의 소대를 배치해야함. - if zone2[0] + zone2[1] <= W: c[1] = 1 # 아랫줄의 0번 열과 1번 열이 쌍을 이룰 수 있는 경우 - else: c[1] = 2 - - a, b, c = recur(1, a, b, c) - res = min(res, c[N-1] + 1) - - # 아랫줄의 0번 열과 끝 열이 쌍을 이룰 수 있을 때 다시 한 번 계산 후 최솟값 갱신 - # 아랫줄의 0번 열이 이미 채워졌다고 생각 - if N > 1 and zone2[0] + zone2[N-1] <= W: - a[1] = 1 - c[1] = 2 # 윗줄의 0번열, 아랫줄의 1번열을 쌍을 이룰 수 없는 채로 2개의 소대를 배치해야함. - if zone1[0] + zone1[1] <= W: b[1] = 1 # 윗줄의 0번 열과 1번 열이 쌍을 이룰 수 있는 경우 - else: b[1] = 2 - - a, b, c = recur(1, a, b, c) - res = min(res, b[N-1] + 1) - - # 윗줄과 아랫줄 모두 0번 열과 끝 열이 쌍을 이룰 수 있을 때 다시 한 번 계산 후 최솟값 갱신 - # 윗줄과 아랫줄 모두 0번 열이 이미 채워졌다고 생각 - if N > 1 and zone1[0] + zone1[N-1] <= W and zone2[0] + zone2[N-1] <= W: - a[1] = 0 # 0열이 이미 채워짐 - b[1] = 1 - c[1] = 1 - - a, b, c = recur(1, a, b, c) - res = min(res, a[N-1] + 2) - - results.append(res) - -for result in results: - sys.stdout.write(str(result)+'\n') \ No newline at end of file diff --git "a/BOJ/dp/1082 \353\260\251\353\262\210\355\230\270/1082 \353\260\251\353\262\210\355\230\270.py" "b/BOJ/dp/1082 \353\260\251\353\262\210\355\230\270/1082 \353\260\251\353\262\210\355\230\270.py" deleted file mode 100644 index e108d72..0000000 --- "a/BOJ/dp/1082 \353\260\251\353\262\210\355\230\270/1082 \353\260\251\353\262\210\355\230\270.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys - -read = sys.stdin.readline -# 입력 -N = int(read()) -nums = list(map(int, read().split())) -M = int(read()) - -dp = [[""] * (M + 1) for _ in range(N + 1)] -zero_dp = ["" for _ in range(M + 1)] - -# 0으로 만들 수 있는 번호 저장 -for w in range(1, M + 1): - if nums[0] <= w: - zero_dp[w] = "0" * (w // nums[0]) - -# Knapsack -for i in range(1, N + 1): - for w in range(1, M + 1): - if w < nums[i - 1]: - dp[i][w] = dp[i - 1][w] - else: - dup = 1 # 번호판을 살 수 있을 때 해당 번호로 살 수 없을 때 까지 구매함. - while dup * nums[i - 1] <= w: - rest = w - (dup * nums[i - 1]) - tmp = f"{i - 1}" * dup - - if dp[i - 1][w] != "": - tmp_max = max(int(tmp + dp[i - 1][rest]), int(dp[i - 1][w])) - if dp[i][w] != "": - tmp_max = max(tmp_max, int(dp[i][w])) - dp[i][w] = str(tmp_max) - else: - dp[i][w] = tmp + dp[i - 1][rest] - # knapsack으로 구한 최대값과 나머지를 0으로 채웠을 때를 비교 - if zero_dp[rest] != "": - dp[i][w] = str(max(int(dp[i][w]), int(tmp + zero_dp[rest]))) - dup += 1 - -# 000 과 같은 수가 나올 수 있어 int로 형변환 -print(int(dp[-1][-1])) \ No newline at end of file diff --git "a/BOJ/dp/11053 \352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264/11053 \352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264.py" "b/BOJ/dp/11053 \352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264/11053 \352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264.py" deleted file mode 100644 index 0e3bb0e..0000000 --- "a/BOJ/dp/11053 \352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264/11053 \352\260\200\354\236\245 \352\270\264 \354\246\235\352\260\200\355\225\230\353\212\224 \353\266\200\353\266\204\354\210\230\354\227\264.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -from bisect import bisect_left -input = sys.stdin.readline - -n = int(input()) -a = list(map(int,input().split())) - -q=[] -for x in a: - if not q or x > q[-1]: - q.append(x) - else: - q[bisect_left(q,x)] = x - -print(len(q)) diff --git "a/BOJ/dp/11660 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 5/11660 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 5.py" "b/BOJ/dp/11660 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 5/11660 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 5.py" deleted file mode 100644 index 7627089..0000000 --- "a/BOJ/dp/11660 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 5/11660 \352\265\254\352\260\204 \355\225\251 \352\265\254\355\225\230\352\270\260 5.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -N,M = map(int, input().split()) - -dp = [[0] + list(map(int, input().split())) for _ in range(N)] -dp = [[0] * (N + 1)] + dp -for i in range(1, N + 1): - for j in range(1, N + 1): - dp[i][j] += dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] - - -for _ in range(M): - x1, y1, x2, y2 = map(int,input().split()) - answer = dp[x2][y2] - dp[x2][y1 - 1] - dp[x1 - 1][y2] + dp[x1 - 1][y1 - 1] - print(answer) \ No newline at end of file diff --git "a/BOJ/dp/12865 \355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255/12865 \355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.PY" "b/BOJ/dp/12865 \355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255/12865 \355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.PY" deleted file mode 100644 index e0f8c36..0000000 --- "a/BOJ/dp/12865 \355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255/12865 \355\217\211\353\262\224\355\225\234 \353\260\260\353\202\255.PY" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -N, K = map(int, input().split()) -costs = [[0, 0]] + [list(map(int, input().split())) for _ in range(N)] -dp = [[0] * (K + 1) for _ in range(N + 1)] - -for i in range(1, N + 1): - for j in range(1, K + 1): - if j < costs[i][0] : - dp[i][j] = dp[i - 1][j] - else: - dp[i][j] = max(costs[i][1] + dp[i - 1][j - costs[i][0]], dp[i - 1][j]) - -print(dp[N][K]) \ No newline at end of file diff --git "a/BOJ/dp/1328 \352\263\240\354\270\265\353\271\214\353\224\251/1328 \352\263\240\354\270\265\353\271\214\353\224\251.py" "b/BOJ/dp/1328 \352\263\240\354\270\265\353\271\214\353\224\251/1328 \352\263\240\354\270\265\353\271\214\353\224\251.py" deleted file mode 100644 index c2c69d4..0000000 --- "a/BOJ/dp/1328 \352\263\240\354\270\265\353\271\214\353\224\251/1328 \352\263\240\354\270\265\353\271\214\353\224\251.py" +++ /dev/null @@ -1,9 +0,0 @@ -n, l, r = map(int, input().split()) -MOD = 1000000007 -dp = [[[0 for _ in range(n + 1)] for _ in range(n + 1)] for _ in range(n + 1)] -dp[1][1][1] = 1 -for i in range(2, n + 1): - for j in range(1, l + 1): - for k in range(1, r + 1): - dp[i][j][k] = (dp[i - 1][j - 1][k] + dp[i - 1][j][k - 1] + dp[i - 1][j][k] * (i - 2)) % MOD -print(dp[n][l][r]) \ No newline at end of file diff --git "a/BOJ/dp/17216 \352\260\200\354\236\245 \355\201\260 \352\260\220\354\206\214 \353\266\200\353\266\204 \354\210\230\354\227\264/17216 \352\260\200\354\236\245 \355\201\260 \352\260\220\354\206\214 \353\266\200\353\266\204 \354\210\230\354\227\264.py" "b/BOJ/dp/17216 \352\260\200\354\236\245 \355\201\260 \352\260\220\354\206\214 \353\266\200\353\266\204 \354\210\230\354\227\264/17216 \352\260\200\354\236\245 \355\201\260 \352\260\220\354\206\214 \353\266\200\353\266\204 \354\210\230\354\227\264.py" deleted file mode 100644 index 5721c7a..0000000 --- "a/BOJ/dp/17216 \352\260\200\354\236\245 \355\201\260 \352\260\220\354\206\214 \353\266\200\353\266\204 \354\210\230\354\227\264/17216 \352\260\200\354\236\245 \355\201\260 \352\260\220\354\206\214 \353\266\200\353\266\204 \354\210\230\354\227\264.py" +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -arr = list(map(int, input().split())) -dp = arr[:] - -for i in range(N): - for j in range(i): - if arr[j] > arr[i]: - dp[i] = max(dp[i], dp[j] + arr[i]) -print(max(dp)) \ No newline at end of file diff --git "a/BOJ/dp/2631 \354\244\204\354\204\270\354\232\260\352\270\260/2631 \354\244\204\354\204\270\354\232\260\352\270\260.py" "b/BOJ/dp/2631 \354\244\204\354\204\270\354\232\260\352\270\260/2631 \354\244\204\354\204\270\354\232\260\352\270\260.py" deleted file mode 100644 index 0772289..0000000 --- "a/BOJ/dp/2631 \354\244\204\354\204\270\354\232\260\352\270\260/2631 \354\244\204\354\204\270\354\232\260\352\270\260.py" +++ /dev/null @@ -1,16 +0,0 @@ -n = int(input()) -s = [] -dp = [0 for i in range(n)] -for i in range(n): - s.append(int(input())) -dp[0] = 1 -for i in range(1, n): - a = [] - for j in range(i): - if s[i] > s[j]: - a.append(dp[j]) - if not a: - dp[i] = 1 - else: - dp[i] = max(a) + 1 -print(n - max(dp)) \ No newline at end of file diff --git a/BOJ/dp/9251 LCS/9251 LCS.py b/BOJ/dp/9251 LCS/9251 LCS.py deleted file mode 100644 index 5a3270d..0000000 --- a/BOJ/dp/9251 LCS/9251 LCS.py +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - -a, b = input().strip(), input().strip() -n, m = len(a), len(b) -dp = [[0] * (m + 1) for _ in range(n + 1)] - -for i in range(n): - for j in range(m): - dp[i + 1][j + 1] = dp[i][j] + 1 if a[i] == b[j] else max(dp[i + 1][j], dp[i][j + 1]) - -print(dp[-1][-1]) \ No newline at end of file diff --git "a/BOJ/graph/1865 \354\233\234\355\231\200/1865 \354\233\234\355\231\200.py" "b/BOJ/graph/1865 \354\233\234\355\231\200/1865 \354\233\234\355\231\200.py" deleted file mode 100644 index 8e76e0e..0000000 --- "a/BOJ/graph/1865 \354\233\234\355\231\200/1865 \354\233\234\355\231\200.py" +++ /dev/null @@ -1,29 +0,0 @@ -import sys -input = sys.stdin.readline - -def bellman_ford(start): - dists[start] = 0 - for cycle in range(n): - for cur_node, next_node, cost in edges: - if dists[cur_node] + cost < dists[next_node]: - dists[next_node] = dists[cur_node] + cost - if cycle == n - 1: - return True - return False - -INF = 123456789 -for test in range(int(input())): - n, m, w = map(int, input().split()) - edges = [] - for _ in range(m): - a, b, c = map(int, input().split()) - edges.append((a, b, c)) - edges.append((b, a, c)) - for _ in range(w): - a, b, c = map(int, input().split()) - edges.append((a, b, -c)) - - dists = {i: INF for i in range(1, n + 1)} - - print("YES" if bellman_ford(1) else "NO") - \ No newline at end of file diff --git "a/BOJ/graph/1916 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260/1916 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260.py" "b/BOJ/graph/1916 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260/1916 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260.py" deleted file mode 100644 index 6319aaa..0000000 --- "a/BOJ/graph/1916 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260/1916 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -from heapq import heappush, heappop -input = sys.stdin.readline -n = int(input()) -m = int(input()) -inf = 100000000 -s = [[] for i in range(n + 1)] -dp = [inf for i in range(n + 1)] -for i in range(m): - a, b, w = map(int, input().split()) - s[a].append([b, w]) -start, end = map(int, input().split()) -def dijkstra(start): - dp[start] = 0 - heap = [] - heappush(heap, [0, start]) - while heap: - w, n = heappop(heap) - if dp[n] < w: - continue - for n_n, wei in s[n]: - n_w = w + wei - if dp[n_n] > n_w: - dp[n_n] = n_w - heappush(heap, [n_w, n_n]) -dijkstra(start) -print(dp[end]) \ No newline at end of file diff --git "a/BOJ/greedy/1092 \353\260\260/1092 \353\260\260.py" "b/BOJ/greedy/1092 \353\260\260/1092 \353\260\260.py" deleted file mode 100644 index 041f2c5..0000000 --- "a/BOJ/greedy/1092 \353\260\260/1092 \353\260\260.py" +++ /dev/null @@ -1,30 +0,0 @@ -n = int(input()) -crane = list(map(int, input().split())) -m = int(input()) -box = list(map(int, input().split())) - -# ⚡ 내림차순 정렬 -crane.sort(reverse = True) -box.sort(reverse = True) - -time = 0 # 시간 -checked = [0 for _ in range(m)] # 박스를 옮겼는지 여부 -count = 0 # 옮긴 박스의 개수 - -positions = [0] * n - -if max(box) > max(crane): - print(-1) -else: - while count < len(box): - for i in range(n): # 크레인에 대하여 - while positions[i] < len(box): - # 아직 안 옮긴 박스 중에서, 옮길 수 있는 박스를 만날 때까지 반복 - if not checked[positions[i]] and crane[i] >= box[positions[i]]: - checked[positions[i]] = True - positions[i] += 1 - count += 1 - break - positions[i] += 1 - time += 1 - print(time) \ No newline at end of file diff --git "a/BOJ/greedy/11508 2+1\354\204\270\354\235\274/11508 2+1\354\204\270\354\235\274.py" "b/BOJ/greedy/11508 2+1\354\204\270\354\235\274/11508 2+1\354\204\270\354\235\274.py" deleted file mode 100644 index 9dd039d..0000000 --- "a/BOJ/greedy/11508 2+1\354\204\270\354\235\274/11508 2+1\354\204\270\354\235\274.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -nums=sorted([int(input()) for _ in range(n)], reverse=True) -answer = 0 -for i in range(n): - if not i % 3 == 2 : - answer += nums[i] -print(answer) \ No newline at end of file diff --git "a/BOJ/greedy/1188 \354\235\214\354\213\235\355\217\211\353\241\240\352\260\200/1188 \354\235\214\354\213\235\355\217\211\353\241\240\352\260\200.py" "b/BOJ/greedy/1188 \354\235\214\354\213\235\355\217\211\353\241\240\352\260\200/1188 \354\235\214\354\213\235\355\217\211\353\241\240\352\260\200.py" deleted file mode 100644 index c26be4a..0000000 --- "a/BOJ/greedy/1188 \354\235\214\354\213\235\355\217\211\353\241\240\352\260\200/1188 \354\235\214\354\213\235\355\217\211\353\241\240\352\260\200.py" +++ /dev/null @@ -1,6 +0,0 @@ -def GCD(a, b): - if a % b == 0: - return b - return GCD(b, a % b) -n, m = map(int, input().split()) -print(m - GCD(n, m)) \ No newline at end of file diff --git "a/BOJ/greedy/16162 \352\260\200\355\235\254\354\231\200 3\353\213\250 \352\263\240\354\235\214/16162 \352\260\200\355\235\254\354\231\200 3\353\213\250 \352\263\240\354\235\214.py" "b/BOJ/greedy/16162 \352\260\200\355\235\254\354\231\200 3\353\213\250 \352\263\240\354\235\214/16162 \352\260\200\355\235\254\354\231\200 3\353\213\250 \352\263\240\354\235\214.py" deleted file mode 100644 index 435327a..0000000 --- "a/BOJ/greedy/16162 \352\260\200\355\235\254\354\231\200 3\353\213\250 \352\263\240\354\235\214/16162 \352\260\200\355\235\254\354\231\200 3\353\213\250 \352\263\240\354\235\214.py" +++ /dev/null @@ -1,8 +0,0 @@ -n, a, d = map(int,input().split()) -L = list(map(int,input().split())) -check = 0 -for pt in range(n): - if L[pt] == a: - check += 1 - a += d -print(check) \ No newline at end of file diff --git "a/BOJ/greedy/26070 \352\263\260\352\263\260\354\235\264\354\231\200 \355\225\231\354\213\235/26070 \352\263\260\352\263\260\354\235\264\354\231\200 \355\225\231\354\213\235.py" "b/BOJ/greedy/26070 \352\263\260\352\263\260\354\235\264\354\231\200 \355\225\231\354\213\235/26070 \352\263\260\352\263\260\354\235\264\354\231\200 \355\225\231\354\213\235.py" deleted file mode 100644 index df0e48d..0000000 --- "a/BOJ/greedy/26070 \352\263\260\352\263\260\354\235\264\354\231\200 \355\225\231\354\213\235/26070 \352\263\260\352\263\260\354\235\264\354\231\200 \355\225\231\354\213\235.py" +++ /dev/null @@ -1,30 +0,0 @@ -A, B, C = map(int, input().split()) -X, Y, Z = map(int, input().split()) -answer = 0 - -# 각 X, Y, Z 식권 3장은 각 Y, Z, X 1장으로 바꿀 수 있다. -# 결국 현재 식권으로 최대한 음식으로 교환 후, 다음 식권으로 교환 -# 이를 총 3번하면 된다. -# 4번째에선 원래 식권으로 돌아오기 때문. - -for _ in range(3): - # 가능한 최대 치킨 수 - chicken = min(A, X) - answer += chicken - A -= chicken - X -= chicken - # 가능한 최대 피자 수 - pizza = min(B, Y) - answer += pizza - B -= pizza - Y -= pizza - # 가능한 최대 햄버거 수 - burger = min(C, Z) - answer += burger - C -= burger - Z -= burger - - # 각 X, Y, Z 식권 3장은 각 Y, Z, X 1장으로 교환 - Y, Z, X = X // 3, Y // 3, Z // 3 - -print(answer) \ No newline at end of file diff --git a/BOJ/implement/12100 2048(easy)/12100 2048(easy).py b/BOJ/implement/12100 2048(easy)/12100 2048(easy).py deleted file mode 100644 index 8002aaf..0000000 --- a/BOJ/implement/12100 2048(easy)/12100 2048(easy).py +++ /dev/null @@ -1,65 +0,0 @@ -import sys -input = sys.stdin.readline - -def next_turn(time, board): - if time == 5: - return - for d in range(4): - new_board = rotate_board(board, d) - next_turn(time + 1, new_board) - - -def rotate_board(matrix, direction): - global answer - ret = [[0] * N for _ in range(N)] - if direction == 0: - for row in range(N): - for col in range(N): - ret[col][N - 1 - row] = matrix[row][col] - elif direction == 1: - for row in range(N): - for col in range(N): - ret[N - 1 - col][N - 1 - row] = matrix[row][col] - elif direction == 2: - for row in range(N): - for col in range(N): - ret[N - 1 - col][row] = matrix[row][col] - else: - for row in range(N): - for col in range(N): - ret[row][col] = matrix[row][col] - ret_mat = [[0] * N for _ in range(N)] - for j in range(N): - tmp = [] - fin = [] - for i in range(N): - if ret[i][j]: - if not tmp: - tmp.append(ret[i][j]) - answer = max(answer, ret[i][j]) - else: - if tmp[-1] == ret[i][j]: - tmp.pop() - fin.append(ret[i][j] * 2) - answer = max(answer, ret[i][j] * 2) - else: - fin.append(tmp.pop()) - tmp.append(ret[i][j]) - if tmp: - fin.append(tmp.pop()) - if not fin: - continue - start = 0 - for row in range(len(fin)): - ret_mat[row][j] = fin[start] - start += 1 - return ret_mat - - -N = int(input()) -board = [list(map(int, input().split())) for _ in range(N)] -answer = 0 - -# 최대 5번 이동해서 가장 큰 블록의 값. -next_turn(0, board) -print(answer) \ No newline at end of file diff --git "a/BOJ/implement/12933 \354\230\244\353\246\254/12933 \354\230\244\353\246\254.py" "b/BOJ/implement/12933 \354\230\244\353\246\254/12933 \354\230\244\353\246\254.py" deleted file mode 100644 index ffd1dd1..0000000 --- "a/BOJ/implement/12933 \354\230\244\353\246\254/12933 \354\230\244\353\246\254.py" +++ /dev/null @@ -1,34 +0,0 @@ -duck = input() -visited = [False] * len(duck) -cnt = 0 - -if len(duck) % 5 != 0: - print(-1) - exit() - - -def solve(start): - global cnt - quack = 'quack' - j = 0 - first = True - for i in range(start, len(duck)): - if duck[i] == quack[j] and not visited[i]: - visited[i] = True - if duck[i] == 'k': - if first: - cnt += 1 - first = False - j = 0 - continue - j += 1 - - -for i in range(len(duck)): - if duck[i] == 'q' and not visited[i]: - solve(i) - -if not all(visited) or cnt == 0: - print(-1) -else: - print(cnt) \ No newline at end of file diff --git "a/BOJ/implement/17143 \353\202\232\354\213\234\354\231\225/17143 \353\202\232\354\213\234\354\231\225.py" "b/BOJ/implement/17143 \353\202\232\354\213\234\354\231\225/17143 \353\202\232\354\213\234\354\231\225.py" deleted file mode 100644 index 2ea53d9..0000000 --- "a/BOJ/implement/17143 \353\202\232\354\213\234\354\231\225/17143 \353\202\232\354\213\234\354\231\225.py" +++ /dev/null @@ -1,53 +0,0 @@ -import sys -input = sys.stdin.readline - -def move_shark(): - new_board = [[0 for _ in range(C)] for _ in range(R)] - for x in range(R): - for y in range(C): - if not board[x][y]: - continue - t_x, t_y = x, y - s, d, z = board[t_x][t_y] - total = s - if d == 0 or d == 1: - s %= 2 * R - 2 - while s: - if (t_x == R - 1 and d == 1) or (t_x == 0 and d == 0): - d ^= 1 - nx = t_x + delta[d][0] - s -= 1 - t_x = nx - else: - s %= 2 * C - 2 - while s: - if (t_y == C - 1 and d == 2) or (t_y == 0 and d == 3): - d = (d - 2)^1 + 2 - ny = t_y + delta[d][1] - s -= 1 - t_y = ny - if new_board[t_x][t_y] and new_board[t_x][t_y][2] > z: - pass - else: - new_board[t_x][t_y] = (total, d, z) - return new_board - -R, C, M = map(int, input().split()) -board = [[0 for _ in range(C)] for _ in range(R)] -for _ in range(M): - r, c, s, d, z = map(int, input().split()) - board[r - 1][c - 1] = (s, d - 1, z) - -delta = ((-1, 0), (1, 0), (0, 1), (0, -1)) -answer = 0 -# 낚시왕은 1초당 1열씩 이동 -for king_of_fishing in range(C): - for i in range(R): - if board[i][king_of_fishing]: - answer += board[i][king_of_fishing][2] - board[i][king_of_fishing] = 0 - break - board = move_shark() -# 해당 열에서 가장 가까운 상어를 잡는다. 잡으면 상어는 사라진다. -# 상어들이 이동한다. -print(answer) \ No newline at end of file diff --git "a/BOJ/implement/17779 \352\262\214\353\246\254\353\247\250\353\215\224\353\247\2012/17779 \352\262\214\353\246\254\353\251\230\353\215\224\353\247\2012.py" "b/BOJ/implement/17779 \352\262\214\353\246\254\353\247\250\353\215\224\353\247\2012/17779 \352\262\214\353\246\254\353\251\230\353\215\224\353\247\2012.py" deleted file mode 100644 index d675778..0000000 --- "a/BOJ/implement/17779 \352\262\214\353\246\254\353\247\250\353\215\224\353\247\2012/17779 \352\262\214\353\246\254\353\251\230\353\215\224\353\247\2012.py" +++ /dev/null @@ -1,59 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -matrix = [list(map(int, input().split())) for _ in range(N)] -answer = float('inf') -total = 0 -for i in range(N): - for j in range(N): - total += matrix[i][j] -for x in range(N - 1): - for y in range(1, N - 1): - for d1 in range(1, min(y + 1, N - x - 1)): - for d2 in range(1, min(N - y, N - x - d1)): - area1 = 0 - for i in range(x): - for j in range(y + 1): - area1 += matrix[i][j] - for i in range(x, x + d1): - for j in range(y - d1): - area1 += matrix[i][j] - for i in range(x, x + d1): - for j in range(y - d1, y - i + x): - area1 += matrix[i][j] - area2 = 0 - for i in range(x): - for j in range(y + 1, N): - area2 += matrix[i][j] - for i in range(x, x + d2 + 1): - for j in range(y + d2 + 1, N): - area2 += matrix[i][j] - for i in range(x, x + d2): - for j in range(y + i - x + 1, y + d2 + 1): - area2 += matrix[i][j] - - area3 = 0 - for i in range(x + d1, N): - for j in range(y - d1): - area3 += matrix[i][j] - for i in range(x + d1 + d2 + 1, N): - for j in range(y - d1, y - d1 + d2): - area3 += matrix[i][j] - for i in range(x + d1 + 1, x + d1 + d2 + 1): - for j in range(y - d1, y - 2 * d1 + i - x): - area3 += matrix[i][j] - area4 = 0 - for i in range(x + d1 + d2 + 1, N): - for j in range(y - d1 + d2, N): - area4 += matrix[i][j] - for i in range(x + d2 + 1, x + d1 +d2 + 1): - for j in range(y + d2 + 1, N): - area4 += matrix[i][j] - for i in range(x + d2 + 1, x + d1 + d2 + 1): - for j in range(y - i + x + 2 * d2 + 1, y + d2 + 1): - area4 += matrix[i][j] - - area5 = total - (area1 + area2 + area3 + area4) - answer = min(answer, max(area1, area2, area3, area4, area5) - min(area1, area2, area3, area4, area5)) -print(answer) diff --git "a/BOJ/implement/17822 \354\233\220\355\214\220 \353\217\214\353\246\254\352\270\260/17822 \354\233\220\355\214\220\353\217\214\353\246\254\352\270\260.py" "b/BOJ/implement/17822 \354\233\220\355\214\220 \353\217\214\353\246\254\352\270\260/17822 \354\233\220\355\214\220\353\217\214\353\246\254\352\270\260.py" deleted file mode 100644 index 99e1bcd..0000000 --- "a/BOJ/implement/17822 \354\233\220\355\214\220 \353\217\214\353\246\254\352\270\260/17822 \354\233\220\355\214\220\353\217\214\353\246\254\352\270\260.py" +++ /dev/null @@ -1,85 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def rotate(i, d): - new_board = [] - if d: - for n in range(k, M): - new_board.append(round_boards[i][n]) - for n in range(k): - new_board.append(round_boards[i][n]) - else: - for n in range(M - k, M): - new_board.append(round_boards[i][n]) - for n in range(M - k): - new_board.append(round_boards[i][n]) - round_boards[i] = new_board - - -def bfs(x, y): - q = deque() - q.append((x, y)) - check_list[x][y] = True - pivot = round_boards[x][y] - flag = 0 - while q: - x, y = q.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if ny == -1: - ny = M - 1 - elif ny == M: - ny = 0 - if 0 <= nx < N and not check_list[nx][ny] and pivot == round_boards[nx][ny]: - check_list[nx][ny] = True - round_boards[x][y] = 0 - round_boards[nx][ny] = 0 - q.append((nx, ny)) - flag = 1 - if flag: - return 1 - return 0 - - - -N, M, T = map(int, input().split()) -round_boards = [list(map(int, input().split())) for _ in range(N)] - -delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) - -for _ in range(T): - x, d, k = map(int, input().split()) - k %= M - if k: - for i in range(x - 1, N, x): - rotate(i, d) - check_list = [[False] * M for _ in range(N)] - change_zero = 0 - for i in range(N): - for j in range(M): - if round_boards[i][j]: - change_zero += bfs(i, j) - if not change_zero: - points = [] - sum_all = 0 - cnt = 0 - for i in range(N): - for j in range(M): - if round_boards[i][j]: - points.append((i, j)) - cnt += 1 - sum_all += round_boards[i][j] - if cnt: - avg = sum_all / cnt - for x, y in points: - if round_boards[x][y] > avg: - round_boards[x][y] -= 1 - elif round_boards[x][y] < avg: - round_boards[x][y] += 1 -answer = 0 -for i in range(N): - for j in range(M): - answer += round_boards[i][j] -print(answer) - \ No newline at end of file diff --git "a/BOJ/implement/17825 \354\243\274\354\202\254\354\234\204 \354\234\267\353\206\200\354\235\264/17825 \354\243\274\354\202\254\354\234\204 \354\234\267\353\206\200\354\235\264.py" "b/BOJ/implement/17825 \354\243\274\354\202\254\354\234\204 \354\234\267\353\206\200\354\235\264/17825 \354\243\274\354\202\254\354\234\204 \354\234\267\353\206\200\354\235\264.py" deleted file mode 100644 index 300d8a1..0000000 --- "a/BOJ/implement/17825 \354\243\274\354\202\254\354\234\204 \354\234\267\353\206\200\354\235\264/17825 \354\243\274\354\202\254\354\234\204 \354\234\267\353\206\200\354\235\264.py" +++ /dev/null @@ -1,87 +0,0 @@ -import sys -input = sys.stdin.readline - - -def calculate(): - global result - # 각 플레이어의 구간, 위치정보 - players = [[0, 0] for _ in range(5)] - # 각 경우의 수에서 포인트의 합 - sum_points = 0 - # 1턴 부터 10턴까지 실행. - for i in range(1, 11): - now = turns[i] - section, pos = players[now] - if section == -1: - return - else: - pos += dice[i] - # 0번 구역일때는 섹션이 옮겨지거나 도착하거나 이동하거나 - if section == 0: - if 20 < pos: - players[now] = [-1, -1] - elif pos == 5: - players[now] = [1, 0] - elif pos == 10: - players[now] = [3, 0] - elif pos == 15: - players[now] = [2, 0] - else: - players[now] = [section, pos] - # 1번 구역일 떄는 쭉 가서 8 이상 가면 도착. - elif section == 1: - if pos >= 8: - players[now] = [-1, -1] - # 4 이상이면 section 3 직진구간에서 칸수를 하나 빼줌.(가로구간은 사이 3칸, 세로구간은 2칸이기 때문에) - elif pos >= 4: - players[now] = [3, pos - 1] - else: - players[now] = [section, pos] - elif section == 2: - if pos >= 8: - players[now] = [-1, -1] - elif pos >= 4: - players[now] = [3, pos - 1] - else: - players[now] = [section, pos] - elif section == 3: - if pos > 6: - players[now] = [-1, -1] - else: - players[now] = [section, pos] - # 이동된 칸이 이미 말이 있던 칸이면 올바르지 않은 경우이므로 연산중지. 아니면 point합산. - nx, ny = players[now] - if nx != -1: - for k in range(1, 5): - if now == k: - continue - a, b = players[k] - if a == -1: - continue - if idx[a][b] == idx[nx][ny]: - return - sum_points += points[nx][ny] - result = max(result, sum_points) - -# 10턴 경우의 수의 조합을 turns에 저장 -def dfs(depth): - if depth == 10: - calculate() - return - # 각 턴에 1 ~ 4 중 하나의 말이 움직임. - for i in range(1, 5): - turns[depth + 1] = i - dfs(depth + 1) - - -turns = [0 for _ in range(11)] -points = [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40], -[10, 13, 16, 19], [30, 28, 27, 26], [20, 22, 24, 25, 30, 35, 40]] -idx = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], -[5, 21, 22, 23], [15, 24, 25, 26], [10, 27, 28, 29, 30, 31, 20]] - -dice = [0] + list(map(int, input().split())) -result = 0 -dfs(0) - -print(result) \ No newline at end of file diff --git "a/BOJ/implement/17837 \354\203\210\353\241\234\354\232\264\352\262\214\354\236\2042/17837 \354\203\210\353\241\234\354\232\264\352\262\214\354\236\2042.py" "b/BOJ/implement/17837 \354\203\210\353\241\234\354\232\264\352\262\214\354\236\2042/17837 \354\203\210\353\241\234\354\232\264\352\262\214\354\236\2042.py" deleted file mode 100644 index c026ce7..0000000 --- "a/BOJ/implement/17837 \354\203\210\353\241\234\354\232\264\352\262\214\354\236\2042/17837 \354\203\210\353\241\234\354\232\264\352\262\214\354\236\2042.py" +++ /dev/null @@ -1,62 +0,0 @@ -import sys -input = sys.stdin.readline - -def move_white(x, y, nx, ny): - now = chess[x][y].index(coin) - top = len(chess[x][y]) - for i in range(now, top): - coins[chess[x][y][i]][0] = nx - coins[chess[x][y][i]][1] = ny - chess[nx][ny].append(chess[x][y][i]) - for _ in range(top - now): - chess[x][y].pop() - - -def move_red(x, y, nx, ny): - now = chess[x][y].index(coin) - top = len(chess[x][y]) - for i in range(top - 1, now - 1, -1): - coins[chess[x][y][i]][0] = nx - coins[chess[x][y][i]][1] = ny - chess[nx][ny].append(chess[x][y][i]) - for _ in range(top - now): - chess[x][y].pop() - - -N, K = map(int, input().split()) -color = [list(map(int, input().split())) for _ in range(N)] -chess = [[[] for _ in range(N)] for _ in range(N)] -coins = {} -delta = ((0, 0), (0, 1), (0, -1), (-1, 0), (1, 0)) -for i in range(K): - x, y, d = map(int, input().split()) - chess[x - 1][y - 1].append(i) - coins[i] = [x - 1, y - 1, d] - -for turn in range(1, 1001): - for coin in range(K): - x, y, d = coins[coin] - nx, ny = x + delta[d][0], y + delta[d][1] - if 0 <= nx < N and 0 <= ny < N and color[nx][ny] != 2: - if color[nx][ny] == 0: - move_white(x, y, nx, ny) - else: - move_red(x, y, nx, ny) - else: - if d == 1 or d == 2: - d = ((d - 1)^1) + 1 - else: - d = ((d - 3)^1) + 3 - coins[coin][2] = d - nx, ny = x + delta[d][0], y + delta[d][1] - if 0 <= nx < N and 0 <= ny < N and color[nx][ny] != 2: - if color[nx][ny] == 0: - move_white(x, y, nx, ny) - else: - move_red(x, y, nx, ny) - - if 0 <= nx < N and 0 <= ny < N and len(chess[nx][ny]) >= 4: - print(turn) - exit() - -print(-1) \ No newline at end of file diff --git "a/BOJ/implement/20061 \353\252\250\353\205\270\353\257\270\353\205\270\353\217\204\353\257\270\353\205\2702/20061 \353\252\250\353\205\270\353\257\270\353\205\270\353\217\204\353\257\270\353\205\2702.py" "b/BOJ/implement/20061 \353\252\250\353\205\270\353\257\270\353\205\270\353\217\204\353\257\270\353\205\2702/20061 \353\252\250\353\205\270\353\257\270\353\205\270\353\217\204\353\257\270\353\205\2702.py" deleted file mode 100644 index 2513fea..0000000 --- "a/BOJ/implement/20061 \353\252\250\353\205\270\353\257\270\353\205\270\353\217\204\353\257\270\353\205\2702/20061 \353\252\250\353\205\270\353\257\270\353\205\270\353\217\204\353\257\270\353\205\2702.py" +++ /dev/null @@ -1,133 +0,0 @@ -import sys -input = sys.stdin.readline - -def move_block(t, x, y): - if t == 1: - for row in range(6): - if green_area[row][y]: - green_area[row - 1][y] = 1 - break - else: - green_area[5][y] = 1 - for col in range(6): - if blue_area[x][col]: - blue_area[x][col - 1] = 1 - break - else: - blue_area[x][5] = 1 - elif t == 2: - for row in range(6): - if green_area[row][y] or green_area[row][y + 1]: - green_area[row - 1][y], green_area[row - 1][y + 1] = 1, 1 - break - else: - green_area[5][y], green_area[5][y + 1] = 1, 1 - for col in range(6): - if blue_area[x][col]: - blue_area[x][col - 1], blue_area[x][col - 2] = 1, 1 - break - else: - blue_area[x][5], blue_area[x][4] = 1, 1 - else: - for row in range(6): - if green_area[row][y]: - green_area[row - 1][y], green_area[row - 2][y] = 1, 1 - break - else: - green_area[5][y], green_area[4][y] = 1, 1 - for col in range(6): - if blue_area[x][col] or blue_area[x + 1][col]: - blue_area[x][col - 1], blue_area[x + 1][col - 1] = 1, 1 - break - else: - blue_area[x][5], blue_area[x + 1][5] = 1, 1 - - -def check_areas(): - global answer - # 녹색영역 검사 - remove_line = [] - for i in range(5, -1, -1): - if sum(green_area[i]) == 4: - answer += 1 - for j in range(4): - green_area[i][j] = 0 - remove_line.append(i) - - remove_line.reverse() - for line in remove_line: - for i in range(line, 0, -1): - for j in range(4): - green_area[i][j] = green_area[i - 1][j] - - for i in range(4): - green_area[0][i] = 0 - # 파란영역 검사 - remove_line = [] - for i in range(5, -1, -1): - tmp = 0 - for j in range(4): - if blue_area[j][i]: - tmp += 1 - if tmp == 4: - answer += 1 - for j in range(4): - blue_area[j][i] = 0 - remove_line.append(i) - remove_line.reverse() - for line in remove_line: - for i in range(line, 0, -1): - for j in range(4): - blue_area[j][i] = blue_area[j][i - 1] - for i in range(4): - blue_area[i][0] = 0 - - -def check_zeroarea(): - global green_area - green_zeros = 0 - blue_zeros = 0 - for i in range(2): - for j in range(4): - if green_area[i][j] == 1: - green_zeros += 1 - break - for j in range(4): - if blue_area[j][i] == 1: - blue_zeros += 1 - break - for _ in range(green_zeros): - green_area.pop() - green_area = [[0, 0, 0, 0]] + green_area - for _ in range(blue_zeros): - for i in range(4): - for j in range(5, 0, -1): - blue_area[i][j] = blue_area[i][j - 1] - blue_area[i][0] = 0 - - -N = int(input()) -blocks = [tuple(map(int, input().split())) for _ in range(N)] -# 1, 2 - 가로, 3 - 세로 - -blue_area = [[0] * 6 for _ in range(4)] -green_area = [[0] * 4 for _ in range(6)] - -answer = 0 -# 블록 놓기 -for t, x, y in blocks: - move_block(t, x, y) - check_areas() - check_zeroarea() - -cnt = 0 -for i in range(4): - for j in range(6): - if blue_area[i][j]: - cnt += 1 -for i in range(6): - for j in range(4): - if green_area[i][j]: - cnt += 1 -print(answer) -print(cnt) diff --git "a/BOJ/implement/21610 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\271\204\353\260\224\353\235\274\352\270\260/21610 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\271\204\353\260\224\353\235\274\352\270\260.py" "b/BOJ/implement/21610 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\271\204\353\260\224\353\235\274\352\270\260/21610 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\271\204\353\260\224\353\235\274\352\270\260.py" deleted file mode 100644 index cc93b1c..0000000 --- "a/BOJ/implement/21610 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\271\204\353\260\224\353\235\274\352\270\260/21610 \353\247\210\353\262\225\354\202\254 \354\203\201\354\226\264\354\231\200 \353\271\204\353\260\224\353\235\274\352\270\260.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline - -N, M = map(int, input().split()) -A = [list(map(int, input().split())) for _ in range(N)] -moves = [tuple(map(int, input().split())) for _ in range(M)] -delta = ((0, 0), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)) -check = ((-1, 1), (1, 1), (-1, -1), (1, -1)) -clouds = [(N - 1, 0), (N - 1, 1), (N - 2, 0), (N - 2, 1)] -for d, s in moves: - # 구름 이동 - moved_clouds = set() - for _ in range(len(clouds)): - x, y = clouds.pop() - nx, ny = (x + delta[d][0] * s) % N, (y + delta[d][1] * s) % N - # 구름에서 비내림 - A[nx][ny] += 1 - moved_clouds.add((nx, ny)) - for x, y in moved_clouds: - tmp = 0 - for dx, dy in check: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N and A[nx][ny]: - tmp += 1 - A[x][y] += tmp - for i in range(N): - for j in range(N): - if A[i][j] >= 2 and (i, j) not in moved_clouds: - A[i][j] -= 2 - clouds.append((i, j)) -water = 0 -for i in range(N): - for j in range(N): - water += A[i][j] -print(water) \ No newline at end of file diff --git "a/BOJ/math/16943 \354\210\253\354\236\220\354\236\254\353\260\260\354\271\230/16943 \354\210\253\354\236\220\354\236\254\353\271\204\354\271\230.py" "b/BOJ/math/16943 \354\210\253\354\236\220\354\236\254\353\260\260\354\271\230/16943 \354\210\253\354\236\220\354\236\254\353\271\204\354\271\230.py" deleted file mode 100644 index 826be71..0000000 --- "a/BOJ/math/16943 \354\210\253\354\236\220\354\236\254\353\260\260\354\271\230/16943 \354\210\253\354\236\220\354\236\254\353\271\204\354\271\230.py" +++ /dev/null @@ -1,14 +0,0 @@ -import sys -import itertools -input = sys.stdin.readline - -a, b = input().split() -b = int(b) -lst = list(map(''.join, list(itertools.permutations(a)))) -c = -1 -for num in lst: - first = num[0] - num = int(num) - if b >= num and first != '0': - c = max(c, num) -print(c) \ No newline at end of file diff --git "a/BOJ/math/1990 \354\206\214\354\210\230\355\214\260\353\246\260\353\223\234\353\241\254.py/1990 \354\206\214\354\210\230 \355\214\260\353\246\260\353\223\234\353\241\254.py" "b/BOJ/math/1990 \354\206\214\354\210\230\355\214\260\353\246\260\353\223\234\353\241\254.py/1990 \354\206\214\354\210\230 \355\214\260\353\246\260\353\223\234\353\241\254.py" deleted file mode 100644 index a1683e0..0000000 --- "a/BOJ/math/1990 \354\206\214\354\210\230\355\214\260\353\246\260\353\223\234\353\241\254.py/1990 \354\206\214\354\210\230 \355\214\260\353\246\260\353\223\234\353\241\254.py" +++ /dev/null @@ -1,87 +0,0 @@ -def check_is_primary_num(num): - for i in range(2, int(num**0.5) + 1): - if num % i == 0: - return False - return True - -def check_is_palindrome(num): - is_palindrome = False - num = str(num) - if num == num[::-1]: - is_palindrome = True - return is_palindrome - -def solution(A, B): - if B > 10000000: - B = 10000000 - palindrome_numbers = [num for num in range(A, B + 1) if check_is_palindrome(num)] - primary_nums = [num for num in palindrome_numbers if check_is_primary_num(num)] - for num in primary_nums: - print(num) - print("-1") - -if __name__ == "__main__": - A, B = map(int, input().split()) - solution(A, B) - - -# 풀이 2 -from sys import stdout -print = stdout.write -a,b = map(int, input().split()) - -if b > 10000000: - b = 10000000 -def solv(): - candidate = set_candidate() - answer = [] - for num in candidate: - if a <= num <= b: - if is_prime(num): - answer.append(num) - if answer: - answer.sort() - for num in answer: - print('%d\n'%num) - print('-1') -def set_candidate(): - candidate = [] - for num in range(1,10000): - if num < 10: - if num%2==1: - candidate.append(num) - candidate.append(num*10+num) - - elif num < 100: - num1 = str(num) - num1 = int(num1+num1[::-1]) - if num1%2==1: - candidate.append(num1) - - num2 = str(num) - num2 = int(num2+num2[0]) - if num2%2==1: - candidate.append(num2) - elif num < 1000: - num1 = str(num) - num1 = int(num1 + num1[::-1]) - if num1%2==1: - candidate.append(num1) - - num2 = str(num) - num2 = int(num2+num2[1]+num2[0]) - if num2%2==1: - candidate.append(num2) - elif num < 10000: - num = str(num) - num = int(num+num[2]+num[1]+num[0]) - if num%2==1: - candidate.append(num) - - return candidate -def is_prime(num): - for i in range(2,int(num**(1/2))+1): - if num%i == 0: - return False - return True -solv() \ No newline at end of file diff --git "a/BOJ/math/3343 \354\236\245\353\257\270/3343\354\236\245\353\257\270.py" "b/BOJ/math/3343 \354\236\245\353\257\270/3343\354\236\245\353\257\270.py" deleted file mode 100644 index 06dadff..0000000 --- "a/BOJ/math/3343 \354\236\245\353\257\270/3343\354\236\245\353\257\270.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - -def buy_flower(optimal_cost): - global min_cost - queue = deque() - start_price = 0 - flower = 0 - queue.append([start_price,flower]) - while queue: - cur_price,flower = queue.popleft() - for flo_cnt,flo_cost in ((A,B),(C,D)): - if cur_price + flo_cost <= optimal_cost: - queue.append([cur_price+flo_cost,flower+flo_cnt]) - if flower+flo_cnt>=N: - if cur_price + flo_cost < min_cost: - min_cost = cur_price + flo_cost - return True - -N,A,B,C,D = map(int,input().split()) - -start = 1 -end = int(1e18) -answer = 0 -min_cost=0 -while start <= end: - mid = (start+end)//2 - if buy_flower(mid) or min_cost<=mid : - end = mid-1 - answer = mid - else: - start = mid +1 - -print(answer) \ No newline at end of file diff --git "a/BOJ/math/3343 \354\236\245\353\257\270/3343\354\236\245\353\257\270_final.py" "b/BOJ/math/3343 \354\236\245\353\257\270/3343\354\236\245\353\257\270_final.py" deleted file mode 100644 index a20b973..0000000 --- "a/BOJ/math/3343 \354\236\245\353\257\270/3343\354\236\245\353\257\270_final.py" +++ /dev/null @@ -1,36 +0,0 @@ -import sys -input = sys.stdin.readline - -N,A,B,C,D = map(int,input().split()) -min_cost = float('inf') -if B/A > D/C: - for i in range(C+1): - if N > A*i: - if (N-A*i)%C==0: - cost = B*i + D*((N-A*i)//C) - if cost C*i: - if (N-C*i)%A==0: - cost = D*i + B*((N-C*i)//A) - if cost (c/d): - return a, b, c, d - else: - return c, d, a, b - -an, bn, cn, dn = compare(A, B, C, D) - -compare_min = float('inf') - -for flower1 in range(an): - flower2 = math.ceil((N - flower1 * cn)/an) - price1 = flower1 * dn - price2 = flower2 * bn - - if price2<0: price2 = 0 - - compare_min = min(compare_min, price1+price2) - -print(compare_min) \ No newline at end of file diff --git "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264.cpp" "b/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264.cpp" deleted file mode 100644 index a5a8475..0000000 --- "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264.cpp" +++ /dev/null @@ -1,145 +0,0 @@ -#include -#include -#include -#define NMAX 300010 -#define PAIR pair -using namespace std; - -int N, C, t, sz; -vector< int > mergeTree[NMAX*4]; -int maxColor[NMAX*4]; - -PAIR tmp, vmax, ans; - -int Q, a, b; - -// 머지소트트리의 현재 인덱스(idx)에서 특정 색깔(val)의 개수 반환 -int getColorCnt(int idx, int val) { - int l, r, mid; - int idxl, idxr; - - // 가장 왼쪽에 위치한 val의 위치 구하기 - l = 0; r = mergeTree[idx].size()-1; - while(l<=r) { - mid = (l+r)/2; - - if(mergeTree[idx][mid] < val) l = mid+1; - else r = mid-1; - } - if(mergeTree[idx][l] != val) return 0; - else idxl = l; - - // 가장 오른쪽에 위치한 val의 위치 구하기 - l = 0; r = mergeTree[idx].size()-1; - while(l<=r) { - mid = (l+r)/2; - - if(mergeTree[idx][mid] <= val) l = mid+1; - else r = mid-1; - } - idxr = r; - - return (idxr-idxl)+1; - -} - -// 구간[l, r]에서 색깔(val)의 개수 가져오기 -PAIR searchColor(int l, int r, int val) { - PAIR ret; - - ret = make_pair(0, val); - while(l<=r) { - if(l%2 == 1) ret.first += getColorCnt(l++, val); - if(r%2 == 0) ret.first += getColorCnt(r--, val); - - l/=2; r/=2; - } - - return ret; -} - -// 구간[l, r]에서 가장 많은 색깔과 개수 탐색 -PAIR search(int l, int r) { - int ll, rr; - PAIR ret; - - ll = l; rr = r; - ret = make_pair(0, 0); - while(ll<=rr) { - // maxColor[ll]/maxColor[rr]의 개수 중 최댓값 구하기 - if(ll%2 == 1) ret = max( ret, searchColor(l, r, maxColor[ll++]) ); - if(rr%2 == 0) ret = max( ret, searchColor(l, r, maxColor[rr--]) ); - - ll/=2; rr/=2; - } - - return ret; -} - - -// 머지소트트리의 현재 인덱스(idx)에서 가장 많은 색깔 찾기 -void cntColor(int idx) { - if(tmp.second == mergeTree[idx].back()) tmp.first++; - else { - vmax = max( vmax, tmp ); - tmp = make_pair(1, mergeTree[idx].back()); - } -} - -int main() { - // input - scanf("%d %d", &N, &C); - for(sz=1;sz0;i--) { - int idxl, idxr, l, r; - - // 초깃값 - tmp = vmax = {0,0}; - l = i*2; r = i*2+1; - idxl = idxr = 0; - - // 머지소트 - while(idxl (b-a+1)/2) printf("yes %d\n", ans.second); - else printf("no\n"); - } -} \ No newline at end of file diff --git "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264.py" "b/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264.py" deleted file mode 100644 index e975ebf..0000000 --- "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264.py" +++ /dev/null @@ -1,45 +0,0 @@ -from sys import stdin -from random import randint - -input = stdin.readline - -n, c = map(int, input().split()) -arr = [0] + list(map(int, input().split())) -arr_inv = [[] for _ in range(c + 1)] -for i in range(1, n + 1): - arr_inv[arr[i]].append(i) -for _ in range(int(input())): - s, e = map(int, input().split()) - ans = 'no' - for _ in range(30): - k = arr[randint(s, e)] - start = 0 - end = len(arr_inv[k]) - 1 - rs = 0 - while start <= end: - mid = (start + end) // 2 - if arr_inv[k][mid] < s: - start = mid + 1 - elif arr_inv[k][mid] > s: - rs = mid - end = mid - 1 - else: - rs = mid - break - start = 0 - end = len(arr_inv[k]) - 1 - re = end - while start <= end: - mid = (start + end) // 2 - if arr_inv[k][mid] < e: - re = mid - start = mid + 1 - elif arr_inv[k][mid] > e: - end = mid - 1 - else: - re = mid - break - if (re - rs + 1) * 2 > (e - s + 1): - ans = f'yes {k}' - break - print(ans) diff --git "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/tree/2263 \355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214/2263 \355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214.py" "b/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/tree/2263 \355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214/2263 \355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214.py" deleted file mode 100644 index 9f6cb1c..0000000 --- "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/tree/2263 \355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214/2263 \355\212\270\353\246\254\354\235\230 \354\210\234\355\232\214.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**6) - -def find_tree(in_left, in_right, post_left, post_right): - if in_left > in_right or post_left > post_right: - return - root = post_order[post_right] - root_idx = in_order_idx[root] - pre_order.append(root) - left_tree_size = root_idx - in_left - find_tree(in_left, root_idx - 1, post_left, post_left - 1 + left_tree_size) - find_tree(root_idx + 1, in_right, post_left + left_tree_size, post_right - 1) - -n = int(input()) -in_order = list(map(int, input().split())) -post_order = list(map(int, input().split())) - -in_order_idx = {in_order[i]: i for i in range(n)} -pre_order = [] -find_tree(0, n - 1, 0, n - 1) -print(*pre_order) diff --git "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/tree/5639 \354\235\264\354\247\204 \352\262\200\354\203\211 \355\212\270\353\246\254/5639 \354\235\264\354\247\204 \352\262\200\354\203\211 \355\212\270\353\246\254.py" "b/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/tree/5639 \354\235\264\354\247\204 \352\262\200\354\203\211 \355\212\270\353\246\254/5639 \354\235\264\354\247\204 \352\262\200\354\203\211 \355\212\270\353\246\254.py" deleted file mode 100644 index 21c2c2b..0000000 --- "a/BOJ/mos/2912 \353\260\261\354\204\244\352\263\265\354\243\274\354\231\200 \353\202\234\354\237\201\354\235\264/tree/5639 \354\235\264\354\247\204 \352\262\200\354\203\211 \355\212\270\353\246\254/5639 \354\235\264\354\247\204 \352\262\200\354\203\211 \355\212\270\353\246\254.py" +++ /dev/null @@ -1,77 +0,0 @@ -import sys - -def dfs(pos, min_v): - ret = 0 - if pos + 1 < len(orders) and orders[pos] > orders[pos + 1]: - ret += dfs(pos + 1, min(min_v, orders[pos])) - if pos + ret + 1 < len(orders) and orders[pos] < orders[pos + ret + 1] \ - and orders[pos + ret + 1] < min_v: - ret += dfs(pos + ret + 1, min_v) - print(orders[pos]) - return ret + 1 - -sys.setrecursionlimit(10009) - -orders = [] -for v in map(int, sys.stdin.read().split()): - orders.append(v) -dfs(0, 0x3c3c3c3c) - - -# 2 -from bisect import bisect_left -import sys -sys.setrecursionlimit(100000) -input = sys.stdin.readline - -def post_order(start, end): - if start > end: - return - - root = pre_order[start] - mid = bisect_left(pre_order, root, start+1, end+1) - post_order(start+1, mid-1) - post_order(mid, end) - print(root) - -if __name__ == "__main__": - pre_order = [] - while True: - try: - x = int(input()) - pre_order.append(x) - except: - break - - post_order(0, len(pre_order)-1) - - -# 3 -import sys -sys.setrecursionlimit(1000000) - - -def pretopost(s, e): - if s >= e: - return - root = prefix[s] - if prefix[e - 1] <= root: - pretopost(s + 1, e) - print(root) - return - for i in range(s + 1, e): - if prefix[i] > root: - tmp = i - break - pretopost(s + 1, tmp) - pretopost(tmp, e) - print(root) - - -prefix = [] -while True: - try: - prefix.append(int(sys.stdin.readline())) - except: - break -pretopost(0, len(prefix)) \ No newline at end of file diff --git "a/BOJ/segment tree/1275 \354\273\244\355\224\274\354\210\2152/1275 \354\273\244\355\224\274\354\210\2152.py" "b/BOJ/segment tree/1275 \354\273\244\355\224\274\354\210\2152/1275 \354\273\244\355\224\274\354\210\2152.py" deleted file mode 100644 index ac471c7..0000000 --- "a/BOJ/segment tree/1275 \354\273\244\355\224\274\354\210\2152/1275 \354\273\244\355\224\274\354\210\2152.py" +++ /dev/null @@ -1,65 +0,0 @@ -import math -import sys - - -sys.setrecursionlimit(10 ** 8) # pypy 제출시 삭제! -input = lambda: sys.stdin.readline().rstrip() -# in_range = lambda y,x: 0<=y y: - x, y = y, x - diff = b - arr[a] - arr[a] = b - print(get(1, 0, n - 1)) - change(1, 0, n - 1) \ No newline at end of file diff --git "a/BOJ/segment tree/13548 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2546/13548 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2546.py" "b/BOJ/segment tree/13548 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2546/13548 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2546.py" deleted file mode 100644 index f3835a2..0000000 --- "a/BOJ/segment tree/13548 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2546/13548 \354\210\230\354\227\264\352\263\274\354\277\274\353\246\2546.py" +++ /dev/null @@ -1,102 +0,0 @@ -import sys -from functools import cmp_to_key -from math import sqrt - -input = sys.stdin.readline - -# 쿼리를 정렬할 때, 사용되는 대소 비교 함수 -def querysort(q1, q2): - if q1[1] // sqrtN != q2[1] // sqrtN: - # [s1 / k] < [s2 / k] - if q1[1] // sqrtN < q2[1] // sqrtN: - return 1 - else: - return -1 - else: - # [s1 / k] = [s2 / k] & e1 < e2 - if q1[2] < q2[2]: - return 1 - else: - return -1 - - # 버킷 중 위의 두 가지 조건에 처리하는 것을 앞으로 정렬 - -# 카운트 증가 -def Plus(x): - global res - if count[x] != 0: - table[count[x]] -= 1 - count[x] += 1 - table[count[x]] += 1 - res = max(res, count[x]) - -# 카운트 감소 -def Minus(x): - global res - table[count[x]] -= 1 - if count[x] == res and table[count[x]] == 0: - res -= 1 - count[x] -= 1 - table[count[x]] += 1 - -N = int(input()) -V = [0] + list(map(int, input().split())) -sqrtN = sqrt(N) - - -ans = [0] * 101010 - -# count[x] : 구간에 존재하는 x의 개수 -count = [0] * 101010 - -# table[y] : count[x] == y를 만족하는 y 개수 -table = [0] * 101010 - -# 최댓값 -res = 0 - -query = [] -Q = int(input()) -for i in range(Q): - S, E = map(int, input().split()) - query.append((i, S, E)) - -# 쿼리 정렬 (버킷) -# querysort 함수를 이용해 정렬한다 -query = sorted(query, key=cmp_to_key(querysort)) - -s = 0 -e = 0 -res = 0 - -# 투 포인터를 이용해 쿼리 처리 -for i in range(Q): - # 쿼리의 start보다 작은 동안 - while s < query[i][1]: - # -> 이므로 빼주어야 한다 - Minus(V[s]) - s += 1 - - # 쿼리의 start보다 큰 동안 - while s > query[i][1]: - # <- 이므로 더해주어야 한다 - s -= 1 - Plus(V[s]) - - # 쿼리의 end보다 작은 동안 - while e < query[i][2]: - # -> 이므로 더해주어야 한다 - e += 1 - Plus(V[e]) - - # 쿼리의 end보다 큰 동안 - while e > query[i][2]: - # <- 이므로 빼주어야 한다. - Minus(V[e]) - e -= 1 - - # 쿼리에 대한 결과 저장 - ans[query[i][0]] = res - -for i in range(Q): - print(ans[i]) \ No newline at end of file diff --git "a/BOJ/segment tree/1572 \354\244\221\354\225\231\352\260\222/1572 \354\244\221\354\225\231\352\260\222.java" "b/BOJ/segment tree/1572 \354\244\221\354\225\231\352\260\222/1572 \354\244\221\354\225\231\352\260\222.java" deleted file mode 100644 index d591347..0000000 --- "a/BOJ/segment tree/1572 \354\244\221\354\225\231\352\260\222/1572 \354\244\221\354\225\231\352\260\222.java" +++ /dev/null @@ -1,53 +0,0 @@ -import java.io.*; -import java.util.*; - -public class Main { - static int[] tree; - static final int MAX=1<<16; - static int update(int node,int start,int end,int idx,int diff){ - if(idxend) return tree[node]; - if(start==end){ - return tree[node]+=diff; - } - int m=(start+end)>>1; - return tree[node]=update(node<<1,start,m,idx,diff)+update(node<<1|1,m+1,end,idx,diff); - } - static long query(int node,int start,int end,int res){ - if(start==end) return start; - int m=(start+end)>>1; - int L=tree[node<<1]; - if(L>=res) return query(node<<1,start,m,res); - else return query(node<<1|1,m+1,end,res-L); - } - public static void main(String[] args) throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st=new StringTokenizer(br.readLine()); - - int n=Integer.parseInt(st.nextToken()); - int k=Integer.parseInt(st.nextToken()); - - int[] arr=new int[n]; - int h=(int)Math.ceil(Math.log(MAX+1)/Math.log(2)); - tree=new int[1< M: - tmp -= arr[left] - left += 1 - if tmp == M: - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/BOJ/\352\263\240\354\206\215\355\221\270\353\246\254\354\227\220\353\263\200\355\231\230/1067 \354\235\264\353\217\231/1067 \354\235\264\353\217\231.py" "b/BOJ/\352\263\240\354\206\215\355\221\270\353\246\254\354\227\220\353\263\200\355\231\230/1067 \354\235\264\353\217\231/1067 \354\235\264\353\217\231.py" deleted file mode 100644 index 689919e..0000000 --- "a/BOJ/\352\263\240\354\206\215\355\221\270\353\246\254\354\227\220\353\263\200\355\231\230/1067 \354\235\264\353\217\231/1067 \354\235\264\353\217\231.py" +++ /dev/null @@ -1,61 +0,0 @@ - import sys -from cmath import exp,pi -def fft(a): - N=len(a) - if N==1: - return a - a_even=fft(a[0::2]) - a_odd=fft(a[1::2]) - w_N=[exp(2j*pi*n/N) for n in range(N//2)] - return [a_even[n] +w_N[n]*a_odd[n] for n in range(N//2)] + [a_even[n]-w_N[n]*a_odd[n] for n in range(N//2)] - -def ifft(a): - N=len(a) - if N==1: - return a - a_even=ifft(a[0::2]) - a_odd=ifft(a[1::2]) - w_N=[exp(-2j*pi*n/N) for n in range(N//2)] - return [a_even[n] +w_N[n]*a_odd[n] for n in range(N//2)] + [a_even[n]-w_N[n]*a_odd[n] for n in range(N//2)] - -M=int(sys.stdin.readline()) -N=2*M -even=0 -for i in range(18): - if M==2**i: - even=-100 - break - elif N<2**i: - even=i - break -A=list(map(int,sys.stdin.readline().split())) -B=list(map(int,sys.stdin.readline().split())) -if even==-100: - A=A[:]+A[:] - B=B[-1::-1]+[0]*M - C=[0]*N - A_fft=fft(A) - B_fft=fft(B) - for i in range(N): - C[i]=A_fft[i]*B_fft[i] - - C_ifft=ifft(C) - for k in range(N): - C_ifft[k]=round(C_ifft[k].real/N) - max_number=max(C_ifft) -else: - N_prime=2**i - N,N_prime=N_prime,N - A=A[:]+[0]*(N-N_prime//2) - B=B[-1::-1]+[0]*(N-N_prime)+B[-1::-1] - - C=[0]*N - A_fft=fft(A) - B_fft=fft(B) - for i in range(N): - C[i]=A_fft[i]*B_fft[i] - C_ifft=ifft(C) - for k in range(N): - C_ifft[k]=round(C_ifft[k].real/N) - max_number=max(C_ifft) -print(max_number) \ No newline at end of file diff --git "a/BOJ/\352\265\254\355\230\204/16937 \353\221\220 \354\212\244\355\213\260\354\273\244.py" "b/BOJ/\352\265\254\355\230\204/16937 \353\221\220 \354\212\244\355\213\260\354\273\244.py" deleted file mode 100644 index 66583c6..0000000 --- "a/BOJ/\352\265\254\355\230\204/16937 \353\221\220 \354\212\244\355\213\260\354\273\244.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys - -h, w = map(int, input().split()) -n = int(input()) -stk = list(list(map(int, sys.stdin.readline().split())) for _ in range(n)) - -result = 0 -for i in range(n): - for j in range(i + 1, n): - r1 = max(stk[i][0], stk[i][1]) - c1 = min(stk[i][0], stk[i][1]) - r2 = max(stk[j][0], stk[j][1]) - c2 = min(stk[j][0], stk[j][1]) - - if (r1 + r2 <= h and max(c1, c2) <= w) or (max(r1, r2) <= h and c1 + c2 <= w): - result = max(result, r1*c1 + r2*c2) - if (c1 + r2 <= h and max(r1, c2) <= w) or (max(c1, r2) <= h and r1 + c2 <= w): - result = max(result, r1*c1 + r2*c2) - if (c1 + c2 <= h and max(r1, r2) <= w) or (max(c1, c2) <= h and r1 + r2 <= w): - result = max(result, r1*c1 + r2*c2) - if (r1 + c2 <= h and max(c1, r2) <= w) or (max(r1, c2) <= h and c1 + r2 <= w): - result = max(result, r1*c1 + r2*c2) - -print(result) \ No newline at end of file diff --git "a/BOJ/\353\263\274\353\241\235\352\273\215\354\247\210/1420 \355\225\231\352\265\220\352\260\200\354\247\200\353\247\210/1420 \355\225\231\352\265\220\352\260\200\354\247\200\353\247\210.cpp" "b/BOJ/\353\263\274\353\241\235\352\273\215\354\247\210/1420 \355\225\231\352\265\220\352\260\200\354\247\200\353\247\210/1420 \355\225\231\352\265\220\352\260\200\354\247\200\353\247\210.cpp" deleted file mode 100644 index ca0536f..0000000 --- "a/BOJ/\353\263\274\353\241\235\352\273\215\354\247\210/1420 \355\225\231\352\265\220\352\260\200\354\247\200\353\247\210/1420 \355\225\231\352\265\220\352\260\200\354\247\200\353\247\210.cpp" +++ /dev/null @@ -1,94 +0,0 @@ -#include -using namespace std; - -typedef pair p; -const int inf = 1e9; - -char arr[111][111]; -vector g[23232]; -int par[23232]; -map c, f; -int s = -1, t = -1; -int si, sj, ti, tj; - -int n, m; - -void addEdge(int s, int e, int x){ - g[s].push_back(e); c[{s, e}] = x; - g[e].push_back(s); c[{e, s}] = 0; -} - -int run(){ - int ret = 0; - while(1){ - memset(par, -1, sizeof par); - queue q; q.push(s); - while(q.size()){ - int now = q.front(); q.pop(); - for(auto nxt : g[now]){ - if(par[nxt] == -1 && c[{now, nxt}] - f[{now, nxt}] > 0){ - q.push(nxt); par[nxt] = now; - } - } - } - if(par[t] == -1) break; - for(int i=t; i!=s; i=par[i]){ - int a = par[i], b = i; - f[{a, b}]++; - f[{b, a}]--; - } - ret++; - } - return ret; -} - -int main(){ - ios_base::sync_with_stdio(0); cin.tie(0); - cin >> n >> m; - - int pv = 0; - for(int i=0; i> arr[i][j]; - if(arr[i][j] == 'K'){ - s = pv + 1; - si = i, sj = j; - } - if(arr[i][j] == 'H'){ - t = pv; - ti = i, tj = j; - } - pv += 2; - } - } - - if(n == 1 && m == 1){ - cout << -1; return 0; - } - if(abs(si - ti) + abs(sj - tj) == 1 || s == -1 || t == -1){ - cout << -1; return 0; - } - - for(int i=0; i None: - self.n=n - self.c=[{} for _ in range(n)] # Capacity of each edge - self.f=[{} for _ in range(n)] # Flow of each edge - self.adj=[[] for _ in range(n)] # Adjacency list of the graph - - def add_edge(self, u, v, w) -> None: # Add an edge to the graph - if w == 0 and v in self.adj[u]: return - self.c[u][v]=w - self.f[u][v]=0 - self.adj[u].append(v) - self.__add_edge(v, u, 0) - - def __add_edge(self, u, v, w) -> None: # Add an edge to the graph - if w == 0 and v in self.adj[u]: return - self.c[u][v]=w - self.f[u][v]=0 - self.adj[u].append(v) - - def mf(self, s: int, e: int) -> int: - t=0 # Total Flow - while True: - prev=[-1]*self.n - q=queue() - q.enqueue(s) - while not q.isEmpty() and prev[e]==-1: - u=q.dequeue() - for v in self.adj[u]: - if self.c[u][v]-self.f[u][v]>0 and prev[v]==-1: - q.enqueue(v) - prev[v]=u - if v==e: break - if prev[e]==-1: break - flow=float('inf') - i=e - while i!=s: - flow=min(flow, self.c[prev[i]][i]-self.f[prev[i]][i]) - i=prev[i] - i=e - while i!=s: - self.f[prev[i]][i]+=flow - self.f[i][prev[i]]-=flow - i=prev[i] - t+=flow - return t - -import sys -input = sys.stdin.readline -n,m=map(int,input().split()) -g=FlowGraph(n*m*2+2) -def valid(x,y): return 0<=x= n or nq < 0 or nq >= m: - continue - - if room[np][nq] == '.': - edge[p * m + q + 1].append(np * m + nq + 1) - - - count = 0 - for q in range(1, m, 2): - for p in range(n): - visited = [0] * (n * m + 1) - if sol(p * m + q + 1): - count += 1 - - print(empty - count) \ No newline at end of file diff --git "a/BOJ/\353\266\204\353\246\254\354\247\221\355\225\251/2162 \354\204\240\353\266\204\352\267\270\353\243\271/2162 \354\204\240\353\266\204\352\267\270\353\243\271.py" "b/BOJ/\353\266\204\353\246\254\354\247\221\355\225\251/2162 \354\204\240\353\266\204\352\267\270\353\243\271/2162 \354\204\240\353\266\204\352\267\270\353\243\271.py" deleted file mode 100644 index 40041f5..0000000 --- "a/BOJ/\353\266\204\353\246\254\354\247\221\355\225\251/2162 \354\204\240\353\266\204\352\267\270\353\243\271/2162 \354\204\240\353\266\204\352\267\270\353\243\271.py" +++ /dev/null @@ -1,63 +0,0 @@ -import sys -input = sys.stdin.readline -n = int(input()) -s = [] -parent = [] -parent_ = [] -def getParent(a): - if parent[a] == a: - return a - else: - parent[a] = getParent(parent[a]) - return parent[a] -def union(x, y): - parentX = getParent(x) - parentY = getParent(y) - if parentX > parentY: - parent[parentX] = parentY - elif parentY > parentX: - parent[parentY] = parentX -def ccw(p1, p2, p3): - temp = (p1[0] * p2[1]) + (p2[0] * p3[1]) + (p3[0] * p1[1]) - temp = temp - (p1[1] * p2[0]) - (p2[1] * p3[0]) - (p3[1] * p1[0]) - if temp > 0: - return 1 - elif temp < 0: - return -1 - else: - return 0 -def checkCross(li1, li2): - li1p1 = [li1[0], li1[1]] - li1p2 = [li1[2], li1[3]] - li2p1 = [li2[0], li2[1]] - li2p2 = [li2[2], li2[3]] - result1 = ccw(li1p1, li1p2, li2p1) * ccw(li1p1, li1p2, li2p2) - result2 = ccw(li2p1, li2p2, li1p1) * ccw(li2p1, li2p2, li1p2) - if result1 <= 0 and result2 <= 0: - if ((li1p1[0] > li2p1[0] and li1p1[0] > li2p2[0] and li1p2[0] > li2p1[0] and li1p2[0] > li2p2[0]) - or (li1p1[0] < li2p1[0] and li1p1[0] < li2p2[0] and li1p2[0] < li2p1[0] and li1p2[0] < li2p2[0])): - return False - elif ((li1p1[1] > li2p1[1] and li1p1[1] > li2p2[1] and li1p2[1] > li2p1[1] and li1p2[1] > li2p2[1]) - or (li1p1[1] < li2p1[1] and li1p1[1] < li2p2[1] and li1p2[1] < li2p1[1] and li1p2[1] < li2p2[1])): - return False - else: - return True - return False -for i in range(n): - s.append(list(map(int, input().split()))) - parent.append(i) - parent_.append(0) -for i in range(n - 1): - for j in range(i + 1, n): - if checkCross(s[i], s[j]): - union(i, j) -cnt = 0 -max_num = 0 -for i in range(n): - if parent[i] == i: - cnt += 1 - parent_[getParent(i)] += 1 - if parent_[getParent(i)] > max_num: - max_num = parent_[getParent(i)] -print(cnt) -print(max_num) \ No newline at end of file diff --git "a/BOJ/\353\266\204\355\225\240\354\240\225\353\263\265/2630 \354\203\211\354\242\205\354\235\264 \353\247\214\353\223\244\352\270\260/2630 \354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260.py" "b/BOJ/\353\266\204\355\225\240\354\240\225\353\263\265/2630 \354\203\211\354\242\205\354\235\264 \353\247\214\353\223\244\352\270\260/2630 \354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260.py" deleted file mode 100644 index d805b53..0000000 --- "a/BOJ/\353\266\204\355\225\240\354\240\225\353\263\265/2630 \354\203\211\354\242\205\354\235\264 \353\247\214\353\223\244\352\270\260/2630 \354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys - -N = int(sys.stdin.readline()) -paper = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] - -result = [] - -def solution(x, y, N) : - color = paper[x][y] - for i in range(x, x+N) : - for j in range(y, y+N) : - if color != paper[i][j] : - solution(x, y, N//2) - solution(x, y+N//2, N//2) - solution(x+N//2, y, N//2) - solution(x+N//2, y+N//2, N//2) - return - if color == 0 : - result.append(0) - else : - result.append(1) - - -solution(0,0,N) -print(result.count(0)) -print(result.count(1)) \ No newline at end of file diff --git "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/1557 \354\240\234\352\263\261 \343\204\264\343\204\264/1557\354\240\234\352\263\261\343\204\264\343\204\264.py" "b/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/1557 \354\240\234\352\263\261 \343\204\264\343\204\264/1557\354\240\234\352\263\261\343\204\264\343\204\264.py" deleted file mode 100644 index 5b80f0e..0000000 --- "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/1557 \354\240\234\352\263\261 \343\204\264\343\204\264/1557\354\240\234\352\263\261\343\204\264\343\204\264.py" +++ /dev/null @@ -1,20 +0,0 @@ -def squareNoNo(n): - p = 0 - for i in range(1, int(n ** 0.5) + 1, 1): - p += mobius[i] * (n // (i * i)) - return p -l, r = 0, 2000000000 -mobius = [0] * 1000001 -k = int(input()) -mobius[1] = 1 -for i in range(1, 1000001): - if mobius[i]: - for j in range(i * 2, 1000001, i): - mobius[j] -= mobius[i] -while l < r - 1: - mid = (l + r) // 2 - if squareNoNo(mid) < k: - l = mid - else: - r = mid -print(r) \ No newline at end of file diff --git "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/17393 \353\213\244\354\235\264\353\202\230\353\257\271 \353\241\244\353\237\254.py" "b/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/17393 \353\213\244\354\235\264\353\202\230\353\257\271 \353\241\244\353\237\254.py" deleted file mode 100644 index a19bae3..0000000 --- "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/17393 \353\213\244\354\235\264\353\202\230\353\257\271 \353\241\244\353\237\254.py" +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_right - -N = int(input()) -A = list(map(int, input().split())) -B = list(map(int, input().split())) -answer = [] -for idx, a in enumerate(A): - answer.append(bisect_right(B, a) - idx - 1) -print(*answer) \ No newline at end of file diff --git "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/2295 \354\204\270 \354\210\230\354\235\230 \355\225\251/2295 \354\204\270 \354\210\230\354\235\230 \355\225\251.py" "b/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/2295 \354\204\270 \354\210\230\354\235\230 \355\225\251/2295 \354\204\270 \354\210\230\354\235\230 \355\225\251.py" deleted file mode 100644 index 88d8bfa..0000000 --- "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/2295 \354\204\270 \354\210\230\354\235\230 \355\225\251/2295 \354\204\270 \354\210\230\354\235\230 \355\225\251.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -N = int(input()) -U = [int(input()) for _ in range(N)] -U.sort() -ab_arr = set() -for i in range(N): - for j in range(N): - ab_arr.add(U[i] + U[j]) - -for i in range(N - 1, 0, -1): - for j in range(i): - if U[i] - U[j] in ab_arr: - print(U[i]) - exit() \ No newline at end of file diff --git "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/8454 Non-Squeare Numbers/8464 Non-Squearefree Numbers.py" "b/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/8454 Non-Squeare Numbers/8464 Non-Squearefree Numbers.py" deleted file mode 100644 index a8d82d3..0000000 --- "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/8454 Non-Squeare Numbers/8464 Non-Squearefree Numbers.py" +++ /dev/null @@ -1,29 +0,0 @@ -def mobius(n): - m = [0] + [1] * n - for i in range(2, n + 1): - if m[i] == 0: continue - for j in range(2 * i, n + 1, i): - m[j] -= m[i] - return m - - -def count(m, k): - x = 0 - for i in range(2, int(k ** .5) + 1): - if m[i] == 0: continue - else: x += m[i] * (k // (i * i)) - return x - - -k = int(input()) -left = int(k * 2.5) -right = int(k * 4 if k < 10 else k * 3 if k < 104 else k * 2.6 if k < 10000 else k * 2.551) -m = mobius(int(right ** .5)) - -while left <= right: - mid = (left + right) // 2 - non = count(m, mid) - if non < k: left = mid + 1 - else: right = mid - 1 - -print(left) diff --git "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/9007 \354\271\264\353\210\204 \354\204\240\354\210\230/9007\354\271\264\353\210\204\354\204\240\354\210\230.py" "b/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/9007 \354\271\264\353\210\204 \354\204\240\354\210\230/9007\354\271\264\353\210\204\354\204\240\354\210\230.py" deleted file mode 100644 index fc20ee1..0000000 --- "a/BOJ/\354\235\264\353\266\204\355\203\220\354\203\211/9007 \354\271\264\353\210\204 \354\204\240\354\210\230/9007\354\271\264\353\210\204\354\204\240\354\210\230.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -input = sys.stdin.readline - -T = int(input()) -for _ in range(T): - k, n = map(int, input().split()) - arr = [] - for _ in range(4): - arr.append(list(map(int, input().split()))) - - one, two = set(), set() - for idx in range(0, 4, 2): - for x in arr[idx]: - for y in arr[idx+1]: - one.add(x+y) if idx == 0 else two.add(x+y) - one = sorted(list(one)) - two = sorted(list(two)) - - # 투포인터 - result = 0 - diff = sys.maxsize - i, j = 0, len(two)-1 - while i < len(one) and 0 <= j: - temp = one[i]+two[j]-k - if abs(temp) < diff: - diff = abs(temp) - result = temp + k - elif abs(temp) == diff: - result = min(result, temp+k) - if temp < 0: - i += 1 - elif temp > 0: - j -= 1 - else: - break - - print(result) \ No newline at end of file diff --git "a/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/10989 \354\210\230 \354\240\225\353\240\254\355\225\230\352\270\260/10989 \354\210\230 \354\240\225\353\240\254\355\225\230\352\270\260.py" "b/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/10989 \354\210\230 \354\240\225\353\240\254\355\225\230\352\270\260/10989 \354\210\230 \354\240\225\353\240\254\355\225\230\352\270\260.py" deleted file mode 100644 index bb4f534..0000000 --- "a/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/10989 \354\210\230 \354\240\225\353\240\254\355\225\230\352\270\260/10989 \354\210\230 \354\240\225\353\240\254\355\225\230\352\270\260.py" +++ /dev/null @@ -1,9 +0,0 @@ -import sys -n = int(sys.stdin.readline()) -b = [0] * 10001 -for i in range(n): - b[int(sys.stdin.readline())] += 1 -for i in range(10001): - if b[i] != 0: - for j in range(b[i]): - print(i) \ No newline at end of file diff --git "a/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/11866 \354\232\224\354\204\270\355\221\270\354\212\244\353\254\270\354\240\2340.py" "b/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/11866 \354\232\224\354\204\270\355\221\270\354\212\244\353\254\270\354\240\2340.py" deleted file mode 100644 index 81e64ce..0000000 --- "a/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/11866 \354\232\224\354\204\270\355\221\270\354\212\244\353\254\270\354\240\2340.py" +++ /dev/null @@ -1,14 +0,0 @@ -from collections import deque -n, k = map(int, input().split()) -s = deque([]) -for i in range(1, n + 1): - s.append(i) -print('<', end='') -while s: - for i in range(k - 1): - s.append(s[0]) - s.popleft() - print(s.popleft(), end='') - if s: - print(', ', end='') -print('>') \ No newline at end of file diff --git "a/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/1966 \355\224\204\353\246\260\355\204\260\355\201\220/1966 \355\224\204\353\246\260\355\204\260\355\201\220.py" "b/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/1966 \355\224\204\353\246\260\355\204\260\355\201\220/1966 \355\224\204\353\246\260\355\204\260\355\201\220.py" deleted file mode 100644 index c8696a9..0000000 --- "a/BOJ/\354\236\220\353\243\214\352\265\254\354\241\260/1966 \355\224\204\353\246\260\355\204\260\355\201\220/1966 \355\224\204\353\246\260\355\204\260\355\201\220.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -read = sys.stdin.readline -f = lambda: map(int, read().split()) - -for _ in range(int(read())): - n,m = f() - s = [*f()] - num = s[m] - s.reverse() - - cnt, target = 0,0 - for i in range(9,num,-1): - cnt += s.count(i) - try: - target = s.index(i,target,n) - except ValueError: - try: - target = s.index(i,0,target+1) - except ValueError: - pass - m = -m + n -1 - - if target <= m: - print(s[0:target].count(num) + s[m::].count(num) + cnt) - else: - print(s[m:target].count(num) + cnt) diff --git "a/BOJ/\354\240\225\353\240\254/11651 \354\242\214\355\221\234\354\240\225\353\240\254\355\225\230\352\270\260 2/11651 \354\242\214\355\221\234 \354\240\225\353\240\254\355\225\230\352\270\260 2.py" "b/BOJ/\354\240\225\353\240\254/11651 \354\242\214\355\221\234\354\240\225\353\240\254\355\225\230\352\270\260 2/11651 \354\242\214\355\221\234 \354\240\225\353\240\254\355\225\230\352\270\260 2.py" deleted file mode 100644 index 8dca850..0000000 --- "a/BOJ/\354\240\225\353\240\254/11651 \354\242\214\355\221\234\354\240\225\353\240\254\355\225\230\352\270\260 2/11651 \354\242\214\355\221\234 \354\240\225\353\240\254\355\225\230\352\270\260 2.py" +++ /dev/null @@ -1,8 +0,0 @@ -import sys -n = int(sys.stdin.readline()) -so = [] -for i in range(n): - so.append(list(map(int, sys.stdin.readline().split()))) -so.sort(key=lambda x: (x[1], x[0])) -for i in so: - print(i[0], i[1]) \ No newline at end of file diff --git "a/BOJ/\354\240\225\353\240\254/18869 \353\251\200\355\213\260\353\262\204\354\212\2442/18869 \353\251\200\355\213\260\353\262\204\354\212\2442.py" "b/BOJ/\354\240\225\353\240\254/18869 \353\251\200\355\213\260\353\262\204\354\212\2442/18869 \353\251\200\355\213\260\353\262\204\354\212\2442.py" deleted file mode 100644 index 69b96c2..0000000 --- "a/BOJ/\354\240\225\353\240\254/18869 \353\251\200\355\213\260\353\262\204\354\212\2442/18869 \353\251\200\355\213\260\353\262\204\354\212\2442.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -m, n = map(int, input().split()) -universe = defaultdict(int) -for _ in range(m): - planets = list(map(int, input().split())) - keys = sorted(list(set(planets))) - ranks = {keys[i]: i for i in range(len(keys))} - add = tuple([ranks[x] for x in planets]) - universe[add] += 1 - -ans = 0 -for cnt in universe.values(): - ans += cnt * (cnt - 1) // 2 -print(ans) \ No newline at end of file diff --git "a/BOJ/\354\265\234\353\214\200\354\234\240\353\237\211/11405 \354\261\205 \352\265\254\353\247\244\355\225\230\352\270\260/11405 \354\261\205 \352\265\254\353\247\244\355\225\230\352\270\260.py" "b/BOJ/\354\265\234\353\214\200\354\234\240\353\237\211/11405 \354\261\205 \352\265\254\353\247\244\355\225\230\352\270\260/11405 \354\261\205 \352\265\254\353\247\244\355\225\230\352\270\260.py" deleted file mode 100644 index c1a3cf5..0000000 --- "a/BOJ/\354\265\234\353\214\200\354\234\240\353\237\211/11405 \354\261\205 \352\265\254\353\247\244\355\225\230\352\270\260/11405 \354\261\205 \352\265\254\353\247\244\355\225\230\352\270\260.py" +++ /dev/null @@ -1,308 +0,0 @@ -import sys -from collections import deque - -n, m = map(int, sys.stdin.readline().split()) -a = list(map(int, sys.stdin.readline().split())) -b = list(map(int, sys.stdin.readline().split())) -board = [list(map(int, sys.stdin.readline().split())) for _ in range(m)] - -graph = [[] for _ in range(m + n + 2)] -for i in range(1, m + 1): - graph[0].append([i, b[i - 1]]) - - for j in range(m + 1, m + n + 1): - graph[i].append([j, float('inf')]) - -for j in range(m + 1, m + n + 1): - graph[j].append([m + n + 1, a[j - m - 1]]) - -weight = 0 -while True: - res = [float('inf')] * (m + n + 2) - res[0] = 0 - - prev = [-1] * (m + n + 2) - visit = [0] * (m + n + 2) - queue = deque([0]) - - while queue: - cur = queue.popleft() - visit[cur] = 0 - - for nxt, capacity in graph[cur]: - if 0 < cur < nxt < m + n + 1: - cost = board[cur - 1][nxt - m - 1] - elif 0 < nxt < cur < m + n + 1: - cost = -board[nxt - 1][cur - m - 1] - else: - cost = 0 - - if res[nxt] > res[cur] + cost: - res[nxt] = res[cur] + cost - prev[nxt] = cur - - if not visit[nxt]: - queue.append(nxt) - visit[nxt] = 1 - - if res[-1] == float('inf'): - break - - flow = float('inf') - nxt = m + n + 1 - while nxt: - cur = prev[nxt] - for i in range(len(graph[cur])): - if graph[cur][i][0] == nxt: - flow = min(flow, graph[cur][i][1]) - break - nxt = cur - - nxt = m + n + 1 - while nxt: - cur = prev[nxt] - - if 0 < cur < nxt < m + n + 1: - weight += flow * board[cur - 1][nxt - m - 1] - elif 0 < nxt < cur < m + n + 1: - weight -= flow * board[nxt - 1][cur - m - 1] - - for i in range(len(graph[cur])): - if graph[cur][i][0] == nxt: - graph[cur][i][1] -= flow - if graph[cur][i][1] == 0: - graph[cur].remove([nxt, 0]) - break - - for i in range(len(graph[nxt])): - if graph[nxt][i][0] == cur: - graph[nxt][i][1] += flow - break - else: - graph[nxt].append([cur, flow]) - - nxt = cur - -print(weight) - - - - -# 2 -from collections import deque - -import sys - -input = sys.stdin.readline - -N, M = map(int, input().split()) #N이 사람 M이 서점 - -S = N + M - -E = N + M + 1 - -total = N + M + 2 - -INF = 10000000 - -adj = [[] for _ in range(total)] - -dist = [[0] * total for _ in range(total)] - -capacity = [[0] * total for _ in range(total)] - -flow = [[0] * total for _ in range(total)] - -left = list(range(M)) - -right = list(range(M, N+M)) - -adj[S] = left - -adj[E] = right - -for u in range(M): - - adj[u] = right + [S] - -for u in range(M, N + M): - - adj[u] = left + [E] - -arr = list(map(int, input().split())) - -for u, cap in enumerate(arr): - - u += M - - capacity[u][E] = cap - -arr = list(map(int, input().split())) - -for u, cap in enumerate(arr): - - capacity[S][u] = cap - -for i in range(M): - - arr = list(map(int, input().split())) - - for j, d in enumerate(arr): - - j += M - - dist[i][j] = d - - dist[j][i] = -d - - capacity[i][j] = INF - -def SPFA(S, E): - - d = [INF] * total - - d[S] = 0 - - q = deque([S]) - - inqueue = [False] * total - - prev = [-1] * total - - while q: - - u = q.popleft() - - inqueue[u] = False - - for v in adj[u]: - - if capacity[u][v] - flow[u][v] > 0 and d[u] + dist[u][v] < d[v]: - - d[v] = d[u] + dist[u][v] - - prev[v] = u - - if not inqueue[v]: - - q.append(v) - - inqueue[v] = True - - return prev - -def MCMF(S, E, prev): - - ret = 0 - - minFlow = INF - - v = E - - while v != S: - - u = prev[v] - - minFlow = min(minFlow, capacity[u][v] - flow[u][v]) - - v = u - - v = E - - while v != S: - - u = prev[u] - - ret += dist[u][v] * minFlow - - flow[u][v] += minFlow - - flow[v][u] -= minFlow - - v = u - - return ret - -ans = 0 - -while 1: - - prev = SPFA(S, E) - - if prev[E] == -1: - - break - - ans += MCMF(S, E, prev) - -print(ans) - -# 3 -import sys - -def solve(graph, capacity, flow, cost, s, t): - ret = 0 - while True: - parent = [-1 for _ in range(210)] - distance = [10 ** 9 for _ in range(210)] - in_queue = [False for _ in range(210)] - queue = [s] - distance[s] = 0 - in_queue[s] = True - while queue: - temp = [] - for curr in queue: - in_queue[curr] = False - for next in graph[curr]: - if capacity[curr][next] - flow[curr][next] > 0 and distance[next] > distance[curr] + cost[curr][next]: - distance[next] = distance[curr] + cost[curr][next] - parent[next] = curr - if in_queue[next] == False: - in_queue[next] = True - temp.append(next) - queue = temp - if parent[t] == -1: - break - val = 10 ** 9 - curr = t - while curr != s: - val = min(val, capacity[parent[curr]][curr] - flow[parent[curr]][curr]) - curr = parent[curr] - curr = t - while curr != s: - ret += val * cost[parent[curr]][curr] - flow[parent[curr]][curr] += val - flow[curr][parent[curr]] -= val - curr = parent[curr] - return ret - -def main(): - n, m = map(int, sys.stdin.readline().split()) - A = list(map(int, sys.stdin.readline().split())) - B = list(map(int, sys.stdin.readline().split())) - capacity = [[0 for _ in range(210)] for _ in range(210)] - flow = [[0 for _ in range(210)] for _ in range(210)] - cost = [[0 for _ in range(210)] for _ in range(210)] - graph = [[] for _ in range(210)] - for i in range(1, m + 1): - temp = list(map(int, sys.stdin.readline().split())) - for j in range(1, n + 1): - cost[i + 100][j] = -temp[j - 1] - cost[j][i + 100] = temp[j - 1] - graph[i + 100].append(j) - graph[j].append(i + 100) - capacity[j][i + 100] = 10 ** 9 - for i in range(n): - graph[i + 1].append(0) - graph[0].append(i + 1) - capacity[0][i + 1] = A[i] - for i in range(m): - graph[i + 101].append(201) - graph[201].append(i + 101) - capacity[i + 101][201] = B[i] - ans = solve(graph, capacity, flow, cost, 0, 201) - print(ans) - return - -if __name__ == "__main__": - main() diff --git a/BinaryTree.py b/BinaryTree.py deleted file mode 100644 index b5ac58d..0000000 --- a/BinaryTree.py +++ /dev/null @@ -1,23 +0,0 @@ -#이진트리 - -def search(): - a,b = map(int,input().split()) - i=0 - j=0 - - while 1: - if (1+i*b)/(1+j*a)>a/b: - j+=1 - elif (1+i*b)/(1+j*a)a/b: - down.append(down[j]+up[i]) - j+=1 - elif up[i]/down[j] m: - continue - - clock[nextHere][cost + nextCost] = min(clock[nextHere][cost + nextCost], distance + nextTime) - - return clock - -def main(): - t = int(input()) - - for _ in range(t): - n, m, k = map(int, input().split()) - - airport = [[] for _ in range(n+1)] - clock = [[INF for _ in range(m+1)] for _ in range(n+1)] - for _ in range(k): - src, dst, cost, time = map(int, sys.stdin.readline().split()) - airport[src].append((dst, cost, time)) - - clock = dijkstra(airport, clock, n, m) - if min(clock[n]) == INF: - print("Poor KCM") - else: - print(min(clock[n])) - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/KCM_algorythm.py b/KCM_algorythm.py index a524311..061b068 100644 --- a/KCM_algorythm.py +++ b/KCM_algorythm.py @@ -1,44 +1,44 @@ -import heapq -import sys -INF = float('inf') - -def dijkstra(airport, clock, n, m): # 공항의 개수, 지원 금액 - queue = list() - heapq.heappush(queue, (1, 0, 0)) # 현재 지점, 비용, 소요 시간 - - clock[1][0] = 0 - - for cost in range(m+1): - for here in range(1, n+1): - if clock[here][cost] == INF: - continue - - distance = clock[here][cost] - for nextHere, nextCost, nextTime in airport[here]: - if cost + nextCost > m: - continue - - clock[nextHere][cost + nextCost] = min(clock[nextHere][cost + nextCost], distance + nextTime) - - return clock - -def main(): - t = int(input()) - - for _ in range(t): - n, m, k = map(int, input().split()) - - airport = [[] for _ in range(n+1)] - clock = [[INF for _ in range(m+1)] for _ in range(n+1)] - for _ in range(k): - src, dst, cost, time = map(int, sys.stdin.readline().split()) - airport[src].append((dst, cost, time)) - - clock = dijkstra(airport, clock, n, m) - if min(clock[n]) == INF: - print("Poor KCM") - else: - print(min(clock[n])) - -if __name__ == "__main__": +import heapq +import sys +INF = float('inf') + +def dijkstra(airport, clock, n, m): # 공항의 개수, 지원 금액 + queue = list() + heapq.heappush(queue, (1, 0, 0)) # 현재 지점, 비용, 소요 시간 + + clock[1][0] = 0 + + for cost in range(m+1): + for here in range(1, n+1): + if clock[here][cost] == INF: + continue + + distance = clock[here][cost] + for nextHere, nextCost, nextTime in airport[here]: + if cost + nextCost > m: + continue + + clock[nextHere][cost + nextCost] = min(clock[nextHere][cost + nextCost], distance + nextTime) + + return clock + +def main(): + t = int(input()) + + for _ in range(t): + n, m, k = map(int, input().split()) + + airport = [[] for _ in range(n+1)] + clock = [[INF for _ in range(m+1)] for _ in range(n+1)] + for _ in range(k): + src, dst, cost, time = map(int, sys.stdin.readline().split()) + airport[src].append((dst, cost, time)) + + clock = dijkstra(airport, clock, n, m) + if min(clock[n]) == INF: + print("Poor KCM") + else: + print(min(clock[n])) + +if __name__ == "__main__": main() \ No newline at end of file diff --git "a/LC169_\352\263\274\353\260\230\354\210\230.py" "b/LC169_\352\263\274\353\260\230\354\210\230.py" index cfd0001..f58e44f 100644 --- "a/LC169_\352\263\274\353\260\230\354\210\230.py" +++ "b/LC169_\352\263\274\353\260\230\354\210\230.py" @@ -1,13 +1,13 @@ -class Solution: - def majorityElement(self, nums) -> int: - if not nums: - return None - if len(nums) == 1: - return nums[0] - - half = len(nums)//2 - a = self.majorityElement(nums[:half]) - b = self.majorityElement(nums[half:]) - return [b,a][nums.count(a)>half] - -# self를 붙히는 이유는 매개변수인 nums에 대한 재귀이기 때문에? +class Solution: + def majorityElement(self, nums) -> int: + if not nums: + return None + if len(nums) == 1: + return nums[0] + + half = len(nums)//2 + a = self.majorityElement(nums[:half]) + b = self.majorityElement(nums[half:]) + return [b,a][nums.count(a)>half] + +# self를 붙히는 이유는 매개변수인 nums에 대한 재귀이기 때문에? diff --git "a/LC241\354\210\253\354\236\220\354\227\260\354\202\260\354\236\220\354\241\260\355\225\251.py" "b/LC241\354\210\253\354\236\220\354\227\260\354\202\260\354\236\220\354\241\260\355\225\251.py" index 6f25e72..097a0a0 100644 --- "a/LC241\354\210\253\354\236\220\354\227\260\354\202\260\354\236\220\354\241\260\355\225\251.py" +++ "b/LC241\354\210\253\354\236\220\354\227\260\354\202\260\354\236\220\354\241\260\355\225\251.py" @@ -1,32 +1,32 @@ -class Solution: - def diffWaysToCompute(self, input: str): - def operation(le, ri, oper): - sm = 0 - result = [] - for l in le: - for r in ri: - if oper == "+": - sm = l + r - elif oper == "-": - sm = l - r - elif oper == "*": - sm = l * r - result.append(sm) - return result - results = [] - - # 연산자없이 오직 숫자만을 가질 때 리스트 형태로 바로 반환. - if input.isdigit(): - return [int(input)] - - # 연산이 수행되는 순서에 따라 값이 달라지므로 모든 경우를 구하기 위해 반복이 필요하다. - for i in range(len(input)): - if input[i] in '+-*': - # 현재 연산자 기준으로 분할 - left = self.diffWaysToCompute(input[:i]) - right= self.diffWaysToCompute(input[i + 1:]) - - # 양쪽 결과를 병합해서 나온 값들을 넣어줌 - # 여러 값이 리스트로 나오는 것은 순서마다 나올 수 있는 값이 다르기 때문! - results.extend(operation(left, right, input[i])) +class Solution: + def diffWaysToCompute(self, input: str): + def operation(le, ri, oper): + sm = 0 + result = [] + for l in le: + for r in ri: + if oper == "+": + sm = l + r + elif oper == "-": + sm = l - r + elif oper == "*": + sm = l * r + result.append(sm) + return result + results = [] + + # 연산자없이 오직 숫자만을 가질 때 리스트 형태로 바로 반환. + if input.isdigit(): + return [int(input)] + + # 연산이 수행되는 순서에 따라 값이 달라지므로 모든 경우를 구하기 위해 반복이 필요하다. + for i in range(len(input)): + if input[i] in '+-*': + # 현재 연산자 기준으로 분할 + left = self.diffWaysToCompute(input[:i]) + right= self.diffWaysToCompute(input[i + 1:]) + + # 양쪽 결과를 병합해서 나온 값들을 넣어줌 + # 여러 값이 리스트로 나오는 것은 순서마다 나올 수 있는 값이 다르기 때문! + results.extend(operation(left, right, input[i])) return results \ No newline at end of file diff --git a/Leetcode/4 Median of Two Sorted Arrays/4 Median of Two Sorted Arrays.py b/Leetcode/4 Median of Two Sorted Arrays/4 Median of Two Sorted Arrays.py deleted file mode 100644 index 23f3927..0000000 --- a/Leetcode/4 Median of Two Sorted Arrays/4 Median of Two Sorted Arrays.py +++ /dev/null @@ -1,31 +0,0 @@ -class Solution: - def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: - if len(nums1) > len(nums2): - return self.findMedianSortedArrays(nums2, nums1) - - partitionLength = (len(nums1)+len(nums2)+1)//2 - isEven = (len(nums1)+len(nums2))%2 == 0 - - start = 0 - end = len(nums1) - while start <= end: - nums1Idx = (start+end)//2 - nums2Idx = (partitionLength - nums1Idx) - - # Edge Cases - 왼쪽 그룹이 비었으면 -INF값을, - # 오른쪽 그룹이 비었으면 +INF값을 적용 - maxLeft1 = nums1[nums1Idx-1] if nums1Idx != 0 else -987654321 - minRight1 = nums1[nums1Idx] if nums1Idx != len(nums1) else 987654321 - - maxLeft2 = nums2[nums2Idx-1] if nums2Idx != 0 else -987654321 - minRight2 = nums2[nums2Idx] if nums2Idx != len(nums2) else 987654321 - - if maxLeft1 <= minRight2 and maxLeft2 <= minRight1: - if isEven: - return (max(maxLeft1,maxLeft2)+min(minRight1,minRight2))/2 - else: - return max(maxLeft1, maxLeft2) - elif maxLeft1 > minRight2: - end = nums1Idx - 1 - else: - start = nums1Idx+1 \ No newline at end of file diff --git a/Leetcode_palindrome_pair.py b/Leetcode_palindrome_pair.py deleted file mode 100644 index 7e67580..0000000 --- a/Leetcode_palindrome_pair.py +++ /dev/null @@ -1,306 +0,0 @@ -from collections import defaultdict - - -class Node: - def __init__(self): - self.children = defaultdict(Node) - self.word_id = -1 - self.palindrome_word_ids = [] - -class Trie: - # 삽입된 word와 id를 node를 생성. 노드는 자식, word_id, 펠린드롬 단어 id를 가짐. - def __init__(self): - self.root = Node() - - # 펠린드롬을 검사하는 메서드 - @staticmethod - def is_palindrome(word): - return word == word[::-1] - - # 결국 핵심은 - def insert(self,index,word): - node = self.root - - # 단어를 뒤집어 검사하는데 만약 뒤에서 일정부분 자른 word가 펠린드롬이면 펠린드롬 단어 ids 배열에 단어의 i를 넣어줌. - for i, char in enumerate(reversed(word)): - # 다른단어 + 왼쪽 펠린드롬 부분 + 오른쪽 부분을 만족하는 단어를 찾기위함. - if self.is_palindrome(word[:len(word)-i]): - node.palindrome_word_ids.append(index) - node = node.children[char] - # 노드의 children[char]이 있으면 node로 삼고 없으면 새로 노드를 만듦 - # 다 끝나면 word_id를 i로 저장.(원배열에서 위치.) - node.word_id = index - - def search(self,index,word): - result = [] - node = self.root - - # word가 없어질때까지 순회 - while word: - # 노드의 word_id가 0 이 아니다? = 단어가 있다.(오른쪽에 붙힐 단어) - if node.word_id >= 0: - # 단어가 펠린드롬을 만족한다? - if self.is_palindrome(word): - # 결과에 단어의 idex와 거꾸로 뒤집혀 삽입된 단어의 id를 넣는다. - result.append([index,node.word_id]) - # word의 맨앞 글자가 node의 children에 없다면? - if not word[0] in node.children: - # 반환. - return result - # 다음 노드는 char의 아들 - node = node.children[word[0]] - # word맨앞 글자는 제외. - word = word[1:] - - # 다 끝났는데 단어의 id가 있다. 즉 온전히 펠린드롬을 이루는 단어가 있다면?그리고 같은 요소가 아니라면? - # 두쌍은 펠린드롬을 이루므로 결과에 삽입. - if node.word_id >= 0 and node.word_id != index: - result.append([index, node.word_id]) - - # 다 돌았는데 마지막노드에서 부분 펠린드롬을 이루는 녀석이 있었다면?(그 노드 앞쪽이 펠린드롬을 이룬다는 뜻.) - # 그 노드에서 끝난 부분 trie에 펠린드롬 워드가 있다면? 워드 + trie에 저장된 펠린드롬 워드의 왼쪽 + 오른쪽이 펠린드롬을 이룬다는 뜻. - for palindrome_word_id in node.palindrome_word_ids: - result.append([index, palindrome_word_id]) - - return result - - -# 단어 리스트에서 word[i] + word[j]가 펠린드롬이 되는 모든 인덱스 조합(i,j)를 구하라. -class Solution: - def palindromePairs(self, words): - trie = Trie() - # 각 문자열에 index 부여.(구분을 위함) 트라이에 삽입. - for i, word in enumerate(words): - trie.insert(i, word) - - results = [] - - for i, word in enumerate(words): - results.extend(trie.search(i,word)) - - return results - - - - -class Solution(object): - def palindromePairs(self, words): - ans = set() - index = {word:i for i, word in enumerate(words)} - - for i, word in enumerate(words): - for j in range(len(word)+1): - # 좌우로 나눠 왼쪽이나 오픈쪽이 펠린드롬이라면 그부분 지워버리고 남은 부분을 뒤집은 게 index에 있다면 ans에 넣는다.(index쌍으로) - (왼쪽, 오른쪽) - left = word[:j] - right = word[j:] - - # check if any other word that concat to the left will make palindrome: "OTHER_WORD+`left`+`right`" - # The above will be palindrome only if - # 1. `left` is palindrome (left==left[::-1]) - # 2. Exit an "OTHER_WORD" in word in words that equals to the reverse of `right` (right[::-1] in index and index[right[::-1]]!=i). - if left==left[::-1]: - if right[::-1] in index and index[right[::-1]]!=i: - ans.add((index[right[::-1]], i)) - - # check if any other word that concat to the right will make palindrome: "`left`+`right`+OTHER_WORD" - # The above will be palindrome only if - # 1. `right` is palindrome (right==right[::-1]) - # 2. Exit an "OTHER_WORD" in words that equals to the reverse of `left` (left[::-1] in index and index[left[::-1]]!=i). - if right==right[::-1]: - if left[::-1] in index and index[left[::-1]]!=i: - ans.add((i, index[left[::-1]])) - - return ans - - -class Solution: - def palindromePairs(self, words: List[str]) -> List[List[int]]: - rmap={w[::-1]:i for i,w in enumerate(words)} - res=[] - for i,wrd in enumerate(words): - rev=wrd[::-1] - if wrd in rmap: # same length pair - if rmap[wrd]!=i: # i and j should be distinct - res.append((i,rmap[wrd])) - for j in range(1,len(wrd)+1): # first or last j characters as palindrome, other part has pair - if wrd[:-j] in rmap and wrd[-j:]==rev[:j]: - res.append((i,rmap[wrd[:-j]])) - if wrd[j:] in rmap and wrd[:j]==rev[-j:]: - res.append((rmap[wrd[j:]],i)) - return res - -class Solution(object): - def palindromePairs(self, words): - result = set() - d = {words[x]: x for x in range(len(words))} - for i, w in enumerate(words): - rev = w[::-1] - l = len(w) - for j in range(l + 1): - if w[j:] == rev[:l-j]: - if rev[l-j:] in d: - result.add((i, d[rev[l-j:]])) - if w[:l-j] == rev[j:]: - if rev[:j] in d: - result.add((d[rev[:j]], i)) - - return [x for x in result if x[0] != x[1]] - - - - - - - -class Solution: - def palindromePairs(self, words): - the_trie = trie(node(None)) - results = [] - for k, i in enumerate(words): - the_trie.insert_word_into_trie(i, k) - for k, i in enumerate(words): - self.check_each_prefix(i, k, the_trie, results) - self.check_each_suffix(i, k, the_trie, results) - return results - - def check_each_prefix(self, word, index, the_trie, results): - idx = 0 - while idx < len(word): - if self.is_palindrome(word[:idx]): - trie_results = the_trie.find_val_in_trie(word[idx:][::-1], index) - for i in trie_results: results.append([i, index]) - idx += 1 - - def check_each_suffix(self, word, index, the_trie, results): - idx = len(word) - 1 - while idx > -1: - if self.is_palindrome(word[idx:]): - suf = word[:idx][::-1] - trie_results = the_trie.find_val_in_trie(suf, index) - for i in trie_results: - results.append([index, i]) - if suf == "": results.append([i, index]) - idx -= 1 - - def is_palindrome(self, w): - return w == w[::-1] - -class node(object): - def __init__(self, val): - self.neighbors = {} - self.suffixes_to_word_idx = set() - -class trie(object): - def __init__(self, root): - self.root = root - self.neighbors = {} - - def insert_word_into_trie(self, word, index): - current_node = self.root - if word == "": # edge case with empty string in list - n = node("") - n.suffixes_to_word_idx.add(index) - self.root.neighbors[""] = n - for k, i in enumerate(word): - if current_node.neighbors.get(i) is None: - current_node.neighbors[i] = node(i) - if k == len(word) - 1: - current_node.neighbors[i].suffixes_to_word_idx.add(index) - current_node = current_node.neighbors[i] - - def find_val_in_trie(self, word, index): - current_node = self.root - if word == "" and self.root.neighbors.get(""): # edge case with empty string in list - c = self.root.neighbors[""].suffixes_to_word_idx.copy() - if index in c: - c.remove(index) - return c - for k, i in enumerate(word): - if current_node.neighbors.get(i) is None: - break - if k == len(word) - 1: - c = current_node.neighbors[i].suffixes_to_word_idx.copy() - if index in c: - c.remove(index) - return c - current_node = current_node.neighbors[i] - return [] - - - - - - - - - - - -class TrieNode: - def __init__(self): - self.children = defaultdict(TrieNode) - # self.word = None - self.index = -1 - -class Solution: - def _buildRevTrie(self, words): - trie = TrieNode() - for i, w in enumerate(words): - p = trie - rev = w[::-1] - for c in rev: - p = p.children[c] - p.word = w - p.index = i - return trie - - def _isPalindrome(self, s): - if len(s) == 0: return True - lo, hi = 0, len(s)-1 - while lo <= hi: - if s[lo] != s[hi]: - return False - lo += 1 - hi -= 1 - return True - - def _traverseTrie(self, root, prefix, results): - # print("!") - if root.index != -1 and self._isPalindrome(prefix): - results.append(root.index) - for i in root.children: - self._traverseTrie(root.children[i], prefix+i, results) - - - def _findPairs(self, idx): - w = self.words[idx] - p = self.trie - ret = [] - i = -1 - c = "" - for i, c in enumerate(w): - if p.index != -1: - # The case where the first word is longer - if self._isPalindrome(w[i:]) and p.index != i: - ret.append(p.index) - if c not in p.children: - return ret - p = p.children[c] - - if i == len(w) - 1: - self._traverseTrie(p, "", ret) - - return [i for i in ret if i != idx] - # return ret - - def palindromePairs(self, words: List[str]) -> List[List[int]]: - self.trie = self._buildRevTrie(words) - self.words = words - - ret = [] - for i in range(len(words)): - for j in self._findPairs(i): - ret.append([i, j]) - - return ret - \ No newline at end of file diff --git a/NXM.py b/NXM.py deleted file mode 100644 index 63cfdc0..0000000 --- a/NXM.py +++ /dev/null @@ -1,3 +0,0 @@ -N = int(input()) -list_num = map(int,list(input())) -print(sum(list_num)) \ No newline at end of file diff --git a/Queue.py b/Queue.py deleted file mode 100644 index 3fd8eae..0000000 --- a/Queue.py +++ /dev/null @@ -1,89 +0,0 @@ -from SWEA4875미로 import N - - -class MyQueue: - - def __init__(self, n): - self.front = 0 - self.rear = 0 - self.n = n - self.arr = [0] * self.n - - def my_enqueue(self, data): - if self.my_isfull(): - print('Queue is full') - return - - self.rear += 1 - self.rear %= self.n - self.arr[self.rear] = data - - def my_dequeue(self): - if self.my_isempty(): - print('Queue is empty') - return - - self.front += 1 - self.front %= self.n - - return self.arr[self.front] - - def my_isempty(self): - return self.front == self.rear - - def my_isfull(self): - return (self.front - 1) % self.n == self.rear - - -for tc in range(1, 11): - _ = input() - numbers = list(map(int, input().split())) - - # 큐 생성 - queue = MyQueue(9) - for number in numbers: - queue.my_enqueue(number) - - # 반복 - playing = True - while playing: - for i in range(1, 6): - now = queue.my_dequeue() # 삭제 - nxt = max(now - i, 0) - - -class Queue: - - def __init__(self,n): - self.front = 0 - self.rear = 0 - self.n = n - self.arr = [0]*self.n - - def en_queue(self,data): - if self.isfull(): - print('Queue is full') - return - - self.rear += 1 - self.rear %= self.n - self.arr[self.rear] = data - - def de_queue(self): - if self.isempty(): - print('Queue is empty') - return - - self.front += 1 - self.front %= self.n - - return self.arr[self.front] - - def isfull(self): - return (self.front - 1) % self.n == self.rear - - def isempty(self): - return self.front == self.rear - - def peek(self): - return self.arr[self.front] \ No newline at end of file diff --git a/README.md.txt b/README.md.txt new file mode 100644 index 0000000..c0373b9 --- /dev/null +++ b/README.md.txt @@ -0,0 +1,15 @@ +1일 1 알고리즘! 생각을 구현하자! + +문제 읽고 이해하기 +문제를 익숙한 용어로 재정의하기 +어떻게 해결할지 계획 세우기 4.계획 검증하기 +프로그램으로 구현하기 +풀이를 돌아보고 개선할 방법 찾기. +-직관적이고 체계적인 접근 + +비슷한 문제를 풀어본 적 있는가? +단순한 방법에서 시작할 수 있는가? +문제를 단순화 할 수 있는가? 그림그릴수있나? 수식으로 표현할 수 있나? +문제를 분해 할 수 있을까? +뒤에서부터 생각해서 문제를 풀수있는가? +특정형태의 답만을 고려할 수 있을까? \ No newline at end of file diff --git "a/SWEA/SWEA 5248 \352\267\270\353\243\271 \353\202\230\353\210\204\352\270\260.py" "b/SWEA/SWEA 5248 \352\267\270\353\243\271 \353\202\230\353\210\204\352\270\260.py" deleted file mode 100644 index 4ef2524..0000000 --- "a/SWEA/SWEA 5248 \352\267\270\353\243\271 \353\202\230\353\210\204\352\270\260.py" +++ /dev/null @@ -1,32 +0,0 @@ - - -def find(x): - if parents[x] == x: - return x - parents[x] = find(parents[x]) - return parents[x] - -def union(x, y): - x = find(x) - y = find(y) - - if x > y: - x, y = y, x - parents[y] = x - - -for test in range(1, int(input()) + 1): - N, M = map(int, input().split()) - prefer_set = list(map(int, input().split())) - parents = {i: i for i in range(1, N + 1)} - for i in range(M): - a, b = prefer_set[i * 2], prefer_set[i * 2 + 1] - if find(a) != find(b): - union(a, b) - group = set() - for i in range(1, N + 1): - if parents[i] not in group: - x = find(i) - if x not in group: - group.add(x) - print(f'#{test} {len(group)}') \ No newline at end of file diff --git "a/SWEA/SWEA 10966 \353\254\274\353\206\200\354\235\264\353\245\274 \352\260\200\354\236\220.py" "b/SWEA/SWEA 10966 \353\254\274\353\206\200\354\235\264\353\245\274 \352\260\200\354\236\220.py" deleted file mode 100644 index c355f31..0000000 --- "a/SWEA/SWEA 10966 \353\254\274\353\206\200\354\235\264\353\245\274 \352\260\200\354\236\220.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -sys.stdin = open('input.txt') - -for test in range(1, int(input()) + 1): - N, M = map(int, input().split()) - pool = [list(input()) for _ in range(N)] - dp = [[float('inf')] * M for _ in range(N)] - answer = 0 - for i in range(N): - for j in range(M): - if pool[i][j] == 'W': - dp[i][j] = 0 - continue - if j: - dp[i][j] = min(dp[i][j-1] + 1, dp[i][j]) - if i: - dp[i][j] = min(dp[i-1][j] + 1, dp[i][j]) - - for i in range(N-1, -1, -1): - for j in range(M-1, -1, -1): - if pool[i][j] == 'W': - dp[i][j] = 0 - continue - if not j == M - 1: - dp[i][j] = min(dp[i][j+1] + 1, dp[i][j]) - if not i == N - 1: - dp[i][j] = min(dp[i+1][j] + 1, dp[i][j]) - if dp[i][j] == float('inf'): - continue - answer += dp[i][j] - - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA 1232 \354\202\254\354\271\231\354\227\260\354\202\260.py" "b/SWEA/SWEA 1232 \354\202\254\354\271\231\354\227\260\354\202\260.py" deleted file mode 100644 index 79d4c4e..0000000 --- "a/SWEA/SWEA 1232 \354\202\254\354\271\231\354\227\260\354\202\260.py" +++ /dev/null @@ -1,34 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def inorder_tree(cur_node): - if not tree[cur_node]: - return int(values[cur_node]) - left = inorder_tree(tree[cur_node][0]) - right = inorder_tree(tree[cur_node][1]) - if values[cur_node] == '-': - return left - right - elif values[cur_node] == '+': - return left + right - elif values[cur_node] == '*': - return left * right - else: - return left / right - - -for test in range(1, 11): - N = int(input()) - tree = {i: [] for i in range(1, N+1)} - values = {i: '' for i in range(1, N+1)} - for _ in range(N): - data = input().split() - values[int(data[0])] = data[1] - if len(data) == 3: - tree[int(data[0])] += [int(data[2])] - elif len(data) == 4: - tree[int(data[0])] += [int(data[2])] - tree[int(data[0])] += [int(data[3])] - - answer = int(inorder_tree(1)) - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA 1249 \353\263\264\352\270\211\353\241\234.py" "b/SWEA/SWEA 1249 \353\263\264\352\270\211\353\241\234.py" deleted file mode 100644 index 894d007..0000000 --- "a/SWEA/SWEA 1249 \353\263\264\352\270\211\353\241\234.py" +++ /dev/null @@ -1,27 +0,0 @@ -from heapq import heappush, heappop - - -def dijkstra(x, y): - heap = [] - dists[x][y] = 0 - heappush(heap, (0, 0, 0)) - while heap: - cur_dist, x, y = heappop(heap) - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N: - next_dist = cur_dist + matrix[nx][ny] - if dists[nx][ny] > next_dist: - dists[nx][ny] = next_dist - heappush(heap, (next_dist, nx, ny)) - - -for test in range(1, int(input()) + 1): - N = int(input()) - matrix = [list(map(int, list(input().rstrip()))) for _ in range(N)] - dists = [[float('inf')] * N for _ in range(N)] - - delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) - dijkstra(0, 0) - - print(f'#{test} {dists[N - 1][N - 1]}') \ No newline at end of file diff --git "a/SWEA/SWEA 1251 \355\225\230\353\202\230\353\241\234.py" "b/SWEA/SWEA 1251 \355\225\230\353\202\230\353\241\234.py" deleted file mode 100644 index f814de1..0000000 --- "a/SWEA/SWEA 1251 \355\225\230\353\202\230\353\241\234.py" +++ /dev/null @@ -1,41 +0,0 @@ -from heapq import heappop, heappush - - -def find(x): - if parents[x] == x: - return x - parents[x] = find(parents[x]) - return parents[x] - - -def union(x, y): - x = find(x) - y = find(y) - - if x > y: - x, y = y, x - parents[y] = x - - -for test in range(1, int(input()) + 1): - N = int(input()) - X = list(map(int, input().split())) - Y = list(map(int, input().split())) - parents = {i: i for i in range(N)} - E = float(input()) - edges = [] - for i in range(N - 1): - for j in range(i + 1, N): - heappush(edges, (abs(X[i] - X[j])**2 + abs(Y[i] - Y[j])**2, i, j)) - - answer = 0 - cnt = 0 - while edges: - dists, a, b = heappop(edges) - if find(a) != find(b): - union(a, b) - answer += E * dists - cnt += 1 - if cnt == N - 1: - break - print(f'#{test} {round(answer)}') diff --git "a/SWEA/SWEA 1795 \354\235\270\354\210\230\354\235\230 \354\203\235\354\235\274\355\214\214\355\213\260.py" "b/SWEA/SWEA 1795 \354\235\270\354\210\230\354\235\230 \354\203\235\354\235\274\355\214\214\355\213\260.py" deleted file mode 100644 index 319f129..0000000 --- "a/SWEA/SWEA 1795 \354\235\270\354\210\230\354\235\230 \354\203\235\354\235\274\355\214\214\355\213\260.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -sys.stdin = open('input.txt') -from heapq import heappop, heappush - - -def dijkstra(graph, start): - dp_dists = {i: float('inf') for i in range(1, N + 1)} - dp_dists[start] = 0 - heap = [] - heappush(heap, (0, start)) - while heap: - cur_dists, cur_node = heappop(heap) - for next_node, next_dist in graph[cur_node]: - dists = cur_dists + next_dist - if dp_dists[next_node] > dists: - dp_dists[next_node] = dists - heappush(heap, (dists, next_node)) - return dp_dists - - -for test in range(1, int(input()) + 1): - N, M, X = map(int, input().split()) - graph = {i: [] for i in range(1, N + 1)} - reverse_graph = {i: [] for i in range(1, N + 1)} - - for _ in range(M): - x, y, c = map(int, input().split()) - graph[x].append((y, c)) - reverse_graph[y].append((x, c)) - dist_set = dijkstra(graph, X) - re_dist_set = dijkstra(reverse_graph, X) - - max_distance = 0 - for i in range(1, N + 1): - max_distance = max(max_distance, dist_set[i] + re_dist_set[i]) - - print(f'#{test} {max_distance}') \ No newline at end of file diff --git "a/SWEA/SWEA 1949 \353\223\261\354\202\260\353\241\234 \354\241\260\354\204\261.py" "b/SWEA/SWEA 1949 \353\223\261\354\202\260\353\241\234 \354\241\260\354\204\261.py" deleted file mode 100644 index f6b5d11..0000000 --- "a/SWEA/SWEA 1949 \353\223\261\354\202\260\353\241\234 \354\241\260\354\204\261.py" +++ /dev/null @@ -1,52 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def dfs(x, y, cnt): - global answer - answer = max(answer, cnt) - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - if 0 <= nx < N and 0 <= ny < N and not visited[nx][ny] and mountain[x][y] > mountain[nx][ny]: - visited[nx][ny] = True - dfs(nx, ny, cnt + 1) - visited[nx][ny] = False - - -def new_start(candidates): - for i, j in candidates: - visited[i][j] = True - dfs(i, j, 1) - visited[i][j] = False - - -def make_climb_road(): - max_height = 0 - candidates = [] - for i in range(N): - for j in range(N): - if max_height < mountain[i][j]: - max_height = mountain[i][j] - candidates = [(i, j)] - elif max_height == mountain[i][j]: - candidates.append((i, j)) - for k in range(K + 1): - for i in range(N): - for j in range(N): - if mountain[i][j] >= k: - mountain[i][j] -= k - new_start(candidates) - mountain[i][j] += k - - -for test in range(1, int(input()) + 1): - N, K = map(int, input().split()) - mountain = [list(map(int, input().split())) for _ in range(N)] - visited = [[False] * N for _ in range(N)] - answer = 0 - - dx = [0, 0, 1, -1] - dy = [1, -1, 0, 0] - - make_climb_road() - print(f'#{test} {answer}') diff --git "a/SWEA/SWEA 1952 \354\210\230\354\230\201\354\236\245.py" "b/SWEA/SWEA 1952 \354\210\230\354\230\201\354\236\245.py" deleted file mode 100644 index 9526111..0000000 --- "a/SWEA/SWEA 1952 \354\210\230\354\230\201\354\236\245.py" +++ /dev/null @@ -1,12 +0,0 @@ -for test in range(1, int(input()) + 1): - # 0, 1, 2, 3: 1일, 1달, 3개월, 1년 - costs = list(map(int, input().split())) - annual_plans = [0] + list(map(int, input().split())) - - dp = [0] * 13 - for i in range(1, 13): - dp[i] = dp[i-1] + min(costs[0] * annual_plans[i], costs[1]) - if i > 2: - dp[i] = min(dp[i], dp[i-3] + costs[2]) - answer = min(dp[12], costs[3]) - print(f'#{test} {answer}') diff --git "a/SWEA/SWEA 1953 \355\203\210\354\243\274\353\262\224 \352\262\200\352\261\260.py" "b/SWEA/SWEA 1953 \355\203\210\354\243\274\353\262\224 \352\262\200\352\261\260.py" deleted file mode 100644 index d1acae6..0000000 --- "a/SWEA/SWEA 1953 \355\203\210\354\243\274\353\262\224 \352\262\200\352\261\260.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -sys.stdin = open('input.txt') -from collections import deque - - -def bfs(x, y, cur_type, time): - q = deque() - q.append((x, y, cur_type, time)) - visited[x][y] = True - answer = 1 - while q: - x, y, cur_type, time = q.popleft() - for direction in tunnels[cur_type]: - nx, ny = x + dx[direction], y + dy[direction] - if 0 <= nx < N and 0 <= ny < M and matrix[nx][ny] and not visited[nx][ny] and time < L: - if direction == 0 or direction == 1: - if direction ^ 1 in tunnels[matrix[nx][ny]]: - visited[nx][ny] = True - q.append((nx, ny, matrix[nx][ny], time + 1)) - answer += 1 - else: - if (direction+1) % 2 + 2 in tunnels[matrix[nx][ny]]: - visited[nx][ny] = True - q.append((nx, ny, matrix[nx][ny], time + 1)) - answer += 1 - return answer - - -for test in range(1, int(input()) + 1): - N, M, R, C, L = map(int, input().split()) - matrix = [list(map(int, input().split())) for _ in range(N)] - visited = [[False] * M for _ in range(N)] - tunnels = {1: [0, 1, 2, 3], 2: [2, 3], 3: [0, 1], 4: [2, 0], 5: [0, 3], 6: [1, 3], 7: [1, 2]} - dx = [0, 0, -1, 1] - dy = [1, -1, 0, 0] - - print(f'#{test} {bfs(R, C, matrix[R][C], 1)}') \ No newline at end of file diff --git "a/SWEA/SWEA 5120 \354\225\224\355\230\270.py" "b/SWEA/SWEA 5120 \354\225\224\355\230\270.py" deleted file mode 100644 index 5ca5cfd..0000000 --- "a/SWEA/SWEA 5120 \354\225\224\355\230\270.py" +++ /dev/null @@ -1,15 +0,0 @@ -for test in range(1,int(input())+1): - N, M, K = map(int, input().split()) - arr = list(map(int, input().split())) - i = M - for _ in range(K): - i %= N - if not i: - arr.append(arr[-1]+arr[0]) - i -= 1 - else: - arr.insert(i,arr[i-1]+arr[i]) - N += 1 - i += M - print(f'#{test}', end=' ') - print(*arr[-10:][::-1]) diff --git "a/SWEA/SWEA 5122 \354\210\230\354\227\264\355\216\270\354\247\221.py" "b/SWEA/SWEA 5122 \354\210\230\354\227\264\355\216\270\354\247\221.py" deleted file mode 100644 index 0fec132..0000000 --- "a/SWEA/SWEA 5122 \354\210\230\354\227\264\355\216\270\354\247\221.py" +++ /dev/null @@ -1,22 +0,0 @@ -for test in range(1,int(input())+1): - N, M, L = map(int, input().split()) - arr = list(map(int, input().split())) - flag = 1 - for _ in range(M): - command = input().split() - if command[0] == 'I': - arr.insert(int(command[1]),int(command[2])) - elif command[0] == 'D': - if not arr: - flag=0 - break - arr.pop(int(command[1])) - else: - arr[int(command[1])] = int(command[2]) - if len(arr) > L: - if flag: - print(f'#{test} {arr[L]}') - else: - print(f'#{test} -1') - else: - print(f'#{test} -1') diff --git "a/SWEA/SWEA 5188 \354\265\234\354\206\214\355\225\251.py" "b/SWEA/SWEA 5188 \354\265\234\354\206\214\355\225\251.py" deleted file mode 100644 index 0ca3098..0000000 --- "a/SWEA/SWEA 5188 \354\265\234\354\206\214\355\225\251.py" +++ /dev/null @@ -1,23 +0,0 @@ - -def dfs(x, y, total): - global min_sum - if total > min_sum: - return - if x == N - 1 and y == N - 1: - min_sum = min(min_sum, total) - return - for dx, dy in delta: - nx, ny = x + dx, y + dy - if nx < N and ny < N: - dfs(nx, ny, total + matrix[nx][ny]) - - -for test in range(1, int(input()) + 1): - N = int(input()) - matrix = [list(map(int, input().split())) for _ in range(N)] - - delta = ((1, 0), (0, 1)) - min_sum = float('inf') - # 총 2N - 1 칸. - dfs(0, 0, matrix[0][0]) - print(f'#{test} {min_sum}') \ No newline at end of file diff --git "a/SWEA/SWEA 5189 \354\240\204\354\236\220\354\271\264\355\212\270.py" "b/SWEA/SWEA 5189 \354\240\204\354\236\220\354\271\264\355\212\270.py" deleted file mode 100644 index 4f5beed..0000000 --- "a/SWEA/SWEA 5189 \354\240\204\354\236\220\354\271\264\355\212\270.py" +++ /dev/null @@ -1,23 +0,0 @@ - -def dfs(depth, cur_node, total): - global min_sum - if depth == N-1: - min_sum = min(min_sum, total + matrix[cur_node][0]) - return - if total > min_sum: - return - for next_node in range(N): - if not col_check[next_node]: - col_check[next_node] = True - dfs(depth + 1, next_node, total + matrix[cur_node][next_node]) - col_check[next_node] = False - - -for test in range(1, int(input()) + 1): - N = int(input()) - matrix = [list(map(int, input().split())) for _ in range(N)] - col_check = [False] * N - min_sum = float('inf') - col_check[0] = True - dfs(0, 0, 0) - print(f'#{test} {min_sum}') \ No newline at end of file diff --git "a/SWEA/SWEA 5201 \354\273\250\355\205\214\354\235\264\353\204\210 \354\232\264\353\260\230.py" "b/SWEA/SWEA 5201 \354\273\250\355\205\214\354\235\264\353\204\210 \354\232\264\353\260\230.py" deleted file mode 100644 index 683849d..0000000 --- "a/SWEA/SWEA 5201 \354\273\250\355\205\214\354\235\264\353\204\210 \354\232\264\353\260\230.py" +++ /dev/null @@ -1,17 +0,0 @@ - -for test in range(1, int(input()) + 1): - N, M = map(int, input().split()) - w = list(map(int, input().split())) - t = list(map(int, input().split())) - t.sort(reverse=True) - w.sort(reverse=True) - answer = 0 - left = 0 - for truck in t: - while left < N and truck < w[left]: - left += 1 - if left == N: break - answer += w[left] - left += 1 - - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA 5202 \355\231\224\353\254\274\353\217\204\355\201\254.py" "b/SWEA/SWEA 5202 \355\231\224\353\254\274\353\217\204\355\201\254.py" deleted file mode 100644 index e7785d2..0000000 --- "a/SWEA/SWEA 5202 \355\231\224\353\254\274\353\217\204\355\201\254.py" +++ /dev/null @@ -1,12 +0,0 @@ - -for test in range(1, int(input()) + 1): - N = int(input()) - works = [tuple(map(int, input().split())) for _ in range(N)] - works.sort(key=lambda x: (x[1], x[0])) - last_finish = 0 - cnt = 0 - for s, e in works: - if s >= last_finish: - last_finish = e - cnt += 1 - print(f'#{test} {cnt}') \ No newline at end of file diff --git "a/SWEA/SWEA 5203 \353\262\240\354\235\264\353\271\204\354\247\204 \352\262\214\354\236\204.py" "b/SWEA/SWEA 5203 \353\262\240\354\235\264\353\271\204\354\247\204 \352\262\214\354\236\204.py" deleted file mode 100644 index 3e4ab68..0000000 --- "a/SWEA/SWEA 5203 \353\262\240\354\235\264\353\271\204\354\247\204 \352\262\214\354\236\204.py" +++ /dev/null @@ -1,32 +0,0 @@ - -def check(player, num): - if player[num] == 3: - return True - - if num > 1 and player[num - 1] and player[num - 2]: - return True - if num < 9 and player[num + 1] and player[num + 2]: - return True - if num and not num==9 and player[num + 1] and player[num - 1]: - return True - return False - - -for test in range(1, int(input()) + 1): - nums = list(map(int, input().split())) - a = {i: 0 for i in range(10)} - b = {i: 0 for i in range(10)} - answer = 0 - flag = 0 - for i in range(len(nums)): - if i&1: - b[nums[i]] += 1 - if check(b, nums[i]): - answer = 2 - break - else: - a[nums[i]] += 1 - if check(a, nums[i]): - answer = 1 - break - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA 5204 \353\263\221\355\225\251\354\240\225\353\240\254.py" "b/SWEA/SWEA 5204 \353\263\221\355\225\251\354\240\225\353\240\254.py" deleted file mode 100644 index 20bf668..0000000 --- "a/SWEA/SWEA 5204 \353\263\221\355\225\251\354\240\225\353\240\254.py" +++ /dev/null @@ -1,39 +0,0 @@ - -def merge_arr(left_arr, right_arr): - global answer - if left_arr[-1] > right_arr[-1]: - answer += 1 - merge_arr = [] - left_idx, right_idx = 0, 0 - n, m = len(left_arr), len(right_arr) - - while left_idx != n and right_idx != m: - if left_arr[left_idx] <= right_arr[right_idx]: - merge_arr.append(left_arr[left_idx]) - left_idx += 1 - else: - merge_arr.append(right_arr[right_idx]) - right_idx += 1 - - if left_idx != n: - merge_arr += left_arr[left_idx:] - if right_idx != m: - merge_arr += right_arr[right_idx:] - - return merge_arr - -def divide_arr(a): - if len(a) == 1: - return a - mid = len(a) // 2 - left = divide_arr(a[:mid]) - right = divide_arr(a[mid:]) - return merge_arr(left, right) - - -for test in range(1, int(input()) + 1): - N = int(input()) - arr = list(map(int, input().split())) - answer = 0 - arr = divide_arr(arr) - print(f'#{test} {arr[N//2]} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA 5205 \355\200\265\354\240\225\353\240\254.py" "b/SWEA/SWEA 5205 \355\200\265\354\240\225\353\240\254.py" deleted file mode 100644 index 83a4a4c..0000000 --- "a/SWEA/SWEA 5205 \355\200\265\354\240\225\353\240\254.py" +++ /dev/null @@ -1,26 +0,0 @@ - - -def quick_sort(a, left, right): - if left < right: - pivot = a[left] - start = left + 1 - end = right - while start <= end: - while start <= end and a[start] <= pivot: - start += 1 - while start <= end and a[end] >= pivot: - end -= 1 - if start <= end: - a[start], a[end] = a[end], a[start] - a[left], a[end] = a[end], pivot - mid = end - quick_sort(a, left, mid - 1) - quick_sort(a, mid + 1, right) - - -for test_case in range(1, int(input()) + 1): - n = int(input()) - arr = list(map(int, input().split())) - - quick_sort(arr, 0, len(arr) - 1) - print(f'#{test_case} {arr[n//2]}') \ No newline at end of file diff --git "a/SWEA/SWEA 5207 \354\235\264\354\247\204\355\203\220\354\203\211.py" "b/SWEA/SWEA 5207 \354\235\264\354\247\204\355\203\220\354\203\211.py" deleted file mode 100644 index ff5900d..0000000 --- "a/SWEA/SWEA 5207 \354\235\264\354\247\204\355\203\220\354\203\211.py" +++ /dev/null @@ -1,24 +0,0 @@ - - - -for test in range(1, int(input()) + 1): - N, M = map(int, input().split()) - A = sorted(list(map(int, input().split()))) - B = list(map(int, input().split())) - answer = 0 - for num in B: - left, right, flag = 0, N - 1, 2 - while left <= right: - mid = (left + right) // 2 - if A[mid] == num: - answer += 1 - break - if num < A[mid]: - right = mid - 1 - if flag == 1: break - flag = 1 - elif num > A[mid]: - left = mid + 1 - if not flag: break - flag = 0 - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA 5208 \354\240\204\352\270\260\353\262\204\354\212\2442.py" "b/SWEA/SWEA 5208 \354\240\204\352\270\260\353\262\204\354\212\2442.py" deleted file mode 100644 index db0b1c8..0000000 --- "a/SWEA/SWEA 5208 \354\240\204\352\270\260\353\262\204\354\212\2442.py" +++ /dev/null @@ -1,11 +0,0 @@ - - -for test in range(1, int(input()) + 1): - N, *battery = map(int, input().split()) - dp = [float('inf')] * N - dp[N - 1] = 0 - for i in range(N - 1, -1, -1): - for j in range(i - 1, -1, -1): - if j + battery[j] >= i: - dp[j] = min(dp[j], dp[i] + 1) - print(f'#{test} {dp[0] - 1}') diff --git "a/SWEA/SWEA 5209 \354\265\234\354\206\214 \354\203\235\354\202\260 \353\271\204\354\232\251.py" "b/SWEA/SWEA 5209 \354\265\234\354\206\214 \354\203\235\354\202\260 \353\271\204\354\232\251.py" deleted file mode 100644 index 7205789..0000000 --- "a/SWEA/SWEA 5209 \354\265\234\354\206\214 \354\203\235\354\202\260 \353\271\204\354\232\251.py" +++ /dev/null @@ -1,21 +0,0 @@ -def dfs(depth, total): - global min_sum - if depth == N: - min_sum = min(min_sum, total) - return - if total > min_sum: - return - for next_node in range(N): - if not col_check[next_node]: - col_check[next_node] = True - dfs(depth + 1, total + matrix[depth][next_node]) - col_check[next_node] = False - - -for test in range(1, int(input()) + 1): - N = int(input()) - matrix = [list(map(int, input().split())) for _ in range(N)] - col_check = [False] * N - min_sum = float('inf') - dfs(0, 0) - print(f'#{test} {min_sum}') \ No newline at end of file diff --git "a/SWEA/SWEA 5247 \354\227\260\354\202\260.py" "b/SWEA/SWEA 5247 \354\227\260\354\202\260.py" deleted file mode 100644 index f72c32c..0000000 --- "a/SWEA/SWEA 5247 \354\227\260\354\202\260.py" +++ /dev/null @@ -1,20 +0,0 @@ -from collections import deque - -def bfs(start): - q = deque() - q.append((start, 0)) - visited = set() - visited.add(start) - while q: - cur_node, cnt = q.popleft() - for next_node in (cur_node + 1, cur_node - 1, cur_node * 2, cur_node - 10): - if next_node <= int(1e6) and next_node not in visited: - visited.add(next_node) - q.append((next_node, cnt + 1)) - if next_node == M: - return cnt + 1 - - -for test in range(1, int(input()) + 1): - N, M = map(int, input().split()) - print(f'#{test} {bfs(N)}') \ No newline at end of file diff --git "a/SWEA/SWEA 5249 \354\265\234\354\206\214 \354\213\240\354\236\245 \355\212\270\353\246\254.py" "b/SWEA/SWEA 5249 \354\265\234\354\206\214 \354\213\240\354\236\245 \355\212\270\353\246\254.py" deleted file mode 100644 index 745ad64..0000000 --- "a/SWEA/SWEA 5249 \354\265\234\354\206\214 \354\213\240\354\236\245 \355\212\270\353\246\254.py" +++ /dev/null @@ -1,34 +0,0 @@ -from heapq import heappop, heappush - - -def find(x): - if parents[x] == x: - return x - parents[x] = find(parents[x]) - return parents[x] - - -def union(a, b): - a = find(a) - b = find(b) - - if a > b: - a, b = b, a - parents[b] = a - - -for test in range(1, int(input()) + 1): - V, E = map(int, input().split()) - parents = {i: i for i in range(V + 1)} - edges = [] - for __ in range(E): - a, b, w = map(int, input().split()) - heappush(edges, (w, a, b)) - - answer = 0 - while edges: - w, a, b = heappop(edges) - if find(a) != find(b): - union(a, b) - answer += w - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA 5250 \354\265\234\354\206\214 \353\271\204\354\232\251.py" "b/SWEA/SWEA 5250 \354\265\234\354\206\214 \353\271\204\354\232\251.py" deleted file mode 100644 index f133cb4..0000000 --- "a/SWEA/SWEA 5250 \354\265\234\354\206\214 \353\271\204\354\232\251.py" +++ /dev/null @@ -1,27 +0,0 @@ -from heapq import heappush, heappop - -def dijkstra(x, y): - heap = [] - dists[x][y] = 0 - heappush(heap, (0, 0, 0)) - while heap: - cur_dist, x, y = heappop(heap) - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < N and 0 <= ny < N: - cost = max(0, matrix[nx][ny] - matrix[x][y]) + 1 - next_dist = cur_dist + cost - if dists[nx][ny] > next_dist: - dists[nx][ny] = next_dist - heappush(heap, (next_dist, nx, ny)) - - -for test in range(1, int(input()) + 1): - N = int(input()) - matrix = [list(map(int, input().split())) for __ in range(N)] - dists = [[float('inf')] * N for __ in range(N)] - - delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) - dijkstra(0, 0) - - print(f'#{test} {dists[N-1][N-1]}') \ No newline at end of file diff --git "a/SWEA/SWEA 5251 \354\265\234\354\206\214 \354\235\264\353\217\231 \352\261\260\353\246\254.py" "b/SWEA/SWEA 5251 \354\265\234\354\206\214 \354\235\264\353\217\231 \352\261\260\353\246\254.py" deleted file mode 100644 index f4f867a..0000000 --- "a/SWEA/SWEA 5251 \354\265\234\354\206\214 \354\235\264\353\217\231 \352\261\260\353\246\254.py" +++ /dev/null @@ -1,26 +0,0 @@ -from heapq import heappush, heappop - -def dijkstra(start): - heap = [] - dists[start] = 0 - heappush(heap, (0, start)) - while heap: - cur_dist, cur_node = heappop(heap) - for next_node, next_dist in graph[cur_node]: - dist = cur_dist + next_dist - if dists[next_node] > dist: - dists[next_node] = dist - heappush(heap, (dist, next_node)) - - -for test in range(1, int(input()) + 1): - N, E = map(int, input().split()) - graph = {i: [] for i in range(N + 1)} - for __ in range(E): - a, b, c = map(int, input().split()) - graph[a].append((b, c)) - dists = {i : float('inf') for i in range(N + 1)} - - dijkstra(0) - - print(f'#{test} {dists[N]}') \ No newline at end of file diff --git "a/SWEA/SWEA 5356\354\235\230\354\204\235\354\235\264\354\235\230 \354\204\270\353\241\234\353\241\234 \353\247\220\355\225\264\354\232\224.py" "b/SWEA/SWEA 5356\354\235\230\354\204\235\354\235\264\354\235\230 \354\204\270\353\241\234\353\241\234 \353\247\220\355\225\264\354\232\224.py" deleted file mode 100644 index 326ac77..0000000 --- "a/SWEA/SWEA 5356\354\235\230\354\204\235\354\235\264\354\235\230 \354\204\270\353\241\234\353\241\234 \353\247\220\355\225\264\354\232\224.py" +++ /dev/null @@ -1,14 +0,0 @@ -def read_vertical(s): - answer = '' - cnt = 0 - while cnt <= 15: - for string in s: - if string: - answer += string.pop(0) - cnt+=1 - return answer - - -for test in range(1, int(input())+1): - strings = list(list(input()) for _ in range(5)) - print(f'#{test} {read_vertical(strings)}') \ No newline at end of file diff --git "a/SWEA/SWEA 7465 \354\260\275\354\232\251\353\247\210\354\235\204\353\254\264\353\246\254\354\235\230\352\260\234\354\210\230.py" "b/SWEA/SWEA 7465 \354\260\275\354\232\251\353\247\210\354\235\204\353\254\264\353\246\254\354\235\230\352\260\234\354\210\230.py" deleted file mode 100644 index 711943e..0000000 --- "a/SWEA/SWEA 7465 \354\260\275\354\232\251\353\247\210\354\235\204\353\254\264\353\246\254\354\235\230\352\260\234\354\210\230.py" +++ /dev/null @@ -1,29 +0,0 @@ -def find(x): - if parents[x] == x: - return x - parents[x] = find(parents[x]) - return parents[x] - -def union(x, y): - x = find(x) - y = find(y) - - if x > y: - x, y = y, x - parents[y] = x - - -for test in range(1, int(input()) + 1): - N, M = map(int, input().split()) - parents = {i: i for i in range(1, N + 1)} - for i in range(M): - a, b = map(int, input().split()) - if find(a) != find(b): - union(a, b) - group = set() - for i in range(1, N + 1): - if parents[i] not in group: - x = find(i) - if x not in group: - group.add(x) - print(f'#{test} {len(group)}') \ No newline at end of file diff --git a/SWEA/SWEA1208_flattern.py b/SWEA/SWEA1208_flattern.py deleted file mode 100644 index 3ee774e..0000000 --- a/SWEA/SWEA1208_flattern.py +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heapify, heappop,heappush - -for test in range(1,11): - dump = int(input()) - boxes = list(map(int,input().split())) - minus_boxes = list(map(lambda x:-x,boxes)) - heapify(boxes) - heapify(minus_boxes) - - for _ in range(dump): - highest_point = -heappop(minus_boxes) - lowest_point = heappop(boxes) - heappush(minus_boxes,-(highest_point-1)) - heappush(boxes,lowest_point+1) - - print(f'#{test} {-heappop(minus_boxes)-heappop(boxes)}') \ No newline at end of file diff --git "a/SWEA/SWEA1209\355\226\211\353\240\254\355\225\251\352\265\254\355\225\230\352\270\260.py" "b/SWEA/SWEA1209\355\226\211\353\240\254\355\225\251\352\265\254\355\225\230\352\270\260.py" deleted file mode 100644 index 5acc2d2..0000000 --- "a/SWEA/SWEA1209\355\226\211\353\240\254\355\225\251\352\265\254\355\225\230\352\270\260.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def find_max(arr): - max_sum = 0 - # 행 조사 - for row in range(100): - sum_row = sum(arr[row]) - if max_sum < sum_row: - max_sum = sum_row - # 열 조사 - for column in range(100): - sum_column = sum([k for k in zip(*arr)][column]) - if max_sum < sum_column: - max_sum = sum_column - - # 대각선 조사 - sum_diagonal1 = 0 - sum_diagonal2 = 0 - for i in range(100): - sum_diagonal1 += arr[i][i] - sum_diagonal2 += arr[i][99-i] - if max_sum < sum_diagonal1: - max_sum = sum_diagonal1 - if max_sum < sum_diagonal2: - max_sum = sum_diagonal2 - - return max_sum - - -for _ in range(10): - test = int(input()) - matrix = [list(map(int, input().split())) for _ in range(100)] - print(f'#{test} {find_max(matrix)}') diff --git a/SWEA/SWEA1210ladder1.py b/SWEA/SWEA1210ladder1.py deleted file mode 100644 index 97fb9fd..0000000 --- a/SWEA/SWEA1210ladder1.py +++ /dev/null @@ -1,41 +0,0 @@ -import sys -sys.stdin = open('input.txt') -from collections import deque - - -def find_start(ladder): - for i in range(100): - for j in range(100): - if ladder[i][j] == 2: - return i, j - - -# 사다리게임을 합니다. -def do_ladder_game(ladder): - visited = [[False for _ in range(100)] for _ in range(100)] - init_x, init_y = find_start(ladder) # 도착지를 찾습니다. - - dx = [0, 0, -1] - dy = [1, -1, 0] - - queue = deque() - queue.append([init_x, init_y]) # 도착지부터 역사다리 게임을 합니다. - visited[init_x][init_y] = True - while queue: - x, y = queue.popleft() - if not x: - return y - for i in range(3): # 좌우를 먼저 살피고 못가면 위로갑니다. - nx = x + dx[i] - ny = y + dy[i] - if 0 <= nx < 100 and 0 <= ny < 100 and not visited[nx][ny] and ladder[nx][ny] == 1: - visited[nx][ny] = True - queue.append([nx, ny]) - break # 갔으면 다른 선택지로 분기가 나뉘는 것을 막습니다. - - -for _ in range(1, 11): - test = int(input()) - ladder = [list(map(int, input().split())) for _ in range(100)] - print(f'#{test} {do_ladder_game(ladder)}') - diff --git "a/SWEA/SWEA1216 \355\232\214\353\254\2702.py" "b/SWEA/SWEA1216 \355\232\214\353\254\2702.py" deleted file mode 100644 index b0a6a1d..0000000 --- "a/SWEA/SWEA1216 \355\232\214\353\254\2702.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def find_palindrome(sentences): - for k in range(100, 0, -1): - for i in range(100): - for j in range(100-k+1): - if sentences[i][j] == sentences[i][j+k-1]: - left = j - right = j+k-1 - while sentences[i][left] == sentences[i][right] and left <= right: - left += 1 - right -= 1 - if left < right: - continue - else: - max_length = k - return max_length - - -for _ in range(10): - test = int(input()) - palindrome = [list(input().rstrip()) for _ in range(100)] - result1 = find_palindrome(palindrome) - reverse_palindrome = list(zip(*palindrome)) - result2 = find_palindrome(reverse_palindrome) - print(f"#{test} {max(result1,result2)}") diff --git "a/SWEA/SWEA1219\352\270\270\354\260\276\352\270\260.py" "b/SWEA/SWEA1219\352\270\270\354\260\276\352\270\260.py" deleted file mode 100644 index 5a0ee5c..0000000 --- "a/SWEA/SWEA1219\352\270\270\354\260\276\352\270\260.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def dfs(v): - if v == 99: - return True - for u in graph[v]: - if not visited[u]: - visited[u] = True - if dfs(u): - return True - - -for _ in range(10): - test, edge_n = map(int, input().split()) - graph = {i: [] for i in range(100)} - edge_set = list(map(int, input().split())) - visited = {i: False for i in range(100)} - for i in range(0, edge_n*2, 2): - graph[edge_set[i]] += [edge_set[i+1]] - print(f'#{test}', end=' ') - visited[0] = True - print(1 if dfs(0) else 0) diff --git a/SWEA/SWEA1220magnetic.py b/SWEA/SWEA1220magnetic.py deleted file mode 100644 index 04382d0..0000000 --- a/SWEA/SWEA1220magnetic.py +++ /dev/null @@ -1,44 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def move_block(): - check = 0 - new_struck = 0 - for i in range(N): - for j in range(N): - if not i == 99 and matrix[i][j] == 1: - if not matrix[i+1][j]: - matrix[i][j], matrix[i+1][j] = matrix[i+1][j], matrix[i][j] - check = 1 - elif matrix[i+1][j] == 1: - matrix[i][j] = 0 - check = 1 - else: - matrix[i][j],matrix[i+1][j] = 0, 0 - new_struck += 1 - check = 1 - elif not i == 0 and matrix[i][j] == 2: - if not matrix[i-1][j]: - matrix[i][j], matrix[i - 1][j] = matrix[i - 1][j], matrix[i][j] - check = 1 - elif matrix[i-1][j] == 2: - matrix[i][j] = 0 - check = 1 - else: - matrix[i][j],matrix[i-1][j] = 0, 0 - new_struck += 1 - check = 1 - return check, new_struck - - -for test in range(1,11): - N = int(input()) - # 파란색은 N 쪽으로 빨간색은 S 쪽으로 교착상태의 갯수? - matrix = [list(map(int, input().split())) for _ in range(N)] - answer = 0 - flag = 1 - while flag: - flag, check_point = move_block() - answer += check_point - print(f'#{test} {answer}') diff --git "a/SWEA/SWEA1223\352\263\204\354\202\260\352\270\2602.py" "b/SWEA/SWEA1223\352\263\204\354\202\260\352\270\2602.py" deleted file mode 100644 index 43541b3..0000000 --- "a/SWEA/SWEA1223\352\263\204\354\202\260\352\270\2602.py" +++ /dev/null @@ -1,43 +0,0 @@ -def calculate(post_ex): - n = len(post_ex) - stack = [] - for i in range(n): - # 숫자면 stack - if post_ex[i].isdigit(): - stack.append(post_ex[i]) - else: - # 곱하기 나오면 두개빼서 곱하고 다시 넣음 - if post_ex[i] == '*': - stack.append(int(stack.pop()) * int(stack.pop())) - # 더하기 나오면 두개 빼서 더하고 다시 넣음 - elif post_ex[i] == '+': - stack.append(int(stack.pop()) + int(stack.pop())) - else: - stack.pop() - return stack[0] - - -def make_post(expression): - isp = {'+': 1, '-': 1, '*': 2, '/': 2, ')': 0, '(': 0} - icp = {'+': 1, '-': 1, '*': 2, '/': 2, ')': 0, '(': 3} - stack = [] - ans = "" - for s in expression: - if s.isdigit(): - ans += s - elif s == ')': - while stack and stack[-1] != '(': - ans += stack.pop() - stack.pop() - else: - while stack and icp[s] <= isp[stack[-1]]: - ans += stack.pop() - stack.append(s) - while stack: - ans += stack.pop() - return ans - - -for test in range(1, 11): - n = int(input()) - print(f'#{test} {calculate(make_post(input()))}') \ No newline at end of file diff --git "a/SWEA/SWEA1225 \354\225\224\355\230\270\354\203\235\354\204\261\352\270\260.py" "b/SWEA/SWEA1225 \354\225\224\355\230\270\354\203\235\354\204\261\352\270\260.py" deleted file mode 100644 index ad68d3c..0000000 --- "a/SWEA/SWEA1225 \354\225\224\355\230\270\354\203\235\354\204\261\352\270\260.py" +++ /dev/null @@ -1,27 +0,0 @@ -from collections import deque - -for _ in range(10): - test = int(input()) - arr = deque(list(map(int, input().split()))) - cnt = 0 - while arr[-1] > 0: - arr.rotate(-1) - arr[-1] -= cnt%5+1 - cnt += 1 - arr[-1] = 0 - print(f'#{test}',*arr) - - -# for _ in range(10): -# test = int(input()) -# arr = list(map(int, input().split())) -# idx = -1 -# cnt = 0 -# while arr[idx] > 0: -# idx += 1 -# idx %= 8 -# arr[idx] -= cnt % 5 + 1 -# cnt += 1 -# arr[idx] = 0 -# answer = arr[idx+1:] + arr[:idx+1] -# print(f'#{test}', *answer) \ No newline at end of file diff --git "a/SWEA/SWEA1231 \354\244\221\354\234\204\354\210\234\355\232\214.py" "b/SWEA/SWEA1231 \354\244\221\354\234\204\354\210\234\355\232\214.py" deleted file mode 100644 index d899cd4..0000000 --- "a/SWEA/SWEA1231 \354\244\221\354\234\204\354\210\234\355\232\214.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def inorder_tree(cur_node): - if not tree[cur_node]: - return values[cur_node] - elif len(tree[cur_node]) == 1: - return inorder_tree(tree[cur_node][0]) + values[cur_node] - return inorder_tree(tree[cur_node][0]) + values[cur_node] + inorder_tree(tree[cur_node][1]) - - -for test in range(1, 11): - N = int(input()) - tree = {i: [] for i in range(1, N+1)} - values = {i: '' for i in range(1, N+1)} - for _ in range(N): - data = input().split() - values[int(data[0])] = data[1] - if len(data) == 3: - tree[int(data[0])] += [int(data[2])] - elif len(data) == 4: - tree[int(data[0])] += [int(data[2])] - tree[int(data[0])] += [int(data[3])] - - answer = inorder_tree(1) - print(f'#{test} {answer}') diff --git "a/SWEA/SWEA1234\353\271\204\353\260\200\353\262\210\355\230\270.py" "b/SWEA/SWEA1234\353\271\204\353\260\200\353\262\210\355\230\270.py" deleted file mode 100644 index 24582a2..0000000 --- "a/SWEA/SWEA1234\353\271\204\353\260\200\353\262\210\355\230\270.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -for test in range(1,11): - s, nums = input().split() - nums = list(nums) # 비밀번호 list - stack = [] # 옮겨담을 stack - - while nums: - stack.append(nums.pop()) # 일단 pop - while nums and stack and stack[-1] == nums[-1]: # 같은 문자가 나오면 양쪽 다 제거. 틀린게 나올때까지 혹은 빌때까지 - stack.pop() - nums.pop() - print(f"#{test} {''.join(stack)[::-1]}") # stack 에 역순으로 담긴 password 뒤집어 출력 - diff --git "a/SWEA/SWEA1859\353\260\261\353\247\214\354\236\245\354\236\220\355\224\204\353\241\234\354\240\235\355\212\270.py" "b/SWEA/SWEA1859\353\260\261\353\247\214\354\236\245\354\236\220\355\224\204\353\241\234\354\240\235\355\212\270.py" deleted file mode 100644 index 12e7e1a..0000000 --- "a/SWEA/SWEA1859\353\260\261\353\247\214\354\236\245\354\236\220\355\224\204\353\241\234\354\240\235\355\212\270.py" +++ /dev/null @@ -1,12 +0,0 @@ -for test in range(1,int(input())+1): - N = int(input()) - prices = list(map(int, input().split())) - answer = 0 - max_price = 0 - for j in range(N-1,-1,-1): - if max_price > prices[j]: - answer += max_price - prices[j] - else: - max_price = prices[j] - - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA1945\354\206\214\354\235\270\354\210\230\353\266\204\355\225\264.py" "b/SWEA/SWEA1945\354\206\214\354\235\270\354\210\230\353\266\204\355\225\264.py" deleted file mode 100644 index 71f67a5..0000000 --- "a/SWEA/SWEA1945\354\206\214\354\235\270\354\210\230\353\266\204\355\225\264.py" +++ /dev/null @@ -1,12 +0,0 @@ -for test in range(1, int(input())+1): - N = int(input()) - prime_nums = [2, 3, 5, 7, 11] - answer_arr = [] - for num in prime_nums: - cnt = 0 - while not N % num: - N = N//num - cnt += 1 - answer_arr.append(cnt) - print(f'#{test}',end=" ") - print(*answer_arr) \ No newline at end of file diff --git "a/SWEA/SWEA1954\353\213\254\355\214\275\354\235\264.py" "b/SWEA/SWEA1954\353\213\254\355\214\275\354\235\264.py" deleted file mode 100644 index 7caec29..0000000 --- "a/SWEA/SWEA1954\353\213\254\355\214\275\354\235\264.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def make_snail(n): - dx = [0, 1, 0, -1] - dy = [1, 0, -1, 0] - complete_snail = [[0 for _ in range(n)] for _ in range(n)] - - # 0,0 에서 초기화 - cnt = 1 - direction = 0 - x, y = 0, 0 - complete_snail[x][y] = cnt - - # cnt 가 모든 칸에 기록될때까지 - while cnt != N**2: - - nx = x + dx[direction] - ny = y + dy[direction] - - if 0 <= nx < N and 0 <= ny < N and not complete_snail[nx][ny]: - cnt += 1 - complete_snail[nx][ny] = cnt - x, y = nx, ny - else: # 진입 못하면 방향 시계방향 전환 - direction = (direction+1) % 4 - - return complete_snail - - -for test in range(1, int(input())+1): - N = int(input()) - snail = make_snail(N) - print(f'#{test}') - for i in range(N): - print(*snail[i]) diff --git "a/SWEA/SWEA1961\354\210\253\354\236\220\353\260\260\354\227\264\355\232\214\354\240\204.py" "b/SWEA/SWEA1961\354\210\253\354\236\220\353\260\260\354\227\264\355\232\214\354\240\204.py" deleted file mode 100644 index 0cfafc4..0000000 --- "a/SWEA/SWEA1961\354\210\253\354\236\220\353\260\260\354\227\264\355\232\214\354\240\204.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -def rotate_clock(n, matrix): - rot90 = [k[::-1] for k in zip(*matrix)] - rot180 = [k[::-1] for k in zip(*rot90)] - rot270 = [k[::-1] for k in zip(*rot180)] - merge_matrix = [[] for _ in range(n)] - for matrix in rot90,rot180,rot270: - for i in range(n): - merge_matrix[i].append(''.join(map(str,matrix[i]))) - return merge_matrix - -for test in range(1,int(input())+1): - N = int(input()) - matrix = [list(map(int,input().split())) for _ in range(N)] - print(f'#{test}') - answer = rotate_clock(N, matrix) - for row in answer: - print(*row) \ No newline at end of file diff --git "a/SWEA/SWEA1966\354\210\253\354\236\220\354\240\225\353\240\254.py" "b/SWEA/SWEA1966\354\210\253\354\236\220\354\240\225\353\240\254.py" deleted file mode 100644 index 16e0a57..0000000 --- "a/SWEA/SWEA1966\354\210\253\354\236\220\354\240\225\353\240\254.py" +++ /dev/null @@ -1,146 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -# 선택정렬. 앞에서부터 최솟값을 찾아 swap 시킨다. -def sort_arr(arr): - for i in range(N-1): - min_value = float('inf') - min_idx = 0 - for j in range(i,N): - if arr[j] < min_value: - min_value = arr[j] - min_idx = j - arr[i], arr[min_idx] = arr[min_idx], arr[i] - return arr - - -for test in range(1, int(input())+1): - N = int(input()) - init_arr = list(map(int, input().split())) - sorted_arr = sort_arr(init_arr) - print(f'#{test}', end=' ') - print(*sorted_arr) - - -import sys -sys.stdin = open('input.txt') - - -# 버블정렬. 끝부터 범위를 하나씩 줄여가며 앞뒤로 스왑시킨다. 스왑이 일어나지 않으면 정렬 완료. -def sort_arr(N, arr): - for i in range(N-2, -1, -1): - swap = 0 - for j in range(0, i+1): - if arr[j] > arr[j+1]: - arr[j], arr[j+1] = arr[j+1], arr[j] - swap = 1 - if not swap: - return arr - return arr - - -for test in range(1, int(input())+1): - N = int(input()) - init_arr = list(map(int, input().split())) - sorted_arr = sort_arr(N, init_arr) - print(f'#{test}', end=' ') - print(*sorted_arr) - - -import sys -sys.stdin = open('input.txt') - - -# 삽입 정렬. 순서대로 하나씩 빼서 내 앞에 있는 애들이랑 비교. 나보다 작은애 만나면 그 뒤에 삽입. -def sort_arr(N, arr): - for i in range(1, N): - tmp = i - for j in range(i-1, -1, -1): - if arr[tmp] < arr[j]: - arr[tmp], arr[j] = arr[j], arr[tmp] - tmp -= 1 - else: - break - return arr - - -for test in range(1, int(input())+1): - N = int(input()) - init_arr = list(map(int, input().split())) - sorted_arr = sort_arr(N, init_arr) - print(f'#{test}', end=' ') - print(*sorted_arr) - - -import sys -sys.stdin = open('input.txt') -sys.setrecursionlimit(10**6) - - -# 퀵 정렬 : 정렬기준인 pivot 을 통해 좌우 범위로 나눠 정렬하고 합치는 정렬. -def sort_arr(arr): - length = len(arr) - if length <= 1: - return arr - middle = length//2 - pivot = arr[middle] # pivot 은 정렬되지 않는 배열의 중앙값이며 대소비교의 기준입니다. - rest = arr[:middle] + arr[middle+1:] # pivot 과 비교할 모집단입니다. - left_arr = [i for i in rest if i <= pivot] # pivot 보다 작은 수들의 집합입니다. - right_arr = [i for i in rest if i > pivot] # pivot 보다 큰 수들의 집합입니다. - return sort_arr(left_arr) + [pivot] + sort_arr(right_arr) # 정렬이 끝났으면 다시 합칩니다. - - -for test in range(1, int(input())+1): - N = int(input()) - init_arr = list(map(int, input().split())) - sorted_arr = sort_arr(init_arr) - print(f'#{test}', end=' ') - print(*sorted_arr) - - -import sys -sys.stdin = open('input.txt') - - -# 앞에서 부터 비교해 작은 숫자부터 새로운 배열에 병합합니다. -# 연산이 끝나면 정렬된 배열 merged 가 반환됩니다. -def merge(left, right): - merged = [] - while left or right: - if not left: - merged += right - return merged - elif not right: - merged += left - return merged - - if left[0] < right[0]: - merged += [left[0]] - left = left[1:] - else: - merged += [right[0]] - right = right[1:] - return merged - - -# 병합 정렬 : 분할 정복을 이용한 정렬. 퀵정렬이 pivot을 기준으로 한다면 얘는 그냥 무지성 반갈. -# 반갈을 1개씩 남을때까지 한 다음 다시 병합하는데 맨앞부터 비교해서 작으면 앞에 놓는 식. -def sort_arr(arr): - length = len(arr) - if length <= 1: - return arr - middle = length//2 - left_arr = sort_arr(arr[:middle]) - right_arr = sort_arr(arr[middle:]) - return merge(left_arr, right_arr) - - -for test in range(1, int(input())+1): - N = int(input()) - init_arr = list(map(int, input().split())) - sorted_arr = sort_arr(init_arr) - print(f'#{test}', end=' ') - print(*sorted_arr) - - diff --git "a/SWEA/SWEA1974\354\212\244\353\217\204\354\277\240\352\262\200\354\246\235.py" "b/SWEA/SWEA1974\354\212\244\353\217\204\354\277\240\352\262\200\354\246\235.py" deleted file mode 100644 index 3cfa74a..0000000 --- "a/SWEA/SWEA1974\354\212\244\353\217\204\354\277\240\352\262\200\354\246\235.py" +++ /dev/null @@ -1,46 +0,0 @@ -import sys -input = sys.stdin.readline - -def check(x,y,matrix): - col_check_box = {i:False for i in range(1,10)} - row_check_box = {i:False for i in range(1,10)} - box_check = {i:False for i in range(1,10)} - # 행 검사 - for num in matrix[x]: - if not col_check_box[num]: - col_check_box[num] = True - else: - return False - # 열 검사 - for j in range(9): - num = matrix[j][y] - if not row_check_box[num]: - row_check_box[num] = True - else: - return False - # 박스 검사 - for i in range(3): - for j in range(3): - num = matrix[(x+i)%3][(y+j)%3] - if not box_check[num]: - box_check[num] = True - else: - return False - return True - -def check_sudoku(s): - # 0,0에서 1,3씩 늘려가며 8이상 넘어가면 8로 나눈 나머지로 바꿔줌 총 9번 검사. - i = 0 - for j in range(0,24,3): - if check(i,j%8,s): - i += 1 - else: - return 0 - else: - return 1 if check(8,8,s) else 0 - - - -for test in range(1,int(input())+1): - sudoku = [list(map(int,input().split())) for _ in range(9)] - print(f'#{test} {check_sudoku(sudoku)}') \ No newline at end of file diff --git "a/SWEA/SWEA1979\354\226\264\353\224\224\354\227\220\353\213\250\354\226\264\352\260\200.py" "b/SWEA/SWEA1979\354\226\264\353\224\224\354\227\220\353\213\250\354\226\264\352\260\200.py" deleted file mode 100644 index 362be18..0000000 --- "a/SWEA/SWEA1979\354\226\264\353\224\224\354\227\220\353\213\250\354\226\264\352\260\200.py" +++ /dev/null @@ -1,41 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -# 각 행에 몇칸짜리 자리가 있는지 count 해 cells 에 저장합니다. -def count_row(n, target, puzzle): - sum_seat = 0 - for row in range(n): - cnt = 0 - cells = [] - for column in range(n): - if puzzle[row][column]: - cnt += 1 - else: - if cnt: - cells.append(cnt) - cnt = 0 - cells.append(cnt) - sum_seat += cells.count(target) # 원하는 자리가 있다면 세줍니다. - return sum_seat - - -# 글자가 들어갈 자리를 찾을 함수입니다. -def find_seat(size, length): - n = size - l = length - answer = 0 - - puzzle = [list(map(int, input().split())) for _ in range(n)] - answer += count_row(n, l, puzzle) - - # 배열의 열과 행을 뒤집에 한번 더 실시합니다. - new_puzzle = [k for k in zip(*puzzle)] - answer += count_row(n, l, new_puzzle) - - return answer - - -for test in range(1, int(input())+1): - N, K = map(int, input().split()) - print(f'#{test} {find_seat(N, K)}') diff --git "a/SWEA/SWEA1979\354\226\264\353\224\224\354\227\220\353\213\250\354\226\264\352\260\200\353\223\244\354\226\264\352\260\210\354\210\230\354\236\210\354\235\204\352\271\214.py" "b/SWEA/SWEA1979\354\226\264\353\224\224\354\227\220\353\213\250\354\226\264\352\260\200\353\223\244\354\226\264\352\260\210\354\210\230\354\236\210\354\235\204\352\271\214.py" deleted file mode 100644 index b1e8ae8..0000000 --- "a/SWEA/SWEA1979\354\226\264\353\224\224\354\227\220\353\213\250\354\226\264\352\260\200\353\223\244\354\226\264\352\260\210\354\210\230\354\236\210\354\235\204\352\271\214.py" +++ /dev/null @@ -1,34 +0,0 @@ -def count_row(n, target, puzzle): - sum_seat = 0 - for row in range(n): - cnt = 0 - cells = [] - for column in range(n): - if puzzle[row][column]: - cnt += 1 - else: - if cnt: - cells.append(cnt) - cnt = 0 - cells.append(cnt) - sum_seat += cells.count(target) - return sum_seat - - -def find_seat(size, length): - n = size - l = length - answer = 0 - - puzzle = [list(map(int, input().split())) for _ in range(n)] - answer += count_row(n, l, puzzle) - - new_puzzle = [k for k in zip(*puzzle)] - answer += count_row(n, l, new_puzzle) - - return answer - - -for test in range(1, int(input())+1): - N, K = map(int, input().split()) - print(f'#{test} {find_seat(N, K)}') diff --git "a/SWEA/SWEA2001\355\214\214\353\246\254\355\207\264\354\271\230.py" "b/SWEA/SWEA2001\355\214\214\353\246\254\355\207\264\354\271\230.py" deleted file mode 100644 index 2a55f0b..0000000 --- "a/SWEA/SWEA2001\355\214\214\353\246\254\355\207\264\354\271\230.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -# 파리채로 쳐 죽입니다. -def count_kill_flies(x,y, fly_killer_size, matrix): - kill = 0 - for i in range(x, x+fly_killer_size): - kill += sum(matrix[i][y:y+fly_killer_size]) - return kill - - -def kill_flies(matrix_size, fly_killer_size): - matrix = [list(map(int, input().split())) for _ in range(matrix_size)] - - # 파리채로 칠 범위를 지정합니다.(왼쪽 위 idx) - kill_sum = [] - for i in range(matrix_size-fly_killer_size+1): - for j in range(matrix_size-fly_killer_size+1): - init_x, init_y = i, j - kill_sum.append(count_kill_flies(init_x, init_y, fly_killer_size, matrix)) - return max(kill_sum) - - -for test in range(1, int(input())+1): - N, M = map(int, input().split()) - print(f'#{test} {kill_flies(N, M)}') diff --git "a/SWEA/SWEA2005\355\214\214\354\212\244\354\271\274\354\235\230\354\202\274\352\260\201\355\230\225.py" "b/SWEA/SWEA2005\355\214\214\354\212\244\354\271\274\354\235\230\354\202\274\352\260\201\355\230\225.py" deleted file mode 100644 index e14a23b..0000000 --- "a/SWEA/SWEA2005\355\214\214\354\212\244\354\271\274\354\235\230\354\202\274\352\260\201\355\230\225.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -test = int(input()) -for test in range(1, test+1): - n = int(input()) - pascals = [[] for _ in range(n)] #* *삼각형을 그릴 틀* - pascals[0].append(1) #* *첫열은 그냥 삽입* - for i in range(1, n): #* *2열부터 그릴 것임.* - stack = pascals[i-1][:] #* *1열(i-1열을 복사)* - pascals[i].append(1) #* *첫인자 삽입* - for j in range(1, i): #* *다음인자부터는 i-1열의 인자를 하나하나 pop 해주며 다음에 나올 인자와의 합을 i열에 삽입해줌.* - pascals[i].append(stack.pop()+stack[-1]) - pascals[i].append(1) #* *마지막 인자 삽입.* - #* *어차피 좌우대칭이므로 기존 파스칼 삼각형의 규칙인* #* *i-1열의 0,1번째 인자의 합이 i열 1인자가 될 필요 없음 - print(f'#{test}') #* *stack 을 이용 i-1열의 i,i-1번째 인자가 i열의 1번 인자가 되는 방식.* - for pas in pascals: - print(*pas) diff --git "a/SWEA/SWEA4408\354\236\220\352\270\260\353\260\251\354\234\274\353\241\234\353\217\214\354\225\204\352\260\200\352\270\260.py" "b/SWEA/SWEA4408\354\236\220\352\270\260\353\260\251\354\234\274\353\241\234\353\217\214\354\225\204\352\260\200\352\270\260.py" deleted file mode 100644 index 5d92b12..0000000 --- "a/SWEA/SWEA4408\354\236\220\352\270\260\353\260\251\354\234\274\353\241\234\353\217\214\354\225\204\352\260\200\352\270\260.py" +++ /dev/null @@ -1,30 +0,0 @@ -from heapq import heappop,heappush -from math import ceil - -def find_time_units(n): - - students = [] - for _ in range(n): - start, end = map(int,input().split()) - if start > end: - start, end = end, start - start = ceil(start/2) - end = ceil(end/2) - students.append([start,end]) - students.sort() - - time_units = [] - heappush(time_units,students[0][1]) - - for i in range(1,n): - if time_units[0] >= students[i][0]: - heappush(time_units,students[i][1]) - else: - heappop(time_units) - heappush(time_units,students[i][1]) - - return len(time_units) - -for test in range(1,int(input())+1): - N = int(input()) - print(f'#{test} {find_time_units(N)}') \ No newline at end of file diff --git "a/SWEA/SWEA4836\354\203\211\354\271\240\355\225\230\352\270\260.py" "b/SWEA/SWEA4836\354\203\211\354\271\240\355\225\230\352\270\260.py" deleted file mode 100644 index 9297179..0000000 --- "a/SWEA/SWEA4836\354\203\211\354\271\240\355\225\230\352\270\260.py" +++ /dev/null @@ -1,26 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def color_areas(color_cnt): - # 색을 칠할 칠판입니다. - matrix = [[[] for _ in range(10)] for _ in range(10)] - for _ in range(color_cnt): - r1, c1, r2, c2, color = map(int, input().split()) - # 내 색깔이 칸에 안칠해져있다면 칠합니다. - for i in range(r1, r2+1): - for j in range(c1, c2+1): - if not color in matrix[i][j]: - matrix[i][j].append(color) - # 원하는 색이 칠해져있다면 세줍니다. - answer = 0 - for i in range(10): - for j in range(10): - if len(matrix[i][j]) == 2: - answer += 1 - return answer - - -for test in range(1, int(input())+1): - N = int(input()) - print(f'#{test} {color_areas(N)}') diff --git "a/SWEA/SWEA4839\354\235\264\354\247\204\355\203\220\354\203\211.py" "b/SWEA/SWEA4839\354\235\264\354\247\204\355\203\220\354\203\211.py" deleted file mode 100644 index e173898..0000000 --- "a/SWEA/SWEA4839\354\235\264\354\247\204\355\203\220\354\203\211.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -# 좌우로 부터 조여 몇번 조여야 원하는 n값에 도달하는지 체크합니다. -def binary_search(P, n): - left = 1 - right = P - cnt = 0 - while left <= right: - mid = (left + right)//2 - cnt += 1 - if mid < n: - left = mid - elif mid > n: - right = mid - else: - break - return cnt - - -def find_winner(): - P, A, B = map(int, input().split()) - if P == 1 or A == B: - return 0 - a_cnt = binary_search(P, A) - b_cnt = binary_search(P, B) - # 체크한 횟수를 비교해 결과를 반환합니다. - if a_cnt > b_cnt: - return 'B' - elif b_cnt > a_cnt: - return 'A' - else: - return 0 - - -for test in range(1, int(input())+1): - print(f'#{test} {find_winner()}') - - diff --git "a/SWEA/SWEA4843\355\212\271\353\263\204\355\225\234 \354\240\225\353\240\254.py" "b/SWEA/SWEA4843\355\212\271\353\263\204\355\225\234 \354\240\225\353\240\254.py" deleted file mode 100644 index fdc8d91..0000000 --- "a/SWEA/SWEA4843\355\212\271\353\263\204\355\225\234 \354\240\225\353\240\254.py" +++ /dev/null @@ -1,77 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -def special_sort(length, arr): - arr.sort() - max_idx = length-1 - min_idx = 0 - special_arr = [] - # 정렬한 배열의 양끝에서부터 하나씩 특별한 배열로 삽입합니다. - # 양끝이 만나면 종료합니다. - while min_idx <= max_idx: - special_arr.append(arr[max_idx]) - special_arr.append(arr[min_idx]) - max_idx -= 1 - min_idx += 1 - return special_arr[:10] - - -for test in range(1, int(input())+1): - N = int(input()) - arr = list(map(int, input().split())) - answer = special_sort(N, arr) - print(f'#{test}', end=' ') - print(*answer) - - -import sys -from collections import deque -sys.stdin = open('input.txt') - - -def special_sort(arr): - arr.sort() - queue = deque([*arr]) - special_arr = [] - while queue: - special_arr.append(queue.pop()) - special_arr.append(queue.popleft()) - return special_arr[:10] - - -for test in range(1, int(input())+1): - N = int(input()) - arr = list(map(int, input().split())) - answer = special_sort(arr) - print(f'#{test}', end=' ') - print(*answer) - -import sys -from heapq import heappop,heapify -sys.stdin = open('input.txt') - - -def special_sort(arr): - length = len(arr) - minus_arr = list(map(lambda x: -x, arr)) - heapify(arr) - heapify(minus_arr) - special_arr = [] - cnt = 0 - while cnt != length: - special_arr.append(-heappop(minus_arr)) - cnt += 1 - if cnt == length: - break - special_arr.append(heappop(arr)) - cnt += 1 - return special_arr[:10] - - -for test in range(1, int(input())+1): - N = int(input()) - arr = list(map(int, input().split())) - answer = special_sort(arr) - print(f'#{test}', end=' ') - print(*answer) diff --git "a/SWEA/SWEA4865\352\270\200\354\236\220\354\210\230.py" "b/SWEA/SWEA4865\352\270\200\354\236\220\354\210\230.py" deleted file mode 100644 index 72bfdc8..0000000 --- "a/SWEA/SWEA4865\352\270\200\354\236\220\354\210\230.py" +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -def count_chrs(s1, s2): - char_set = defaultdict(int) - for chr in s2: - char_set[chr] += 1 - max_cnt = 0 - for char in s1: - max_cnt = max(max_cnt,char_set[char]) - return max_cnt - - -for test in range(1,int(input())+1): - str1 = input().rstrip() - str2 = input().rstrip() - print(f'#{test} {count_chrs(str1, str2)}') diff --git "a/SWEA/SWEA4866\352\264\204\355\230\270\352\262\200\354\202\254.py" "b/SWEA/SWEA4866\352\264\204\355\230\270\352\262\200\354\202\254.py" deleted file mode 100644 index d206766..0000000 --- "a/SWEA/SWEA4866\352\264\204\355\230\270\352\262\200\354\202\254.py" +++ /dev/null @@ -1,40 +0,0 @@ - -def bracket_inspection(s): - dic = {')':0, '}':0,']':0, '(':0, '{':0,'[':0} - stack1 = [] - stack2 = [] - for chr in s: - if chr in dic: - dic[chr] += 1 - stack1.append(chr) - - if dic[')'] != dic['('] or dic['}'] != dic['{'] or dic[']'] != dic['[']: - return 0 - - while stack1: - check = stack1.pop() - if check == ')' or check == '}' or check==']': - stack2.append(check) - else: - if check =='(': - if stack2[-1]==')': - stack2.pop() - else: - return 0 - elif check=='{': - if stack2[-1]=='}': - stack2.pop() - else: - return 0 - elif check=='[': - if stack2[-1]==']': - stack2.pop() - else: - return 0 - - return 1 - - -for test in range(1,int(input())+1): - s = list(input()) - print(f'#{test} {bracket_inspection(s)}') diff --git "a/SWEA/SWEA4871\352\267\270\353\236\230\355\224\204\352\262\275\353\241\234.py" "b/SWEA/SWEA4871\352\267\270\353\236\230\355\224\204\352\262\275\353\241\234.py" deleted file mode 100644 index b48769b..0000000 --- "a/SWEA/SWEA4871\352\267\270\353\236\230\355\224\204\352\262\275\353\241\234.py" +++ /dev/null @@ -1,26 +0,0 @@ - -def find_path(s,g): - global answer - if s==g: - answer = 1 - return - for next_node in graph[s]: - if not visited[next_node]: - visited[next_node] = True - find_path(next_node,g) - - - -for test in range(1,int(input())+1): - V, E = map(int,input().split()) - graph = {i:[] for i in range(1,V+1)} - answer = 0 - visited = {i:False for i in range(1,V+1)} - for _ in range(E): - a, b = map(int,input().split()) - graph[a] += [b] - s,g = map(int,input().split()) - visited[s] = True - find_path(s,g) - - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA4873\353\260\230\353\263\265\353\254\270\354\236\220\354\247\200\354\232\260\352\270\260.py" "b/SWEA/SWEA4873\353\260\230\353\263\265\353\254\270\354\236\220\354\247\200\354\232\260\352\270\260.py" deleted file mode 100644 index 1716f5a..0000000 --- "a/SWEA/SWEA4873\353\260\230\353\263\265\353\254\270\354\236\220\354\247\200\354\232\260\352\270\260.py" +++ /dev/null @@ -1,21 +0,0 @@ - -def repeat_str(s): - init = len(s) - stack = [] - cnt = 0 - while s: - pre = s.pop() - if stack: - if pre == stack[-1]: - stack.pop() - cnt += 1 - else: - stack.append(pre) - else: - stack.append(pre) - return init - 2*cnt - - -for test in range(1,int(input())+1): - s = list(input()) - print(f'#{test} {repeat_str(s)}') \ No newline at end of file diff --git a/SWEA/SWEA4874Forth.py b/SWEA/SWEA4874Forth.py deleted file mode 100644 index c85dd2c..0000000 --- a/SWEA/SWEA4874Forth.py +++ /dev/null @@ -1,34 +0,0 @@ -for test in range(1, int(input())+1): - equation = input().split() - flag = 0 - stack = [] - try: - for el in equation: - # 숫자면 stack에 밀어넣기. - if el.isdigit(): - stack.append(int(el)) - # 연산자면 숫자 두개꺼내서 연산. - elif el == '+': - stack.append(stack.pop() + stack.pop()) - elif el == '-': - tmp = stack.pop() - stack.append(stack.pop() - tmp) - elif el == '*': - tmp = stack.pop() - stack.append(stack.pop() * tmp) - elif el == '/': - tmp = stack.pop() - stack.append(stack.pop() // tmp) - else: - answer = stack.pop() - # 점 나왔는데 stack에 숫자 남아있으면 실패. - if len(stack) != 0: - flag = 1 - break - # 연산자 나왔는데 stack에 숫자 두개가 없을 떄. - except: - flag = 1 - if flag: - print(f'#{test} error') - else: - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA4875\353\257\270\353\241\234.py" "b/SWEA/SWEA4875\353\257\270\353\241\234.py" deleted file mode 100644 index a535b45..0000000 --- "a/SWEA/SWEA4875\353\257\270\353\241\234.py" +++ /dev/null @@ -1,29 +0,0 @@ - - -def DFS(x,y): - for i in range(4): - nx = x+dx[i] - ny = y+dy[i] - if 0<=nx min_sum: - return - for i in range(N): - if not col_check[i]: - col_check[i] = True - DFS(row+1,sum_nums+matrix[row][i]) - col_check[i] = False - - -for test in range(1,int(input())+1): - N = int(input()) - matrix = [list(map(int,input().split())) for _ in range(N)] - min_sum = float('inf') - col_check = [False] * N - DFS(0,0) - print(f'#{test} {min_sum}') \ No newline at end of file diff --git "a/SWEA/SWEA5015\353\257\270\353\241\234\354\235\230\352\261\260\353\246\254.py" "b/SWEA/SWEA5015\353\257\270\353\241\234\354\235\230\352\261\260\353\246\254.py" deleted file mode 100644 index 6802018..0000000 --- "a/SWEA/SWEA5015\353\257\270\353\241\234\354\235\230\352\261\260\353\246\254.py" +++ /dev/null @@ -1,35 +0,0 @@ -from collections import deque - -def BFS(x,y): - visited = [[-1]*N for _ in range(N)] - visited[x][y] = 0 - queue = deque() - queue.append([x,y]) - while queue: - x, y = queue.popleft() - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if 0<=nx1: - oven.rotate(-1) - oven[-1][0] //=2 - if not oven[-1][0]: - oven.pop() - answer = oven[-1][1] - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA5102\353\205\270\353\223\234\354\235\230\352\261\260\353\246\254.py" "b/SWEA/SWEA5102\353\205\270\353\223\234\354\235\230\352\261\260\353\246\254.py" deleted file mode 100644 index 87c6abe..0000000 --- "a/SWEA/SWEA5102\353\205\270\353\223\234\354\235\230\352\261\260\353\246\254.py" +++ /dev/null @@ -1,28 +0,0 @@ - -from collections import deque - -def BFS(start,goal): - queue = deque() - queue.append([start,0]) - visited = {i: False for i in range(1,V+1)} - visited[start] = True - while queue: - cur_node, cur_dist = queue.popleft() - if cur_node==goal: - return cur_dist - for next_node in graph[cur_node]: - if not visited[next_node]: - visited[next_node] = True - queue.append([next_node,cur_dist+1]) - return 0 - -for test in range(1,int(input())+1): - V, E = map(int, input().split()) - graph = {i: [] for i in range(1,V+1)} - for _ in range(E): - a, b = map(int, input().split()) - graph[a] += [b] - graph[b] += [a] - S, G = map(int, input().split()) - answer = BFS(S, G) - print(f'#{test} {answer}') \ No newline at end of file diff --git "a/SWEA/SWEA5108\354\210\253\354\236\220 \354\266\224\352\260\200.py" "b/SWEA/SWEA5108\354\210\253\354\236\220 \354\266\224\352\260\200.py" deleted file mode 100644 index 8eb5db7..0000000 --- "a/SWEA/SWEA5108\354\210\253\354\236\220 \354\266\224\352\260\200.py" +++ /dev/null @@ -1,8 +0,0 @@ - -for test in range(1,int(input())+1): - N, M, L = map(int, input().split()) - arr = list(map(int, input().split())) - for _ in range(M): - idx, num = map(int, input().split()) - arr.insert(idx,num) - print(f'#{test} {arr[L]}') \ No newline at end of file diff --git "a/SWEA/SWEA5110\354\210\230\354\227\264 \355\225\251\354\271\230\352\270\260.py" "b/SWEA/SWEA5110\354\210\230\354\227\264 \355\225\251\354\271\230\352\270\260.py" deleted file mode 100644 index 1b49981..0000000 --- "a/SWEA/SWEA5110\354\210\230\354\227\264 \355\225\251\354\271\230\352\270\260.py" +++ /dev/null @@ -1,96 +0,0 @@ -# class Node: -# # 초기화 메소드 -# def __init__(self, data): -# self.data = data -# self.link = None - -# class LinkedList: -# # 초기화 메소드 -# def __init__(self): -# new_node = Node('head') -# self.head = new_node -# self.tail = new_node -# self.before = None -# self.current = None -# self.num_of_data = 0 - -# def append(self, data): -# new_node = Node(data) # 새 노드 생성 -# self.tail.link = new_node # 연결 -# self.tail = new_node # tail 갱신 -# self.num_of_data += 1 - -# def first(self): -# if self.num_of_data == 0: # 빈 리스트이면 None 리턴 -# return None -# self.before = self.head -# self.current = self.head.link -# return self.current.data - -# def next(self): -# self.before = self.current -# self.current = self.current.link -# if self.current == None: -# return None -# return self.current.data - -# def insertlist(self, new_list): -# insert_num = new_list.first() -# num = self.first() -# # 수열 2의 첫 숫자 보다 큰 수자를 수열 1에서 찾아 그 앞에 수열 2를 끼워 넣는다. -# for _ in range(self.num_of_data): -# if num > insert_num: -# self.before.link = new_list.head.link -# new_list.tail.link = self.current -# self.num_of_data += new_list.num_of_data -# break -# num = self.next() -# else: # 큰 숫자가 없는 경우 맨 뒤에 붙인다. -# self.tail.link = new_list.head.link -# self.num_of_data += new_list.num_of_data - -# # 빈 리스트에 링크드리스트data 담아서 마지막 10요소 출력 -# def my_result(self): -# lst = [] -# num = self.first() -# for i in range(self.num_of_data): -# lst.append(num) -# num = self.next() -# return ' '.join(map(str, lst[-1:-11:-1])) - -# # main 함수 -# T = int(input()) -# for test_case in range(1, T + 1): -# N, M = map(int, input().split()) - -# # 빈 LinkedList 생성 -# Seq1 = LinkedList() - -# # LinkedList 입력받기 -# for i in map(int, input().split()): -# Seq1.append(i) - -# for _ in range(M - 1): -# # 빈 LinkedList 생성 -# Seq2 = LinkedList() -# # LinkedList 입력받기 -# for j in map(int, input().split()): -# Seq2.append(j) -# # Seq1에 Seq2 삽입 -# Seq1.insertlist(Seq2) - -# print('#{} {}'.format(test_case, Seq1.my_result())) - -for test in range(1,int(input())+1): - N, M = map(int, input().split()) - arr = [float('inf')] - cnt = 0 - for _ in range(M): - a = list(map(int, input().split())) - for i in range(N*cnt+1): - if a[0] < arr[i]: - arr[i:i] = a - break - cnt += 1 - print(f'#{test}',end=' ') - print(*arr[-11:-1][::-1]) \ No newline at end of file diff --git a/SWEA/SWEA5174sub_tree.py b/SWEA/SWEA5174sub_tree.py deleted file mode 100644 index 28d253c..0000000 --- a/SWEA/SWEA5174sub_tree.py +++ /dev/null @@ -1,15 +0,0 @@ -for test in range(1,int(input())+1): - E, N = map(int, input().split()) - graph = {i:[] for i in range(1,E+2)} - edge = list(map(int, input().split())) - for i in range(0,2*E,2): - graph[edge[i]] += [edge[i+1]] - cnt = 1 - queue = [] - queue.append(N) - while queue: - cur_node = queue.pop() - for next_node in graph[cur_node]: - queue.append(next_node) - cnt += 1 - print(f'#{test} {cnt}') diff --git "a/SWEA/SWEA5176\354\235\264\354\247\204\355\203\220\354\203\211.py" "b/SWEA/SWEA5176\354\235\264\354\247\204\355\203\220\354\203\211.py" deleted file mode 100644 index bb02ce7..0000000 --- "a/SWEA/SWEA5176\354\235\264\354\247\204\355\203\220\354\203\211.py" +++ /dev/null @@ -1,16 +0,0 @@ - -def inorder_tree(node,value): - if node > N: - return value - else: - value = inorder_tree(node*2,value) - value += 1 - tree[node] = value - value = inorder_tree(node*2 + 1,value) - return value - -for test in range(1, int(input())+1): - N = int(input()) - tree = [0] *(N+1) - inorder_tree(1,0) - print(f'#{test} {tree[1]} {tree[N//2]}') \ No newline at end of file diff --git "a/SWEA/SWEA5177\354\235\264\354\247\204\355\236\231.py" "b/SWEA/SWEA5177\354\235\264\354\247\204\355\236\231.py" deleted file mode 100644 index 3a37c2c..0000000 --- "a/SWEA/SWEA5177\354\235\264\354\247\204\355\236\231.py" +++ /dev/null @@ -1,25 +0,0 @@ -def heap_sort(node): - mom_node = node//2 - if mom_node < 0: - return - else: - if tree[mom_node] > tree[node]: - tree[node], tree[mom_node] = tree[mom_node], tree[node] - heap_sort(mom_node) - - - -for test in range(1,int(input())+1): - N = int(input()) - tree = [0] - node_num = 1 - for num in map(int, input().split()): - tree.append(num) - heap_sort(node_num) - node_num += 1 - sum_value = 0 - while N: - N //= 2 - sum_value += tree[N] - - print(f'#{test} {sum_value}') \ No newline at end of file diff --git "a/SWEA/SWEA5178\353\205\270\353\223\234\354\235\230\355\225\251.py" "b/SWEA/SWEA5178\353\205\270\353\223\234\354\235\230\355\225\251.py" deleted file mode 100644 index 416cd59..0000000 --- "a/SWEA/SWEA5178\353\205\270\353\223\234\354\235\230\355\225\251.py" +++ /dev/null @@ -1,21 +0,0 @@ - -def prefix_tree(node): - if N-M < node <= N: - return tree[node] - elif node > N: - return 0 - else: - left = prefix_tree(node*2) - right = prefix_tree(node*2 + 1) - tree[node] = left + right - return tree[node] - -for test in range(1, int(input())+1): - N, M, L = map(int, input().split()) - tree = [0] *(N+1) - for _ in range(M): - node_num, value = map(int, input().split()) - tree[node_num] = value - prefix_tree(1) - print(f'#{test} {tree[L]}') - diff --git "a/SWEA/SWEA5185_\354\235\264\354\247\204\354\210\230.py" "b/SWEA/SWEA5185_\354\235\264\354\247\204\354\210\230.py" deleted file mode 100644 index 7a663b5..0000000 --- "a/SWEA/SWEA5185_\354\235\264\354\247\204\354\210\230.py" +++ /dev/null @@ -1,7 +0,0 @@ - -for test in range(1,int(input())+1): - N, s = input().split() - ans = '' - for i in range(int(N)): - ans += bin(int(s[i],16))[2:].zfill(4) - print(f"#{test} {ans}") diff --git "a/SWEA/SWEA5186\354\235\264\354\247\204\354\210\2302.py" "b/SWEA/SWEA5186\354\235\264\354\247\204\354\210\2302.py" deleted file mode 100644 index 088b25e..0000000 --- "a/SWEA/SWEA5186\354\235\264\354\247\204\354\210\2302.py" +++ /dev/null @@ -1,18 +0,0 @@ - -def binary(n,depth): - if depth>13: - return '2' - if not n: - return '' - if n >= 2**(-depth): - n -= 2**(-depth) - return '1' + binary(n,depth+1) - return '0' + binary(n,depth+1) - - -for test in range(1,int(input())+1): - N = float(input()) - ans = binary(N,1) - if ans[-1]=='2': - ans = 'overflow' - print(f'#{test} {ans}') \ No newline at end of file diff --git "a/SWEA/SWEA5432\354\207\240\353\247\211\353\214\200\354\236\220\353\245\264\352\270\260.py" "b/SWEA/SWEA5432\354\207\240\353\247\211\353\214\200\354\236\220\353\245\264\352\270\260.py" deleted file mode 100644 index 13eea71..0000000 --- "a/SWEA/SWEA5432\354\207\240\353\247\211\353\214\200\354\236\220\353\245\264\352\270\260.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -for test in range(1,int(input())+1): - arr = list(input()) - board = 0 - answer = 0 - for i in range(len(arr)): - if arr[i] == '(': - if arr[i+1] == ')': - answer += board - else: - board += 1 - - if arr[i] == ')': - if arr[i-1] == ')': - board -= 1 - answer += 1 - print(f'#{test} {answer}') diff --git "a/SWEA/SWEA6485\354\202\274\354\204\261\354\213\234\354\235\230\353\262\204\354\212\244\353\205\270\354\204\240.py" "b/SWEA/SWEA6485\354\202\274\354\204\261\354\213\234\354\235\230\353\262\204\354\212\244\353\205\270\354\204\240.py" deleted file mode 100644 index 77ddd94..0000000 --- "a/SWEA/SWEA6485\354\202\274\354\204\261\354\213\234\354\235\230\353\262\204\354\212\244\353\205\270\354\204\240.py" +++ /dev/null @@ -1,18 +0,0 @@ -def count_bus(n): - bus_stops = [0 for _ in range(5000)] - for _ in range(n): - start, end = map(int,input().split()) - for i in range(start-1,end): - bus_stops[i] += 1 - P = int(input()) - qa_set = [] - for i in range(P): - qa_set.append(bus_stops[int(input())-1]) - return qa_set - - -for test in range(1, int(input())+1): - N = int(input()) - answer = count_bus(N) - print(f'#{test}', end=' ') - print(*answer) \ No newline at end of file diff --git "a/SWEA/SWEA_4861\355\232\214\353\254\270.py" "b/SWEA/SWEA_4861\355\232\214\353\254\270.py" deleted file mode 100644 index ed602b3..0000000 --- "a/SWEA/SWEA_4861\355\232\214\353\254\270.py" +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline - -def find_palindrome(N,M,sentences): - for i in range(N): - for j in range(N-M+1): - if sentences[i][j] == sentences[i][j+M-1]: - left = j - right = j+M-1 - while sentences[i][left] == sentences[i][right] and left <= right: - left += 1 - right -= 1 - if left < right: - continue - else: - return sentences[i][j:j+M] - -for test in range(1,int(input())+1): - N, M = map(int,input().split()) - palindrome = list(list(input().rstrip()) for _ in range(N)) - result1 = find_palindrome(N,M,palindrome) - if result1: - print(f"#{test} {''.join(result1)}") - else: - reverse_palindrome = list(zip(*palindrome)) - result2 = find_palindrome(N,M,reverse_palindrome) - print(f"#{test} {''.join(result2)}") diff --git "a/SWEA/SWEA_4864\353\254\270\354\236\220\354\227\264\353\271\204\352\265\220.py" "b/SWEA/SWEA_4864\353\254\270\354\236\220\354\227\264\353\271\204\352\265\220.py" deleted file mode 100644 index 9e0b0ca..0000000 --- "a/SWEA/SWEA_4864\353\254\270\354\236\220\354\227\264\353\271\204\352\265\220.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - -def make_pattern(s): - counter = 0 - for idx in range(1, len(s)): - while counter > 0 and s[counter] != s[idx]: - counter = lose_funtion[counter-1] - if s[counter] == s[idx]: - counter += 1 - lose_funtion[idx] = counter - -def KMP_pattern_matching(p, s): - counter = 0 - p_size = len(p) - for idx in range(len(s)): - while counter > 0 and p[counter] != s[idx]: - counter = lose_funtion[counter-1] - if p[counter] == s[idx]: - if counter == p_size - 1: - return 1 - else: - counter += 1 - return 0 - -for test in range(1,int(input())+1): - str1 = input().rstrip() - str2 = input().rstrip() - - lose_funtion = [0 for _ in range(len(str1))] - make_pattern(str1) - print(f'#{test} {KMP_pattern_matching(str1, str2)}') diff --git a/SumOdds.py b/SumOdds.py deleted file mode 100644 index 7938ba3..0000000 --- a/SumOdds.py +++ /dev/null @@ -1,12 +0,0 @@ -T = int(input()) - -def sumOdd(): - number = list(map(int,input().split())) - S = 0 - for i in range(10): - if number[i] % 2 ==1: - S += number[i] - return S - -for j in range(T): - print("#{0} {1}".format(j+1,sumOdd())) \ No newline at end of file diff --git a/Test_im.py b/Test_im.py deleted file mode 100644 index e57fed1..0000000 --- a/Test_im.py +++ /dev/null @@ -1,4 +0,0 @@ -for test in range(1,int(input())+1): - X,Y = map(int,input().split()) - answer = ((X+Y)/6)*(X-(X+Y)/3)*(Y-(X+Y)/3) - print(answer) \ No newline at end of file diff --git "a/__pycache__/SWEA5185_\354\235\264\354\247\204\354\210\230.cpython-38.pyc" "b/__pycache__/SWEA5185_\354\235\264\354\247\204\354\210\230.cpython-38.pyc" deleted file mode 100644 index 1fb29bf..0000000 Binary files "a/__pycache__/SWEA5185_\354\235\264\354\247\204\354\210\230.cpython-38.pyc" and /dev/null differ diff --git a/__pycache__/lotto_numbering_module.cpython-38.pyc b/__pycache__/lotto_numbering_module.cpython-38.pyc new file mode 100644 index 0000000..18826a9 Binary files /dev/null and b/__pycache__/lotto_numbering_module.cpython-38.pyc differ diff --git a/average_condition.py b/average_condition.py deleted file mode 100644 index 4163485..0000000 --- a/average_condition.py +++ /dev/null @@ -1,118 +0,0 @@ -import random - - - -T = int(input()) - - -def move(): - global i,j - if direction == 'right': - j +=1 - if j==C: - j=0 - if direction == 'left': - j -=1 - if j==-1: - j=C-1 - if direction == 'up': - i -=1 - if i==-1: - i=R-1 - if direction == 'down': - i +=1 - if i==R: - i=0 - - - - -for test in range(1,T+1): - memory = 0 - R,C = map(int,input().split()) - game = [list(input()) for _ in range(R)] - check = [] - - i,j=0,0 - direction = 'right' - - - while 1: - - if (i,j,direction,memory) in check and game[i][j] != '?': - answer = 'NO' - break - else: - check.append((i,j,direction,memory)) - - if game[i][j] =='<': - direction ='left' - move() - - if game[i][j] =='>': - direction ='right' - move() - - if game[i][j] =='^': - direction = 'up' - move() - - if game[i][j] =='v': - direction = 'down' - move() - - - if game[i][j] =='_': - if memory == 0: - direction ='right' - else: - direction ='left' - move() - - if game[i][j] =='|': - if memory == 0: - direction = 'down' - else: - direction = 'up' - move() - - if game[i][j] =='?': - ran_num = random.randint(0,3) - if ran_num==0: - direction ='right' - elif ran_num==1: - direction ='left' - elif ran_num==2: - direction = 'down' - else: - direction = 'up' - move() - - if game[i][j].isdigit(): - memory = game[i][j] - move() - - if game[i][j] =='+': - memory += 1 - if memory == 16: - memory = 0 - move() - - if game[i][j] =='-': - memory = int(memory) - memory -= 1 - if memory == -1: - memory = 15 - move() - - if game[i][j] =='.': - move() - - if game[i][j] == '@': - answer = 'YES' - break - - - - - print(f"#{test} {answer}") diff --git a/baby-gin.py b/baby-gin.py deleted file mode 100644 index a443265..0000000 --- a/baby-gin.py +++ /dev/null @@ -1,26 +0,0 @@ -import sys - -try_baby_gin = int(input()) -cards = [] -for _ in range(try_baby_gin): - count_card = {i:0 for i in range(10)} - one_try = list(map(int, list(input()))) - for card in one_try: - count_card[card] += 1 - - for num in range(10): - if count_card[num]>=3: - count_card[num] -= 3*(count_card[num]//3) - if count_card[num] != 0: - if count_card[num]%3==count_card[num+1]%3==count_card[num+2]%3: - cnt= count_card[num]%3 - for i in range(3): - count_card[num+i] -= cnt - continue - else: - print("Not Baby-gin") - break - else: - print("Baby-gin") - - \ No newline at end of file diff --git a/back_rooms.py b/back_rooms.py deleted file mode 100644 index 3d95c43..0000000 --- a/back_rooms.py +++ /dev/null @@ -1,28 +0,0 @@ - -for test_case in range(1,int(input())+1): - N = int(input()) - student = [] - for _ in range(N): - st = list(map(int,input().split())) - st = sorted(st) - student.append(st) - student = sorted(student,key = lambda a : a[0]) - student = sorted(student,key = lambda a : a[1]) - check = [0]*N - cnt = 0 - while sum(check) != N: - last = 0 - for i in range(N): - if last %2 ==1: - if student[i][0] > last+1 and check[i] ==0: - last = student[i][1] - check[i] = 1 - else: - if student[i][0] > last and check[i] ==0: - last = student[i][1] - check[i] = 1 - cnt+=1 - print("#{} {}".format(test_case, cnt)) - - - diff --git a/back_rooms_answer.py b/back_rooms_answer.py deleted file mode 100644 index 8f02fec..0000000 --- a/back_rooms_answer.py +++ /dev/null @@ -1,13 +0,0 @@ -for t in range(1, int(input()) + 1 ): - check_list = [0] * 201 - for _ in range(int(input())): - a, b = map(int, input().split()) - if a > b : a, b = b, a - a = (a + 1) // 2 - b = (b + 1) // 2 - for i in range(a, b+1): - check_list[i] += 1 - print('#{} {}'.format(t, max(check_list))) - - - #겹치는 횟수의 max가 몇이냐... \ No newline at end of file diff --git a/backtracking_DFS.py b/backtracking_DFS.py index 8fcbafe..c51fa5e 100644 --- a/backtracking_DFS.py +++ b/backtracking_DFS.py @@ -1,34 +1,34 @@ -#부분집합 기본코드 -def printSet(n): - for i in range(n): - if A[i] == 1: - print(data[i], end = " ") - print() - -def powerset(k, n): # k는 A배열의 k인덱스의 포함 유무를 판별한다. - if n == k: - printSet(k) - else: - A[k] = 1 - powerset(k+1, n) # 배열 A에 체크하고 다음 인덱스로 넘어간다 - A[k] = 0 # 재귀로 되돌아와서 체크 했던걸 다시 원상복귀시킨다 - powerset(k+1, n) - -# data = 구하려는 리스트 -n = len(data) # 부분집합을 구하는 리스트의 수 -A = [0]* n # 포함 유무를 체크할 리스트 (0이 미포함, 1이 포함) - - -# 부분집합의 합 -def powerset(k, n, sum): - if sum > 10: # 부분집합의 합을 구하는 문제에서 구하고자하는 값인 10을 넘는다면 더이상 계산할 필요가 없으므로 return해버린다.(가지치기) - return - if n == k: - printSet(k, sum) - else: - A[k] = 1 - powerset(k+1, n, sum+data[k]) - A[k] = 0 - powerset(k+1, n, sum) - +#부분집합 기본코드 +def printSet(n): + for i in range(n): + if A[i] == 1: + print(data[i], end = " ") + print() + +def powerset(k, n): # k는 A배열의 k인덱스의 포함 유무를 판별한다. + if n == k: + printSet(k) + else: + A[k] = 1 + powerset(k+1, n) # 배열 A에 체크하고 다음 인덱스로 넘어간다 + A[k] = 0 # 재귀로 되돌아와서 체크 했던걸 다시 원상복귀시킨다 + powerset(k+1, n) + +# data = 구하려는 리스트 +n = len(data) # 부분집합을 구하는 리스트의 수 +A = [0]* n # 포함 유무를 체크할 리스트 (0이 미포함, 1이 포함) + + +# 부분집합의 합 +def powerset(k, n, sum): + if sum > 10: # 부분집합의 합을 구하는 문제에서 구하고자하는 값인 10을 넘는다면 더이상 계산할 필요가 없으므로 return해버린다.(가지치기) + return + if n == k: + printSet(k, sum) + else: + A[k] = 1 + powerset(k+1, n, sum+data[k]) + A[k] = 0 + powerset(k+1, n, sum) + # 백트래킹은 완전검색에서 가지치기를함 \ No newline at end of file diff --git a/baekjoon10162_greedy.py b/baekjoon10162_greedy.py deleted file mode 100644 index b7fbe23..0000000 --- a/baekjoon10162_greedy.py +++ /dev/null @@ -1,15 +0,0 @@ -import sys -###인풋 -N = int(input()) -strings = [] - -for _ in range(N): - string = list(sys.stdin.readline()) - del string[-1] - strings.append([len(string)]+string) - -strings = sorted(strings,reverse=True) -del strings[0] - - -print(strings) \ No newline at end of file diff --git a/baekjoon11047.py b/baekjoon11047.py deleted file mode 100644 index 3816458..0000000 --- a/baekjoon11047.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys - -N = int(input()) -roof = [] - -for _ in range(N): - roof.append(int(input())) - -roof = sorted(roof) -answer = [] - -for i in range(1,N+1): - if roof[-i]*i >= answer: - answer = roof[-i]*i - -print(answer) \ No newline at end of file diff --git a/baekjoon13305_oilshop.py b/baekjoon13305_oilshop.py deleted file mode 100644 index a42e42b..0000000 --- a/baekjoon13305_oilshop.py +++ /dev/null @@ -1,17 +0,0 @@ - - - - - -i=0 -while 1: - i +=1 - ans = 0 - L,P,V = map(int,input().split()) - - if L ==0 and P ==0 and V ==0: - break - - ans = (V//P)*L + (V%P)%L - - print(f"Case {i}: {ans}") diff --git a/baekjoon1339_greedy.py b/baekjoon1339_greedy.py deleted file mode 100644 index ea76d43..0000000 --- a/baekjoon1339_greedy.py +++ /dev/null @@ -1,23 +0,0 @@ - -N = int(input()) -alpha = [0]*26 -string = [list(map(lambda x: ord(x)-65,input())) for _ in range(N)] -ans = 0 -topN = 9 - -for i in range(N): - for m in string[i][::-1]: - for j in range(len(string[i])): - alpha[m] += (10**j) - -alpha.sort(reverse = True) - -for i in range(26): - if alpha[i] ==0: - continue - else: - ans += alpha[i]*topN - topN -= 1 - -print(ans) - diff --git a/baekjoon1339_greedy_dic_cal_hard.py b/baekjoon1339_greedy_dic_cal_hard.py deleted file mode 100644 index afe6a74..0000000 --- a/baekjoon1339_greedy_dic_cal_hard.py +++ /dev/null @@ -1,26 +0,0 @@ -# N개의도시 일직선 -#왼 -> 오 -# 도시간 거리 가중치.km단위 -# 기름통 무제한 km당 1리터 -#도시당 주유소 1개 리터당 가격 다름 -# 오른쪽 까지 가는 최소비용. -# -# -# -#정점N개 간선 N-1개 - -N = int(input()) -distance = list(map(int,input().split())) -pricePerKm = list(map(int,input().split())) -mincost = pricePerKm[0] -totalCost = 0 - - -for i in range(N-1): - if mincost>=pricePerKm[i]: - mincost = pricePerKm[i] - totalCost += mincost*distance[i] - else: - totalCost +=mincost*distance[i] - -print(totalCost) \ No newline at end of file diff --git a/baekjoon1541_incomplete.py b/baekjoon1541_incomplete.py deleted file mode 100644 index 98d30f1..0000000 --- a/baekjoon1541_incomplete.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys -###인풋 -T = int(sys.stdin.readline()) -for test in range(T): - N = int(sys.stdin.readline()) - sample = [] - - for _ in range(N): - W, M = map(int,sys.stdin.readline().split()) - sample.append([W,M]) - - -###비교 - cnt = 0 - sample = sorted(sample,key=lambda x : x[0]) - minN = sample[0][1] - for i in range(1,N): - if minN>sample[i][1]: - minN = sample[i][1] - cnt += 1 - - print(cnt) -###출력 \ No newline at end of file diff --git a/baekjoon1946.py b/baekjoon1946.py deleted file mode 100644 index 4ceece1..0000000 --- a/baekjoon1946.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -###인풋 -T = int(sys.stdin.readline()) -cntA = 0 -cntB = 0 -cntC = 0 - -if T%10 !=0: - print("-1") -else: - cntA += T//300 - T = T%300 - cntB += T//60 - T = T%60 - cntC += T//10 - print(f'{cntA} {cntB} {cntC}') \ No newline at end of file diff --git a/baekjoon2217.py b/baekjoon2217.py deleted file mode 100644 index ac1f058..0000000 --- a/baekjoon2217.py +++ /dev/null @@ -1,19 +0,0 @@ -fomula = list(input()) - -while fomula[0] == '0': - del fomula[0] - -fomula = ''.join(fomula) -fomula = fomula.split('-') - -i=0 - -while i != len(fomula): - fomula[i] = eval(fomula[i]) - i += 1 - -fomula = list(map(str,fomula)) -answer = eval('-'.join(fomula)) - - -print(answer) \ No newline at end of file diff --git a/baekjoon_1463_DP_practice.py b/baekjoon_1463_DP_practice.py deleted file mode 100644 index b9ac1a2..0000000 --- a/baekjoon_1463_DP_practice.py +++ /dev/null @@ -1,16 +0,0 @@ - - -n = int(input()) - -dp = [0 for _ in range(n+1)] - -for i in range(2, n+1): - dp[i] = dp[i-1] + 1 #i(n값)+1되면 cnt도 +1 - - if i%2 == 0 and dp[i] > dp[i//2] + 1 : #n이 2의 배수이면 그전 2의배수의 cnt+1 - dp[i] = dp[i//2]+1 - - if i%3 == 0 and dp[i] > dp[i//3] + 1 : #n이 3의 배수이면 그전 3의배수의 cnt+1 - dp[i] = dp[i//3] + 1 - -print(dp[n]) #n까지 반복하고 n의 cnt값 출력 \ No newline at end of file diff --git a/be_rich.py b/be_rich.py deleted file mode 100644 index e4264b3..0000000 --- a/be_rich.py +++ /dev/null @@ -1,27 +0,0 @@ -#N일 매매가 알고있음 -# 하루 1개만큼 구입 -# 판매는 얼마든지 가능#=>쌀때사서 비쌀때 판매. - -#T -#일 수N -#N개의 자연수(매매가) - -T = int(input()) - - - - -def MakeMoney(): - N = int(input()) - P = list(map(int,input().split())) - maxProfit = 0 - for i in range(N): - for j in range(i+1): - if max(P)==P[i] and j<=i and P[j] !=0: - maxProfit += P[i]-P[j] - P[j]=0 - return maxProfit - - -for testcase in range(T): - print("#{} {}".format(testcase+1,MakeMoney())) \ No newline at end of file diff --git a/beakjoon1003_DP.py b/beakjoon1003_DP.py deleted file mode 100644 index 88a1ee2..0000000 --- a/beakjoon1003_DP.py +++ /dev/null @@ -1,22 +0,0 @@ -import sys - -def fibonacii(n): - global cnt_0,cnt_1 - if n==0: - cnt_0 += 1 - return 0 - elif n==1: - cnt_1 += 1 - return 1 - else: - return fibonacii(n-1) + fibonacii(n-2) - - -T = int(sys.stdin.readline()) - -for test in range(1,T+1): - n = int(sys.stdin.readline()) - cnt_0 = 0 - cnt_1 = 0 - fibonacii(n) - print(f'{cnt_0} {cnt_1}') \ No newline at end of file diff --git a/beakjoon1003_DP_for.py b/beakjoon1003_DP_for.py deleted file mode 100644 index 174e428..0000000 --- a/beakjoon1003_DP_for.py +++ /dev/null @@ -1,42 +0,0 @@ -import sys - -#입력부 -n = int(sys.stdin.readline()) -scores =[] -sum_score=[] -check = [0]*n - -for _ in range(n): - score = int(sys.stdin.readline()) - scores.append(score) - - - -sum_score.append(scores[0]) -sum_score.append(scores[0]+scores[1]) -check[0] = 1 -check[1] = 1 - -for i in range(2,n): - if sum_score[i-2]scores[i-2] and (check[i-2]==1 and check[i-1] ==1): - sum_score.append(sum_score[i-1]-scores[i-2]+scores[i]) - check[i] = 1 - check[i-1]=2 - else: - sum_score.append(sum_score[i-2]+scores[i]) - check[i] = 2 - - -print(check) - -""" -case1: i-1이 i-2보다 커서 i-1에서 이동.(i-1), i-2가 동시에 1이동이면 안됨. -case2: i-2가 i-1보다 커서 i-2에서 이동.(조건 없음) -case3: i-1이랑 i-2가 동시에 1인데 i-1score보다 i-2스코어 가 더 큼.그럼 i-1배제보다 i-2배제가 더 좋음. --> - - -""" \ No newline at end of file diff --git a/beakjoon1003_DP_recursion.py b/beakjoon1003_DP_recursion.py deleted file mode 100644 index ed1a596..0000000 --- a/beakjoon1003_DP_recursion.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys - -T = int(sys.stdin.readline()) - -for test in range(1,T+1): - n = int(sys.stdin.readline()) - dp = [] - - dp.append([1,0]) - dp.append([0,1]) - - for i in range(2, n+1): - dp_x = dp[i-1][0]+dp[i-2][0] - dp_y = dp[i-1][1]+dp[i-2][1] - dp.append([dp_x,dp_y]) - print(f'{dp[n][0]} {dp[n][1]}') - - - diff --git a/beakjoon1005_ACM_craft.py b/beakjoon1005_ACM_craft.py deleted file mode 100644 index 2446b42..0000000 --- a/beakjoon1005_ACM_craft.py +++ /dev/null @@ -1,27 +0,0 @@ -import collections as col - - -T = int(input()) - -for test in range(T): - N,K= map(int,input().split()) - D = [0] + list(map(int,input().split())) - order = col.defaultdict(list) - dp = [0]*(N+1) - - for _ in range(K): - X,Y = map(int,input().split()) - order[Y].append(X) - - finish = int(input()) - for i in range(1,N+1): - if i not in order: - dp[i] = D[i] - for key in order: - s = [] - if order[key]: - for adj in order[key]: - s.append(dp[adj]) - dp[key] = max(s) +D[key] - - print(dp) \ No newline at end of file diff --git a/beakjoon1006_dp.py b/beakjoon1006_dp.py index f128a6d..76e9c29 100644 --- a/beakjoon1006_dp.py +++ b/beakjoon1006_dp.py @@ -1,16 +1,16 @@ -import sys, collections -T = int(sys.stdin.readline()) - -for test in range(T): - - N,M,K= map(int,sys.stdin.readline().split()) - - air = collections.defaultdict(list) - c = [0]*N - t = [0]*N - - for _ in range(K): - u,v,c,d = map(int,sys.stdin.readline().split()) - air[u].append(v) - +import sys, collections +T = int(sys.stdin.readline()) + +for test in range(T): + + N,M,K= map(int,sys.stdin.readline().split()) + + air = collections.defaultdict(list) + c = [0]*N + t = [0]*N + + for _ in range(K): + u,v,c,d = map(int,sys.stdin.readline().split()) + air[u].append(v) + print(air[1]) \ No newline at end of file diff --git a/beakjoon10844.py b/beakjoon10844.py deleted file mode 100644 index 952256a..0000000 --- a/beakjoon10844.py +++ /dev/null @@ -1,4 +0,0 @@ -import inspect,collections - -inspect.getsource(collections.defaultdict) - diff --git a/beakjoon1149.py b/beakjoon1149.py deleted file mode 100644 index cb59194..0000000 --- a/beakjoon1149.py +++ /dev/null @@ -1,17 +0,0 @@ -import sys - -N = int(sys.stdin.readline()) -c = [] - -for _ in range(N): - color = list(map(int,sys.stdin.readline().split())) - c.append(color) - - -# 각 색을 선택시마다 최소값을 누적시키면서 진행.(결국 i-1이랑만 안겹치면됨) -for i in range(1,N): - c[i][0] = min(c[i-1][1],c[i-1][2])+c[i][0] - c[i][1] = min(c[i-1][0],c[i-1][2])+c[i][1] - c[i][2] = min(c[i-1][0],c[i-1][1])+c[i][2] - -print(min(c[N-1][0],c[N-1][1],c[N-1][2])) \ No newline at end of file diff --git a/beakjoon1149__Failed_repeat_afterward.py b/beakjoon1149__Failed_repeat_afterward.py deleted file mode 100644 index d36f4ad..0000000 --- a/beakjoon1149__Failed_repeat_afterward.py +++ /dev/null @@ -1,25 +0,0 @@ -import sys - -N = int(sys.stdin.readline()) -num = [] - -for _ in range(N): - n = list(map(int,sys.stdin.readline().split())) - num.append(n) - - - -for i in range(1,N): - for j in range(len(num[i])): - if j==0: - num[i][j] = num[i-1][j]+num[i][j] - elif j==len(num[i])-1: - num[i][j] = num[i-1][len(num[j])-2]+num[i][j] - else: - num[i][j] = max(num[i-1][j],num[i-1][j-1])+num[i][j] - - - -print(max(num[N-1])) - -# \ No newline at end of file diff --git a/beakjoon11727.py b/beakjoon11727.py deleted file mode 100644 index 470ff69..0000000 --- a/beakjoon11727.py +++ /dev/null @@ -1,15 +0,0 @@ - - - - -n = int(input()) -dp = [] - -dp.append(0) -dp.append(1) -dp.append(1) -if n>2: - for i in range(3,n+1): - dp.append(dp[i-1]+dp[i-2]) - -print(dp[n]) \ No newline at end of file diff --git a/beakjoon1202_bag_jwelry.py b/beakjoon1202_bag_jwelry.py deleted file mode 100644 index df5571a..0000000 --- a/beakjoon1202_bag_jwelry.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys - -N = int(sys.stdin.readline()) - - - -num = [int(sys.stdin.readline()) for _ in range(N)] - -num.sort(reverse=True) -Sum=0 -i=0 -while num[i]>1 and num[i+1]>1 and imatrix[X][Y]: - if check[X][Y] >=0: - cnt += check[X][Y] - else: - cnt += dfs(X,Y) - check[x][y] = cnt - return cnt #최종 긑나면 cnt반환까지 해줘야함. -cnt = dfs(0,0) -print(cnt) - - -# 결국 아이디어는 미로찾기에서 경로의 수와 비슷함. 모서리마다 경우의 수를 더하여 -# 사거리, 삼거리 , 골목길에서는 각 모서리들의 경우의 수의 합을 하다보면 최종 도착 시 경우의 수가 나옴. \ No newline at end of file diff --git a/beakjoon1463.py b/beakjoon1463.py index 45a7f15..967ea72 100644 --- a/beakjoon1463.py +++ b/beakjoon1463.py @@ -1,22 +1,22 @@ -import sys - -N=int(sys.stdin.readline()) -cnt=0 -bag=[3,5] - -while N != 0: - if N%3==0: - cnt += N//3 - N=0 - elif N%2==0: - cnt += N//2 - N=0 - elif N < 0: - print(-1) - break - else: - N = N-1 - cnt += 1 - -if N==0: +import sys + +N=int(sys.stdin.readline()) +cnt=0 +bag=[3,5] + +while N != 0: + if N%3==0: + cnt += N//3 + N=0 + elif N%2==0: + cnt += N//2 + N=0 + elif N < 0: + print(-1) + break + else: + N = N-1 + cnt += 1 + +if N==0: print(cnt) \ No newline at end of file diff --git a/beakjoon1463_dp.py b/beakjoon1463_dp.py index e4ab3d0..b268912 100644 --- a/beakjoon1463_dp.py +++ b/beakjoon1463_dp.py @@ -1,18 +1,18 @@ -import sys - -T = int(sys.stdin.readline()) -dp = [0 for _ in range(11)] -for i in range(4,11): - dp[1] = 1 - dp[2] = 2 - dp[3] = 4 - dp[i] = dp[i-1] + dp[i-2] + dp[i-3] -for test in range(T): - N = int(sys.stdin.readline()) - - print(dp[N]) - - - - - +import sys + +T = int(sys.stdin.readline()) +dp = [0 for _ in range(11)] +for i in range(4,11): + dp[1] = 1 + dp[2] = 2 + dp[3] = 4 + dp[i] = dp[i-1] + dp[i-2] + dp[i-3] +for test in range(T): + N = int(sys.stdin.readline()) + + print(dp[N]) + + + + + diff --git a/beakjoon1520_DP_DFS_repeat_practice_essential.py b/beakjoon1520_DP_DFS_repeat_practice_essential.py deleted file mode 100644 index 6b08017..0000000 --- a/beakjoon1520_DP_DFS_repeat_practice_essential.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys - -A = list(sys.stdin.readline()) -B = list(sys.stdin.readline()) -A.pop() -B.pop() -cnt = 0 -dp = [] - - -for i in range(len(A)): - for j in range(len(B)): - if A[i] == B[j]: - for m in range(min(len(A)-i,len(B)-j)): - if A[i+m]==B[j+m]: - cnt+=1 - else: - dp.append(cnt) - cnt=0 - break - -print(dp) - diff --git a/beakjoon1715.py b/beakjoon1715.py deleted file mode 100644 index 6d6673d..0000000 --- a/beakjoon1715.py +++ /dev/null @@ -1,28 +0,0 @@ -import sys, heapq - -N, K = map(int,sys.stdin.readline().split()) - - -jew = [list(map(int,sys.stdin.readline().split())) for _ in range(N)] - -bag = [int(sys.stdin.readline()) for _ in range(K)] - -max_value = 0 - -jew = sorted(jew) -bag = sorted(bag) - - -max_heap = [] -i=0 - -for j in range(K): - while i1: - plus.append(num[i]) - elif num[i]<0: - minus.append(num[i]) - else: - zeroOne.append(num[i]) - -Sum = 0 - - diff --git a/beakjoon1912.py b/beakjoon1912.py deleted file mode 100644 index f7823be..0000000 --- a/beakjoon1912.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys - -n = int(sys.stdin.readline()) - -dp = [[0]*10 for _ in range(n)] - -dp[0] = [0,1,1,1,1,1,1,1,1,1] -if n>1: - dp[1] = [1,1,2,2,2,2,2,2,2,1] - -if n>2: - for i in range(2,n): - for j in range(10): - if j==0: - dp[i][j] = dp[i-1][1] - elif j==9: - dp[i][j] = dp[i-1][8] - else: - dp[i][j] = dp[i-1][j-1]+dp[i-1][j+1] - -print(sum(dp[n-1])) \ No newline at end of file diff --git a/beakjoon1932_DP.py b/beakjoon1932_DP.py deleted file mode 100644 index f29e7b9..0000000 --- a/beakjoon1932_DP.py +++ /dev/null @@ -1,22 +0,0 @@ -import sys - -n = int(sys.stdin.readline()) -wine = [] -drink = [] -for _ in range(n): - wine.append(int(sys.stdin.readline())) - - -drink.append(wine[0]) -if n>1: - drink.append(wine[0]+wine[1]) -if n>2: - drink.append(max(wine[0]+wine[2],wine[1]+wine[2])) -if n>3: - for i in range(3,n): - drink.append(max(drink[i-2]+wine[i],drink[i-3]+wine[i-1]+wine[i],drink[i-1])) - -print(drink[n-1]) - -# 출발지점, 도착지점이 정해지지 않으면 이전까지 모든 값중 max값을 찾으면됨. -# 그리고 두칸띄워도됨. \ No newline at end of file diff --git a/beakjoon2156_DP_condition_lookcareful.py b/beakjoon2156_DP_condition_lookcareful.py deleted file mode 100644 index 17afe21..0000000 --- a/beakjoon2156_DP_condition_lookcareful.py +++ /dev/null @@ -1,10 +0,0 @@ - -n = int(input()) -a = list(map(int, input().split())) -dp = [0 for i in range(n)] -for i in range(n): - for j in range(i): - if a[i] > a[j] and dp[i] < dp[j]: - dp[i] = dp[j] - dp[i] += 1 -print(dp) diff --git a/beakjoon2579_DP_for.py b/beakjoon2579_DP_for.py deleted file mode 100644 index feeaf20..0000000 --- a/beakjoon2579_DP_for.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys - -n = int(sys.stdin.readline()) -score =[0]*300 -dp=[0]*300 - -for _ in range(n): - score.append(int(sys.stdin.readline())) - -dp.append(score[0]) -dp.append(score[0]+score[1]) -dp.append(max(score[0]+score[2],score[1]+score[2])) - - -for i in range(3,n): - dp.append(max(dp[i-2]+score[i],dp[i-3]+score[i]+score[i-1])) - -print(dp[n-1]) - diff --git a/beakjoon2579_DP_limitconditon_care.py b/beakjoon2579_DP_limitconditon_care.py deleted file mode 100644 index 691e459..0000000 --- a/beakjoon2579_DP_limitconditon_care.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys - -n = int(sys.stdin.readline()) - -s = list(map(int,sys.stdin.readline().split())) - -max = 0 -sum = 0 - - -for i in range(n): - if sum>0: - sum += s[i] - if sum>max: - max = sum - else: - sum = s[i] - -print(max) \ No newline at end of file diff --git a/beakjoon2748_DP.py b/beakjoon2748_DP.py deleted file mode 100644 index 283e895..0000000 --- a/beakjoon2748_DP.py +++ /dev/null @@ -1,26 +0,0 @@ - - - - -n = int(input()) - -T = [0] -P = [0] -dp = [0] -for _ in range(n): - t,p = map(int, input().split()) - T.append(t) - P.append(p) - dp.append(p) - -dp.append(0) #맨뒤시작 누적p는 0으로 설정.(dp[n]=0으로 설정된것.) - -for i in range(n,0,-1): - if T[i]+i>n: #t[i]값(소요일자) + i(날짜) 의 합이 d-day를 넘으면 선택하지않음. - dp[i] = dp[i+1] #날짜 넘어가면 선택안하고 1더한오른쪽값(이전값을 가져옴(역순이기때문.)) - else: #선택이 가능하면 - dp[i] = max(dp[i+1],P[i]+dp[i+T[i]]) #나를 선택하지 않는 값과 나를 선택(p + dp[내위치+t[i]즉 내 위치를 선택했을때 도착하는 다음 노드의dp누적값]중에 더 큰것을 선택한다.) - # 역산하면서 선택하면 전에 선택한 노드의dp값을 계승해 더하는 식으로 각 노드의 dp값을 계산. - - -print(dp) \ No newline at end of file diff --git a/beakjoon2839.py b/beakjoon2839.py index 45a7f15..967ea72 100644 --- a/beakjoon2839.py +++ b/beakjoon2839.py @@ -1,22 +1,22 @@ -import sys - -N=int(sys.stdin.readline()) -cnt=0 -bag=[3,5] - -while N != 0: - if N%3==0: - cnt += N//3 - N=0 - elif N%2==0: - cnt += N//2 - N=0 - elif N < 0: - print(-1) - break - else: - N = N-1 - cnt += 1 - -if N==0: +import sys + +N=int(sys.stdin.readline()) +cnt=0 +bag=[3,5] + +while N != 0: + if N%3==0: + cnt += N//3 + N=0 + elif N%2==0: + cnt += N//2 + N=0 + elif N < 0: + print(-1) + break + else: + N = N-1 + cnt += 1 + +if N==0: print(cnt) \ No newline at end of file diff --git a/beakjoon9095_dp.py b/beakjoon9095_dp.py index d1a7926..35396f6 100644 --- a/beakjoon9095_dp.py +++ b/beakjoon9095_dp.py @@ -1,32 +1,32 @@ -import sys - -T = int(sys.stdin.readline()) - -N,W = map(int,sys.stdin.readline().split()) - -circle = [list(map(int,sys.stdin.readline().split()))for _ in range(2)] - -check = [[0]*8 for _ in range(2)] -cnt = 0 - -for j in range(2): - for i in range(8): - if check[i][j] ==0: - if circle[i][j] < W: - if circle[i][j]+circle[(i-1)%8][j] <=100 and check[(i-1)%8][j] ==0: - check[i][j], check[(i-1)%8][j] = 1,1 - cnt +=1 - elif circle[i][j]+circle[(i+1)%8][j] <=100 and check[(i+1)%8][j] ==0: - check[i][j], check[(i+1)%8][j] = 1,1 - cnt +=1 - elif circle[i][j]+circle[i][(j-1)%2] <=100 and check[i][(j-1)%2] ==0: - check[i][j], check[i][(j-1)%2] = 1,1 - cnt +=1 - elif circle[i][j]+circle[i][(j+1)%2] <=100 and check[i][(j+1)%2] ==0: - check[i][j], check[i][(j+1)%2] = 1,1 - cnt +=1 - else: - check[i][j]=1 - cnt +=1 - +import sys + +T = int(sys.stdin.readline()) + +N,W = map(int,sys.stdin.readline().split()) + +circle = [list(map(int,sys.stdin.readline().split()))for _ in range(2)] + +check = [[0]*8 for _ in range(2)] +cnt = 0 + +for j in range(2): + for i in range(8): + if check[i][j] ==0: + if circle[i][j] < W: + if circle[i][j]+circle[(i-1)%8][j] <=100 and check[(i-1)%8][j] ==0: + check[i][j], check[(i-1)%8][j] = 1,1 + cnt +=1 + elif circle[i][j]+circle[(i+1)%8][j] <=100 and check[(i+1)%8][j] ==0: + check[i][j], check[(i+1)%8][j] = 1,1 + cnt +=1 + elif circle[i][j]+circle[i][(j-1)%2] <=100 and check[i][(j-1)%2] ==0: + check[i][j], check[i][(j-1)%2] = 1,1 + cnt +=1 + elif circle[i][j]+circle[i][(j+1)%2] <=100 and check[i][(j+1)%2] ==0: + check[i][j], check[i][(j+1)%2] = 1,1 + cnt +=1 + else: + check[i][j]=1 + cnt +=1 + print(cnt) \ No newline at end of file diff --git a/beakjoon9250_DP_LCS.py b/beakjoon9250_DP_LCS.py deleted file mode 100644 index c2c3517..0000000 --- a/beakjoon9250_DP_LCS.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys - -A = list(sys.stdin.readline()) -B = list(sys.stdin.readline()) -A.pop() -B.pop() -cnt = 0 -dp = [[0]*len(B) for _ in range(len(A))] - - -for i in range(len(A)): - for j in range(len(B)): - if A[i] == B[j]: - - -print(dp) - -ACAYKP -CAPCAK \ No newline at end of file diff --git a/bfs.py b/bfs.py index b7a4a3a..db8d535 100644 --- a/bfs.py +++ b/bfs.py @@ -1,74 +1,74 @@ -# 순열 - -def permute(arr): - result = [arr[:]] - c = [0] * len(arr) - i = 0 - while i < len(arr): - if c[i] < i: - if i % 2 == 0: - arr[0], arr[i] = arr[i], arr[0] - else: - arr[c[i]], arr[i] = arr[i], arr[c[i]] - - result.append(arr[:]) - c[i] += 1 - i = 0 - else: - c[i] = 0 - i += 1 - return result - -# 재귀순열 -def perm(lis, n): - result = [] - if n > len(lis): - return result - if n == 1: - for li in lis: - result.append([li]) - elif n > 1: - for i in range(len(lis)): - tmp = [i for i in lis] - tmp.remove(lis[i]) - for j in perm(tmp, n-1): - result.append([lis[i]]+j) - return result - -n = int(input()) -lis = list(i for i in range(1, n+1)) -for li in perm(lis,n): - print(' '.join(list(map(str, li)))) - -# 리스트 그래프 -s = [[0]*6 for i in range(6)] s[1][2] = 1 s[2][1] = 1 s[1][3] = 1 s[3][1] = 1 s[2][4] = 1 s[4][2] = 1 s[2][5] = 1 s[5][2] = 1 - -# dic그래프 -adj_list = {1: set([2,3]), 2: set([1,4,5]), 3: set([1]), 4: set([2]), 5: set([2])} - -# bfs - -def bfs(graph, start): - visited = [] - queue = [start] - while queue: - n = queue.pop(0) - if n not in visited: - visited.append(n) - queue += graph[n] - set(visited) - return visited - -# deque bfs - -from collections import deque - -def bfs_dequeue(graph, start): - visited = [] - queue = deque([start]) - - while queue: - n = queue.popleft() - if n not in visited: - visited.append(n) - queue += graph[n] - set(visited) - return visited +# 순열 + +def permute(arr): + result = [arr[:]] + c = [0] * len(arr) + i = 0 + while i < len(arr): + if c[i] < i: + if i % 2 == 0: + arr[0], arr[i] = arr[i], arr[0] + else: + arr[c[i]], arr[i] = arr[i], arr[c[i]] + + result.append(arr[:]) + c[i] += 1 + i = 0 + else: + c[i] = 0 + i += 1 + return result + +# 재귀순열 +def perm(lis, n): + result = [] + if n > len(lis): + return result + if n == 1: + for li in lis: + result.append([li]) + elif n > 1: + for i in range(len(lis)): + tmp = [i for i in lis] + tmp.remove(lis[i]) + for j in perm(tmp, n-1): + result.append([lis[i]]+j) + return result + +n = int(input()) +lis = list(i for i in range(1, n+1)) +for li in perm(lis,n): + print(' '.join(list(map(str, li)))) + +# 리스트 그래프 +s = [[0]*6 for i in range(6)] s[1][2] = 1 s[2][1] = 1 s[1][3] = 1 s[3][1] = 1 s[2][4] = 1 s[4][2] = 1 s[2][5] = 1 s[5][2] = 1 + +# dic그래프 +adj_list = {1: set([2,3]), 2: set([1,4,5]), 3: set([1]), 4: set([2]), 5: set([2])} + +# bfs + +def bfs(graph, start): + visited = [] + queue = [start] + while queue: + n = queue.pop(0) + if n not in visited: + visited.append(n) + queue += graph[n] - set(visited) + return visited + +# deque bfs + +from collections import deque + +def bfs_dequeue(graph, start): + visited = [] + queue = deque([start]) + + while queue: + n = queue.popleft() + if n not in visited: + visited.append(n) + queue += graph[n] - set(visited) + return visited diff --git a/bitsolved.py b/bitsolved.py index 15d5961..5faa57e 100644 --- a/bitsolved.py +++ b/bitsolved.py @@ -1,31 +1,31 @@ -def d(c): - if ord('0') <= ord(c) <= ord('9'): - return ord(c)-ord('0') - return ord(c)-ord('A')+10 -def to36(n): - if n == 0: - return "0" - S = "" - d = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] - while n > 0: - S += d[n%36] - n = n // 36 - return S[::-1] -N = int(input()) -val = [0]*36 -for _ in range(N): - S = input() - for i in range(len(S)): - val[d(S[i])] += 36**(len(S)-i-1) -K = int(input()) -arr = [[0]*2 for i in range(36)] -for i in range(36): - arr[i][0] = val[i]*(35-i) - arr[i][1] = i -arr.sort() -ans = 0 -for i in range(36-K): - ans += val[arr[i][1]]*arr[i][1] -for i in range(36-K, 36): - ans += val[arr[i][1]]*35 +def d(c): + if ord('0') <= ord(c) <= ord('9'): + return ord(c)-ord('0') + return ord(c)-ord('A')+10 +def to36(n): + if n == 0: + return "0" + S = "" + d = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] + while n > 0: + S += d[n%36] + n = n // 36 + return S[::-1] +N = int(input()) +val = [0]*36 +for _ in range(N): + S = input() + for i in range(len(S)): + val[d(S[i])] += 36**(len(S)-i-1) +K = int(input()) +arr = [[0]*2 for i in range(36)] +for i in range(36): + arr[i][0] = val[i]*(35-i) + arr[i][1] = i +arr.sort() +ans = 0 +for i in range(36-K): + ans += val[arr[i][1]]*arr[i][1] +for i in range(36-K, 36): + ans += val[arr[i][1]]*35 print(to36(ans)) \ No newline at end of file diff --git a/calkin_wilf_tree1.py b/calkin_wilf_tree1.py index 6d315c1..3f4119d 100644 --- a/calkin_wilf_tree1.py +++ b/calkin_wilf_tree1.py @@ -1,25 +1,25 @@ -T = int(input()) - - - -for test_case in range(1, T + 1): - P = list(input()) - Q = list(input()) - - for i in range(len(P)): - if len(Q) == len(P)+1 and Q[-1] == "a": - if P[i] == Q[i]: - answer = 1 - continue - else: - answer = 0 - else: - answer = 0 - break - if answer == 1: - print("#{} N".format(test_case)) - else: - print("#{} Y".format(test_case)) - - +T = int(input()) + + + +for test_case in range(1, T + 1): + P = list(input()) + Q = list(input()) + + for i in range(len(P)): + if len(Q) == len(P)+1 and Q[-1] == "a": + if P[i] == Q[i]: + answer = 1 + continue + else: + answer = 0 + else: + answer = 0 + break + if answer == 1: + print("#{} N".format(test_case)) + else: + print("#{} Y".format(test_case)) + + \ No newline at end of file diff --git a/climb_mountain.py b/climb_mountain.py deleted file mode 100644 index 2840797..0000000 --- a/climb_mountain.py +++ /dev/null @@ -1,22 +0,0 @@ -import collections as col - -T = int(input()) -def find_mfn(): - students = list(map(int,input().split())) - cnt = col.Counter(students) - mfn = cnt.most_common() - maxf = mfn[0][1] - - maxes = [] - - for i in range(len(students)): - if mfn[i][1] == maxf: - maxes.append(mfn[i][0]) - else: - break - - answer = max(maxes) - - -for testcase in range(T): - print("#{} {}".format(testcase+1,answer)) \ No newline at end of file diff --git "a/codeforce#320A\353\260\225\355\205\214\353\246\254\354\225\204\355\202\244\354\232\260\352\270\260.py" "b/codeforce#320A\353\260\225\355\205\214\353\246\254\354\225\204\355\202\244\354\232\260\352\270\260.py" deleted file mode 100644 index ed7c0ec..0000000 --- "a/codeforce#320A\353\260\225\355\205\214\353\246\254\354\225\204\355\202\244\354\232\260\352\270\260.py" +++ /dev/null @@ -1,5 +0,0 @@ -cnt = 0 -for char in bin(int(input())): - if char == '1': - cnt += 1 -print(cnt) \ No newline at end of file diff --git "a/codeforce/#656/A_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#656/A_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 1abad66..0000000 --- "a/codeforce/#656/A_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - x, y, z = map(int, input().split()) - # x.ab, y.ac, z.bc - if x == y: - # a > b, a >= c - # b = a, a >= c - # b > a, b = c - pass - elif x > y: - pass - else: - pass diff --git "a/codeforce/#656/B_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#656/B_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 7f951bb..0000000 --- "a/codeforce/#656/B_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n, m = map(int, input().split()) - answer = 0 - for _ in range(n): - a, b = map(int, input().split()) - c, d = map(int, input().split()) - if b == c: - answer = 1 - if m & 1: - answer = 0 - print("YES" if answer else "NO") - diff --git "a/codeforce/#656/C_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#656/C_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 0c38a8a..0000000 --- "a/codeforce/#656/C_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline -from math import sqrt - -for test in range(int(input())): - n = int(input()) - answer = float('inf') - t = sqrt(n) - for i in range(-5, 6, 1): - t2 = int(t - i) - if t2 > n or t2 < 1: - continue - answer = min(answer, t2 - 2 + (n + t2 - 1) // t2) - print(answer) - # for k in range(1, n + 1): - # cnt = (k - 1) + ((n - k) + k - 1) / k - # if cnt > answer: - # break - # else: - # answer = cnt - diff --git "a/codeforce/#656/D_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#656/D_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index f542747..0000000 --- "a/codeforce/#656/D_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -a = list(map(int, input().split())) -segments = {0} -cnt, s = 0, 0 -for i in range(n): - s += a[i] - if s in segments: - cnt += 1 - segments = {0} - s = a[i] - segments.add(s) -print(cnt) diff --git "a/codeforce/#656/E_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#656/E_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index af160fe..0000000 --- "a/codeforce/#656/E_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,5 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) diff --git "a/codeforce/#656/F_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#656/F_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 9592120..0000000 --- "a/codeforce/#656/F_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,7 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) \ No newline at end of file diff --git "a/codeforce/#674/A_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#674/A_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 714b994..0000000 --- "a/codeforce/#674/A_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline -from math import ceil - - -for test in range(int(input())): - n, x = map(int, input().split()) - answer = ceil((n - 2) / x) + 1 - if n < 2: - answer = 1 - print(answer) \ No newline at end of file diff --git "a/codeforce/#674/B_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#674/B_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 7f951bb..0000000 --- "a/codeforce/#674/B_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n, m = map(int, input().split()) - answer = 0 - for _ in range(n): - a, b = map(int, input().split()) - c, d = map(int, input().split()) - if b == c: - answer = 1 - if m & 1: - answer = 0 - print("YES" if answer else "NO") - diff --git "a/codeforce/#674/C_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#674/C_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 0c38a8a..0000000 --- "a/codeforce/#674/C_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,21 +0,0 @@ -import sys -input = sys.stdin.readline -from math import sqrt - -for test in range(int(input())): - n = int(input()) - answer = float('inf') - t = sqrt(n) - for i in range(-5, 6, 1): - t2 = int(t - i) - if t2 > n or t2 < 1: - continue - answer = min(answer, t2 - 2 + (n + t2 - 1) // t2) - print(answer) - # for k in range(1, n + 1): - # cnt = (k - 1) + ((n - k) + k - 1) / k - # if cnt > answer: - # break - # else: - # answer = cnt - diff --git "a/codeforce/#674/D_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#674/D_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index f542747..0000000 --- "a/codeforce/#674/D_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -a = list(map(int, input().split())) -segments = {0} -cnt, s = 0, 0 -for i in range(n): - s += a[i] - if s in segments: - cnt += 1 - segments = {0} - s = a[i] - segments.add(s) -print(cnt) diff --git "a/codeforce/#674/E_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#674/E_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index af160fe..0000000 --- "a/codeforce/#674/E_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,5 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) diff --git "a/codeforce/#674/F_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#674/F_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 9592120..0000000 --- "a/codeforce/#674/F_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,7 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) \ No newline at end of file diff --git "a/codeforce/#686/A_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#686/A_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 24a0deb..0000000 --- "a/codeforce/#686/A_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - answer = [i for i in range(n, 0, -1)] - if n & 1: - answer.append(answer.pop(n//2)) - print(*answer) \ No newline at end of file diff --git "a/codeforce/#686/B_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#686/B_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index f1240fc..0000000 --- "a/codeforce/#686/B_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop, heappush -from collections import defaultdict - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - cnt = defaultdict(int) - heap = [] - for idx, num in enumerate(arr): - heappush(heap, (num, idx + 1)) - cnt[num] += 1 - while heap and cnt[heap[0][0]] != 1: - heappop(heap) - if heap: - print(heap[0][1]) - else: - print(-1) \ No newline at end of file diff --git "a/codeforce/#686/C_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#686/C_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 887de3f..0000000 --- "a/codeforce/#686/C_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,23 +0,0 @@ - -import sys -input = sys.stdin.readline -from collections import defaultdict - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - cnt = defaultdict(int) - for i in range(1, n): - if arr[i] != arr[i - 1]: - cnt[arr[i]] += 1 - if not cnt: - print(0) - continue - if arr[0] not in cnt: - print(1) - continue - min_value = min(cnt.values()) - if min_value != cnt[arr[-1]]: - min_value += 1 - print(min_value) \ No newline at end of file diff --git "a/codeforce/#686/D_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#686/D_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 35c31dd..0000000 --- "a/codeforce/#686/D_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,37 +0,0 @@ -import sys -input = sys.stdin.readline - -def sieve(n): - m = int(n ** 0.5) + 1 - s = [True] * (m) - for i in range(2, m): - if s[i] == True: - for j in range(i + i, m, i): - s[j] = False - return [i for i in range(2, m) if s[i] == True] - -for test in range(int(input())): - n = int(input()) - primes = sieve(n) - max_cnt = 0 - max_num = 0 - for prime in primes: - tmp = n - cnt = 0 - while not tmp % prime: - tmp //= prime - cnt += 1 - if max_cnt < cnt: - max_cnt = cnt - max_num = prime - rest = tmp - if tmp == 1: - break - if max_cnt < 2: - print(1) - print(n) - else: - print(max_cnt) - for _ in range(max_cnt - 1): - print(max_num, end = ' ') - print(max_num * rest) \ No newline at end of file diff --git "a/codeforce/#686/E_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#686/E_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 989048f..0000000 --- "a/codeforce/#686/E_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,54 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict -sys.setrecursionlimit(10**6) - -def dfs(cur_node, pre_node): - visited[cur_node] = 1 - for next_node in graph[cur_node]: - if next_node == pre_node: - continue - if visited[next_node]: - if visited[next_node] == 1: - isCycle[next_node] = 2 - isCycle[cur_node] = 1 - else: - dfs(next_node, cur_node) - - if isCycle[next_node] == 1 and isCycle[cur_node] != 2: - isCycle[cur_node] = 1 - visited[cur_node] = 2 - - -def dfs2(cur_node, pre_node): - res = 1 - for next_node in graph[cur_node]: - if next_node == pre_node: continue - if isCycle[next_node]: continue - res += dfs2(next_node, cur_node) - - return res - - -# 사이클이 없다면 n(n-1)/2개의 단순 경로(a출발, b도착)이지만 -# 사이클이 있기 때문에 (a, b)의 경로가 2개일 수 있다(사이클을 돌고 도착하는) -# 따라서 n(n-1)에서 사이클을 돌지 않는 (a,b)의 갯수를 빼주면 답이다. -# 사이클의 각 정정에서 뻗어나가는 트리(사이클이 없는)의 크기 (s(s-1)/2)를 각각 빼주면 된다. -for test in range(int(input())): - n = int(input()) - graph = defaultdict(list) - isCycle = [0] * (n + 1) - visited = [0] * (n + 1) - for _ in range(n): - u, v = map(int , input().split()) - graph[u] += [v] - graph[v] += [u] - - answer = n * (n - 1) - dfs(1, 0) - for i in range(1, n + 1): - if isCycle[i]: - res = dfs2(i, 0) - answer -= res * (res - 1) // 2 - - print(answer) \ No newline at end of file diff --git "a/codeforce/#686/F_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#686/F_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 9592120..0000000 --- "a/codeforce/#686/F_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,7 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) \ No newline at end of file diff --git "a/codeforce/#690/A_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#690/A_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 82a4e43..0000000 --- "a/codeforce/#690/A_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - left, right = 0, n - 1 - answer = [] - while left <= right: - answer.append(arr[left]) - if left == right: - break - answer.append(arr[right]) - left += 1 - right -= 1 - print(*answer) \ No newline at end of file diff --git "a/codeforce/#690/B_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#690/B_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 4558068..0000000 --- "a/codeforce/#690/B_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - s = input().rstrip() - answer = '2020' - if s[0] + s[-3:] == answer or s[:2] + s[-2:] == answer or s[:3] + s[-1] == answer or s[:4] == answer or s[-4:] == answer: - print("YES") - else: - print("NO") \ No newline at end of file diff --git "a/codeforce/#690/C_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#690/C_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 635b794..0000000 --- "a/codeforce/#690/C_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,17 +0,0 @@ - -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - x = int(input()) - answer, flag = '', 0 - for num in range(9, 0, -1): - if x >= num: - x -= num - answer += str(num) - if not x: - print(answer[::-1]) - break - else: - print(-1) \ No newline at end of file diff --git "a/codeforce/#690/D_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#690/D_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 70faa1d..0000000 --- "a/codeforce/#690/D_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - total = sum(arr) - candidate = [num for num in range(1, total + 1) if not total % num] - for target in candidate: - tmp, answer = 0, 0 - for num in arr: - tmp += num - answer += 1 - if tmp == target: - tmp = 0 - answer -= 1 - elif tmp > target: - break - else: - print(answer) - break \ No newline at end of file diff --git "a/codeforce/#690/E1_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#690/E1_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index a14f78b..0000000 --- "a/codeforce/#690/E1_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - arr.sort() - done = {} - answer = 0 - for i in range(n - 2): - if arr[i] not in done: - right = bisect_left(arr, arr[i] + 3) - done[arr[i]] = right - length = done[arr[i]] - i - if length > 2: - length -= 2 - answer += length * (length + 1) // 2 - print(answer) \ No newline at end of file diff --git "a/codeforce/#690/E2_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#690/E2_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index f838c3e..0000000 --- "a/codeforce/#690/E2_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_right -from math import factorial - -MOD = int(1e9) + 7 -for test in range(int(input())): - n, m, k = map(int, input().split()) - arr = list(map(int, input().split())) - arr.sort() - done = {} - answer = 0 - for i in range(n - m + 1): - if arr[i] not in done: - right = bisect_right(arr, arr[i] + k) - done[arr[i]] = right - length = done[arr[i]] - i - if length >= m: - answer += factorial(length - 1) // (factorial(m - 1) * factorial(length - m)) - print(answer) diff --git "a/codeforce/#690/F_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#690/F_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index a6f8403..0000000 --- "a/codeforce/#690/F_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,6 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - pass \ No newline at end of file diff --git "a/codeforce/#697/A_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#697/A_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 1063821..0000000 --- "a/codeforce/#697/A_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - left, right = 0, n - 1 - answer = [] - while left <= right: - answer.append(arr[left]) - if left == right: - break - answer.append(arr[right]) - left += 1 - right -= 1 - print(*answer) \ No newline at end of file diff --git "a/codeforce/#697/B_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#697/B_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 4558068..0000000 --- "a/codeforce/#697/B_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - s = input().rstrip() - answer = '2020' - if s[0] + s[-3:] == answer or s[:2] + s[-2:] == answer or s[:3] + s[-1] == answer or s[:4] == answer or s[-4:] == answer: - print("YES") - else: - print("NO") \ No newline at end of file diff --git "a/codeforce/#697/C_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#697/C_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index c2ad941..0000000 --- "a/codeforce/#697/C_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - x = int(input()) - answer = '' - for num in range(9, 0, -1): - if x >= num: - x -= num - answer += str(num) - if not x: - print(answer[::-1]) - break - else: - print(-1) \ No newline at end of file diff --git "a/codeforce/#697/D_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#697/D_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index a53fd3c..0000000 --- "a/codeforce/#697/D_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - total = sum(arr) - candidate = [num for num in range(1, total + 1) if not total % num] - for target in candidate: - tmp, answer = 0, 0 - for num in arr: - tmp += num - answer += 1 - if tmp == target: - tmp = 0 - answer -= 1 - elif tmp > target: - break - else: - print(answer) - break \ No newline at end of file diff --git "a/codeforce/#697/E1_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#697/E1_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index ec2cb3a..0000000 --- "a/codeforce/#697/E1_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - arr.sort() - done = {} - answer = 0 - for i in range(n - 2): - if arr[i] not in done: - right = bisect_left(arr, arr[i] + 3) - done[arr[i]] = right - length = done[arr[i]] - i - if length > 2: - length -= 2 - answer += length * (length + 1) // 2 - print(answer) diff --git "a/codeforce/#697/E2_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#697/E2_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index b71770f..0000000 --- "a/codeforce/#697/E2_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_right -from math import factorial - -MOD = int(1e9) + 7 -for test in range(int(input())): - n, m, k = map(int, input().split()) - arr = list(map(int, input().split())) - arr.sort() - done = {} - answer = 0 - for i in range(n - m + 1): - if arr[i] not in done: - right = bisect_right(arr, arr[i] + k) - done[arr[i]] = right - length = done[arr[i]] - i - if length >= m: - answer += (factorial(length - 1) // (factorial(m - 1) * factorial(length - m))) % MOD - print(answer % MOD) diff --git "a/codeforce/#697/F_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#697/F_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index a6f8403..0000000 --- "a/codeforce/#697/F_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,6 +0,0 @@ -import sys -input = sys.stdin.readline - - -for test in range(int(input())): - pass \ No newline at end of file diff --git "a/codeforce/#702/A_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#702/A_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 0375a94..0000000 --- "a/codeforce/#702/A_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - answer = 0 - for i in range(n - 1): - a, b = arr[i], arr[i + 1] - if a > b: - a, b = b, a - while 2 * a < b: - answer += 1 - b /= 2 - print(answer) \ No newline at end of file diff --git "a/codeforce/#702/B_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#702/B_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index f8d7350..0000000 --- "a/codeforce/#702/B_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,40 +0,0 @@ -import sys -input = sys.stdin.readline - -def check(d): - pivot = d[0] - for i in range(1, 3): - if d[i] != pivot: - return True - return False - -def move(over, d): - global answer - for i in range(3): - if not over and d[i] > n // 3: - pivot = d[i] - (n // 3) - over.append((i, pivot)) - d[i] -= pivot - elif over and d[i] < n // 3: - idx, num = over.pop() - if idx < i: - dist = num * (i - idx) - else: - dist = num * (3 - (idx - i)) - d[i] += num - answer += dist - over = [] - if over: - move(over, d) - return d - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - count = {0: 0, 1: 0, 2: 0} - answer = 0 - for num in arr: - count[num%3] += 1 - while check(count): - count = move([], count) - print(answer) \ No newline at end of file diff --git "a/codeforce/#702/C_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#702/C_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 47223ba..0000000 --- "a/codeforce/#702/C_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -dic = {} -for i in range(1, 10001): - dic[i**3] = True - -for test in range(int(input())): - x = int(input()) - for num in dic: - if x - num in dic: - print("YES") - break - if num > x // 2: - print("NO") - break \ No newline at end of file diff --git "a/codeforce/#702/D_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#702/D_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index cf5541d..0000000 --- "a/codeforce/#702/D_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -def make_tree(depth, a): - if not a: - return a - max_num = 0 - for idx, num in enumerate(a): - if max_num < num: - max_idx = idx - max_num = num - answer[dic[max_num]] = depth - make_tree(depth+1, a[:max_idx]) - make_tree(depth+1, a[max_idx+1:]) - - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - dic = {num: idx for idx, num in enumerate(arr)} - answer = [0] * n - make_tree(0, arr) - print(*answer) \ No newline at end of file diff --git "a/codeforce/#702/E_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#702/E_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index ba273e7..0000000 --- "a/codeforce/#702/E_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop, heappush - - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - heap = [] - for idx, num in enumerate(arr): - heappush(heap, (num, idx)) - total, answer = 0, [] - while heap: - num, idx = heappop(heap) - if total >= num: - answer.append(idx + 1) - else: - answer = [idx + 1] - total += num - answer.sort() - print(len(answer)) - print(*answer) - - diff --git "a/codeforce/#702/F_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#702/F_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 76a9e8c..0000000 --- "a/codeforce/#702/F_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - counter = defaultdict(int) - for num in arr: - counter[num] += 1 - candidate = set() - for target in counter.values(): - candidate.add(target) - answer = float('inf') - for target in candidate: - total = 0 - for cnt in counter.values(): - if cnt == target: - continue - if target > cnt: - total += cnt - else: - total += cnt - target - if total >= answer: - break - answer = min(answer, total) - print(answer) \ No newline at end of file diff --git "a/codeforce/#702/G_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#702/G_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 2ca4fe3..0000000 --- "a/codeforce/#702/G_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -# 풀이 참고했는데 -for test in range(int(input())): - n, m = map(int, input().split()) - arr = list(map(int, input().split())) - prefix_sum, idxes, idx, total = [], [], 0, 0 - for num in arr: - total += num - if not prefix_sum or prefix_sum[-1] < total: - prefix_sum.append(total) - idxes.append(idx) - idx += 1 - x = list(map(int, input().split())) - answer = [] - for target in x: - # 총합이 더해질 수 없고 양의 총합보다 목표치가 높으면 도달할 수 없음 - if prefix_sum[-1] < target and total <= 0: - answer.append(-1) - continue - # 이부분이 이해가 잘 안감. - # 바퀴수 = (목표치 - 양의 최대치 + 총합 - 1) // 총합 ? - # 양의 최대치에서 목표치를 초과할 가능성에 대해 보정해주는건가? - cycle = 0 - if prefix_sum[-1] < target: - cycle = (target - prefix_sum[-1] + total - 1) // total - target -= cycle * total - # 바퀴수 * 크기 + 나머지의 누적합에서의 위치 - answer.append(cycle * n + idxes[bisect_left(prefix_sum, target)]) - print(*answer) \ No newline at end of file diff --git a/codeforce/#710/code_force_710_A.py b/codeforce/#710/code_force_710_A.py deleted file mode 100644 index a2061b8..0000000 --- a/codeforce/#710/code_force_710_A.py +++ /dev/null @@ -1,8 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n, m, x = map(int, input().split()) - row, col = (x - 1) % n, (x - 1) // n - answer = row * m + col + 1 - print(answer) \ No newline at end of file diff --git a/codeforce/#710/code_force_710_B.py b/codeforce/#710/code_force_710_B.py deleted file mode 100644 index f6cb8f9..0000000 --- a/codeforce/#710/code_force_710_B.py +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline - - -def dfs(cur_node, cnt): - global min_cnt - visited[cur_node] = cnt - if cur_node >= end: - min_cnt = min(min_cnt, cnt) - return - if cnt > min_cnt: - return - for next_node in range(cur_node + k, cur_node, -1): - if 0 <= next_node < n and s[next_node] == '*' and visited[next_node] > cnt + 1: - - dfs(next_node, cnt + 1) - -for test in range(int(input())): - n, k = map(int, input().split()) - s = input().strip() - visited = [float('inf')] * n - for i in range(n): - if s[i] == '*': - start = i - break - for j in range(n - 1, -1, -1): - if s[j] == '*': - end = j - break - min_cnt = float('inf') - dfs(start, 0) - print(min_cnt +1) \ No newline at end of file diff --git a/codeforce/#710/code_force_710_C.py b/codeforce/#710/code_force_710_C.py deleted file mode 100644 index f761cb7..0000000 --- a/codeforce/#710/code_force_710_C.py +++ /dev/null @@ -1,58 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import deque - - -def make_set(s): - if s in b_set: - return - if not s: - return - b_set.add(s) - make_set(s[1:]) - make_set(s[:-1]) - - -for test in range(int(input())): - a = input().rstrip() - b = input().rstrip() - if a == b: - print(0) - continue - if len(a) > len(b): - a, b = b, a - b_set = set() - answer = float('inf') - make_set(b) - start = -1 - end = -2 - for i in range(len(a)): - if a[i] in b_set: - start = i - break - for j in range(len(a) - 1, -1, -1): - if a[j] in b_set: - end = j - break - if start == end: - print(len(a) + len(b) - 2) - continue - elif start == -1 and end == -2: - print(len(a) + len(b)) - else: - new_a = a[start: end + 1] - if new_a in b_set: - print(len(a) + len(b) - len(new_a) * 2) - continue - q = deque() - q.append(new_a) - while q: - s = q.popleft() - left = s[1:] - right = s[:-1] - if left in b_set or right in b_set: - print(len(a) + len(b) - len(left) * 2) - break - else: - q.append(left) - q.append(right) diff --git a/codeforce/#710/code_force_710_D.py b/codeforce/#710/code_force_710_D.py deleted file mode 100644 index 85c2d3a..0000000 --- a/codeforce/#710/code_force_710_D.py +++ /dev/null @@ -1,49 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappush, heappop -from collections import defaultdict - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - min_heap = [] - max_heap = [] - counter = defaultdict(int) - for num in arr: - counter[num] += 1 - min_num = float('inf') - max_num = 0 - for num in counter: - heappush(min_heap, (counter[num], num)) - heappush(max_heap, (-counter[num], -num)) - while min_heap and max_heap: - min_count, min_num = heappop(min_heap) - max_count, max_num = heappop(max_heap) - print(counter, min_num, max_num) - while min_heap and min_count != counter[min_num]: - if counter[min_num]: - heappush(min_heap, (counter[min_num], min_num)) - min_count, min_num = heappop(min_heap) - while max_heap and -max_count != counter[-max_num]: - if counter[-max_num]: - heappush(max_heap, (-counter[max_num], max_num)) - max_count, max_num = heappop(max_heap) - if not counter[-max_num] or not counter[min_num] or min_num == -max_num: - break - counter[min_num] -= 1 - counter[-max_num] -= 1 - if counter[min_num]: - heappush(min_heap, (counter[min_num], min_num)) - if counter[-max_num]: - heappush(max_heap, (-counter[-max_num], max_num)) - while min_heap[0][1] == -max_heap[0][1]: - heappush(min_heap, heappop(min_heap)) - heappush(max_heap, heappop(max_heap)) - print(min_heap) - print(max_heap) - answer = 0 - for num in counter: - answer += counter[num] - if answer == -1: - answer = 1 - print(answer) \ No newline at end of file diff --git a/codeforce/#710/code_force_710_E.py b/codeforce/#710/code_force_710_E.py deleted file mode 100644 index e69de29..0000000 diff --git a/codeforce/#710/code_force_710_F.py b/codeforce/#710/code_force_710_F.py deleted file mode 100644 index e69de29..0000000 diff --git a/codeforce/#710/code_force_710_G.py b/codeforce/#710/code_force_710_G.py deleted file mode 100644 index e69de29..0000000 diff --git a/codeforce/#719/codeforce_719_1.py b/codeforce/#719/codeforce_719_1.py deleted file mode 100644 index 5ed4521..0000000 --- a/codeforce/#719/codeforce_719_1.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - a = list(input().rstrip()) - char_set = {a[0]: True} - for i in range(1, n): - if a[i - 1] != a[i]: - if a[i] in char_set: - print('NO') - break - else: - char_set[a[i]] = True - else: - print('YES') \ No newline at end of file diff --git a/codeforce/#719/codeforce_719_2.py b/codeforce/#719/codeforce_719_2.py deleted file mode 100644 index e061246..0000000 --- a/codeforce/#719/codeforce_719_2.py +++ /dev/null @@ -1,17 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - tmp = n - k = 0 - while tmp // 10: - tmp //= 10 - k += 9 - num = str(n) - k += int(num[0]) - 1 - if num >= num[0] * len(num): - k += 1 - print(k) - - \ No newline at end of file diff --git a/codeforce/#719/codeforce_719_3.py b/codeforce/#719/codeforce_719_3.py deleted file mode 100644 index e8e23f2..0000000 --- a/codeforce/#719/codeforce_719_3.py +++ /dev/null @@ -1,38 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - if n == 1: - print(1) - continue - elif n == 2: - print(-1) - continue - matrix = [[1] * n for _ in range(n)] - - k = 1 - for i in range(n): - for j in range(i, -1, -1): - matrix[i - j][j] = k - k += 2 - - k = 2 - if n&1: - for i in range(n // 2): - matrix[n//2 + 1 + i][n//2 - 1 - i] = k - k += 2 - else: - for i in range(n // 2): - matrix[n //2 + i][n//2 - 1 - i] = k - k += 2 - - - for i in range(1, n): - for j in range(n - 1, i - 1, -1): - matrix[n + i - j - 1][j] = k - k += 2 - for row in matrix: - print(*row) - - diff --git a/codeforce/#719/codeforce_719_4.py b/codeforce/#719/codeforce_719_4.py deleted file mode 100644 index a7e9aee..0000000 --- a/codeforce/#719/codeforce_719_4.py +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - new_arr = defaultdict(int) - for idx, num in enumerate(arr): - new_arr[num - idx] += 1 - answer = 0 - for num in new_arr: - k = new_arr[num] - answer += k * (k - 1) // 2 - print(answer) \ No newline at end of file diff --git a/codeforce/#719/codeforce_719_5.py b/codeforce/#719/codeforce_719_5.py deleted file mode 100644 index 4d6360a..0000000 --- a/codeforce/#719/codeforce_719_5.py +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - arr = list(input().rstrip()) + ['.'] - dp = [[0, 0] for _ in range(n + 1)] - last_sheep = -1 - cnt = 0 - for i in range(n + 1): - if arr[i] == '*': - last_sheep = i - cnt += 1 - else: - if last_sheep != -1: - dp[i][0] = cnt * (i - last_sheep) - last_sheep = -1 - cnt = 0 - for i in range(n, -1, -1): - if arr[i] == '*': - last_sheep = i - cnt += 1 - else: - if last_sheep != -1: - dp[i][1] = (last_sheep - i) * cnt - answer = 0 - min_value = float('inf') - for i in range(n + 1): - if dp[i][0] and dp[i][1]: - min_value = min(min_value, dp[i][0] + dp[i + 1][1], dp[i][1] + dp[i - 1][0]) - elif not dp[i][0] and not dp[i][1] and min_value != float('inf'): - answer += min_value - min_value = float('inf') - print(answer) - diff --git a/codeforce/#719/codeforce_719_6.py b/codeforce/#719/codeforce_719_6.py deleted file mode 100644 index 223fdaa..0000000 --- a/codeforce/#719/codeforce_719_6.py +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline - - - - -n, t = map(int, input().split()) -k = int(input()) - - - \ No newline at end of file diff --git a/codeforce/#725/codeforce_725_1.py b/codeforce/#725/codeforce_725_1.py deleted file mode 100644 index 390d5fb..0000000 --- a/codeforce/#725/codeforce_725_1.py +++ /dev/null @@ -1,37 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - min_p = float('inf') - max_p = 0 - min_idx = -1 - max_idx = -1 - for i in range(n): - if arr[i] > max_p: - max_p = arr[i] - max_idx = i - if arr[i] < min_p: - min_p = arr[i] - min_idx = i - answer = 0 - left = 0 - right = n - 1 - if max_idx < min_idx: - min_idx, max_idx = max_idx, min_idx - if min_idx + 1 <= right - max_idx + 1: - answer += min_idx + 1 - left = min_idx + 1 - if max_idx - left + 1 <= right - max_idx + 1: - answer += max_idx - left + 1 - else: - answer += right - max_idx + 1 - else: - answer += right - max_idx + 1 - right = max_idx - 1 - if min_idx - left + 1 <= right - min_idx + 1: - answer += min_idx - left + 1 - else: - answer += right - min_idx + 1 - print(answer) \ No newline at end of file diff --git a/codeforce/#725/codeforce_725_2.py b/codeforce/#725/codeforce_725_2.py deleted file mode 100644 index 6a3e8f2..0000000 --- a/codeforce/#725/codeforce_725_2.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - avg = sum(arr) / n - if avg > int(avg): - print(-1) - continue - avg = int(avg) - answer = 0 - for num in arr: - if num > avg: - answer += 1 - print(answer) \ No newline at end of file diff --git a/codeforce/#725/codeforce_725_3.py b/codeforce/#725/codeforce_725_3.py deleted file mode 100644 index 23bc423..0000000 --- a/codeforce/#725/codeforce_725_3.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left, bisect_right - -for test in range(int(input())): - n, l, r = map(int, input().split()) - arr = sorted(list(map(int, input().split()))) - answer = 0 - for i in range(n - 1): - if arr[i] + arr[n - 1] < l: - continue - # 범위를 만족하는 최소 j와 최대 j를 이분탐색으로 찾아야함. - left = max(i + 1, bisect_left(arr, l - arr[i])) - right = max(i + 1, bisect_right(arr, r - arr[i])) - answer += right - left - print(answer) \ No newline at end of file diff --git a/codeforce/#725/codeforce_725_4.py b/codeforce/#725/codeforce_725_4.py deleted file mode 100644 index 75f3e44..0000000 --- a/codeforce/#725/codeforce_725_4.py +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from math import gcd - -for test in range(int(input())): - a, b, k = map(int, input().split()) - if a > b: - a, b = b, a - if gcd(a, b) != a and k == 1: - print('NO') - continue - if a == b and k == 1: - print('NO') - continue - max_cnt = 0 - for i in range(2, b + 1): - while not a % i: - max_cnt += 1 - a //= i - while not b % i: - max_cnt += 1 - b //= i - if b == 1 and a == 1: - break - if k > max_cnt: - print('NO') - continue - print('YES') - - - - \ No newline at end of file diff --git a/codeforce/#725/codeforce_725_6.py b/codeforce/#725/codeforce_725_6.py deleted file mode 100644 index caf5c35..0000000 --- a/codeforce/#725/codeforce_725_6.py +++ /dev/null @@ -1,11 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - l, r = map(int, input().split()) - answer = 0 - while r or l: - answer += r - l - r //= 10 - l //= 10 - print(answer) \ No newline at end of file diff --git a/codeforce/#725/codeforce_725_7.py b/codeforce/#725/codeforce_725_7.py deleted file mode 100644 index 0dd02f9..0000000 --- a/codeforce/#725/codeforce_725_7.py +++ /dev/null @@ -1,18 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - red, blue, a, b = map(int, input().split()) - cnt = 0 - if a > b: - a, b = b, a - while red or blue: - if red > blue: - red, blue = blue, red - if red // a and blue // b: - cnt += min(red//a, blue//b) - red -= a * cnt - blue -= b * cnt - if red < a or blue < b: - break - print(cnt) \ No newline at end of file diff --git a/codeforce/#731/codeforce_731_1.py b/codeforce/#731/codeforce_731_1.py deleted file mode 100644 index ab92ed6..0000000 --- a/codeforce/#731/codeforce_731_1.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - input() - a_x, a_y = map(int, input().split()) - b_x, b_y = map(int, input().split()) - if a_x < b_x: - a_x, b_x = b_x, a_x - if a_y < b_y: - a_y, b_y = b_y, a_y - f_x, f_y = map(int, input().split()) - answer = a_x-b_x + a_y-b_y - if a_x == b_x == f_x and a_y > f_y > b_y: - answer += 2 - if a_y == b_y == f_y and a_x > f_x > b_x: - answer += 2 - print(answer) - \ No newline at end of file diff --git a/codeforce/#731/codeforce_731_2.py b/codeforce/#731/codeforce_731_2.py deleted file mode 100644 index 3a42bb2..0000000 --- a/codeforce/#731/codeforce_731_2.py +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - s = input().rstrip() - left = 0 - right = len(s) - 1 - start = len(s) - 1 + ord('a') - while left <= right: - flag = 0 - if s[right] == chr(start): - right -= 1 - start -= 1 - flag = 1 - elif s[left] == chr(start): - left += 1 - start -= 1 - flag = 1 - if not flag: - print('NO') - break - else: - print('YES') - diff --git a/codeforce/#731/codeforce_731_3.py b/codeforce/#731/codeforce_731_3.py deleted file mode 100644 index 95345be..0000000 --- a/codeforce/#731/codeforce_731_3.py +++ /dev/null @@ -1,44 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - input() - k, n, m = map(int, input().split()) - a = list(map(int, input().split())) - b = list(map(int, input().split())) - answer = [] - idx_a = 0 - idx_b = 0 - while idx_a < n and not a[idx_a]: - answer.append(0) - idx_a += 1 - k += 1 - while idx_b < m and not b[idx_b]: - answer.append(0) - idx_b += 1 - k += 1 - while idx_a != n or idx_b != m: - flag = 0 - if idx_a < n: - if a[idx_a] <= k: - answer.append(a[idx_a]) - idx_a += 1 - flag = 1 - while idx_a < n and not a[idx_a]: - answer.append(0) - idx_a += 1 - k += 1 - if idx_b < m: - if b[idx_b] <= k: - answer.append(b[idx_b]) - idx_b += 1 - flag = 1 - while idx_b < m and not b[idx_b]: - answer.append(0) - idx_b += 1 - k += 1 - if not flag: - answer = [-1] - break - - print(*answer) diff --git a/codeforce/#731/codeforce_731_4.py b/codeforce/#731/codeforce_731_4.py deleted file mode 100644 index c633197..0000000 --- a/codeforce/#731/codeforce_731_4.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - x = list(map(int, input().split())) - pivot = x[0] - y = [0] * n - for i in range(1, n): - l = len(bin(pivot)[2:]) - for j in range(l): - k = (1 << j) - if pivot & k and not x[i] & k: - y[i] += k - pivot = x[i] ^ y[i] - print(*y) \ No newline at end of file diff --git a/codeforce/#731/codeforce_731_5.py b/codeforce/#731/codeforce_731_5.py deleted file mode 100644 index b0d3d82..0000000 --- a/codeforce/#731/codeforce_731_5.py +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - input() - n, k = map(int, input().split()) - a = list(map(lambda x: int(x) - 1, input().split())) - t = list(map(int, input().split())) - answer = [float('inf')] * n - for i in range(k): - answer[a[i]] = t[i] - dp_right = [0] * n - dp_left = [0] * n - last = float('inf') - for i in range(n): - last = min(last + 1, answer[i]) - dp_right[i] = last - for i in range(n-1, -1, -1): - last = min(last + 1, answer[i]) - dp_left[i] = last - for i in range(n): - print(min(dp_left[i],dp_right[i]), end=' ') \ No newline at end of file diff --git a/codeforce/#731/codeforce_731_6.py b/codeforce/#731/codeforce_731_6.py deleted file mode 100644 index df9ccfd..0000000 --- a/codeforce/#731/codeforce_731_6.py +++ /dev/null @@ -1,24 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -for test in range(int(input())): - n = int(input()) - a = list(map(int, input().split())) - cnt = 0 - primes = defaultdict(int) - for i in range(n): - tmp = a[i] - for j in range(2, tmp + 1): - if tmp == 1: - break - if not tmp % j: - while not tmp % j: - tmp //= j - primes[j] += 1 - print(primes) - max_cnt = 0 - for prime in primes: - if not primes[prime] == n and max_cnt < primes[prime]: - max_cnt = primes[prime] - print(max_cnt) \ No newline at end of file diff --git a/codeforce/#731/codeforce_731_7.py b/codeforce/#731/codeforce_731_7.py deleted file mode 100644 index 43fafc1..0000000 --- a/codeforce/#731/codeforce_731_7.py +++ /dev/null @@ -1,41 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**5) - - -# 1부터 탐색. cycle생기면 cycle에 포함되는 요소 하나 check. -def dfs(cur_node, path): - if answer[cur_node] == 2: - return - answer[cur_node] += 1 - for next_node in graph[cur_node]: - if path & (1 << next_node): - cycle.append(next_node) - else: - dfs(next_node, path | (1 << next_node)) - - -# cycle요소로부터 갈 수 있는 모든 요소들 -1로 바꿈(infinite기 때문) -def dfs2(cur_node, path): - if answer[cur_node] == -1: - return - answer[cur_node] = -1 - for next_node in graph[cur_node]: - if not path & (1 << next_node): - dfs2(next_node, path | (1 << next_node)) - - -for test in range(int(input())): - input() - n, m = map(int, input().split()) - cycle = [] - graph = {i: [] for i in range(1, n + 1)} - answer = [0] * (n+1) - for _ in range(m): - a, b = map(int, input().split()) - graph[a] += [b] - # 못가면 0, 1, 2(경로 1개 초과), -1(경로 사이에 사이클 있으면) - dfs(1, 1) - for infinite in cycle: - dfs2(infinite, (1 << infinite)) - print(*answer[1:]) \ No newline at end of file diff --git a/codeforce/#734/codeforce_734_1.py b/codeforce/#734/codeforce_734_1.py deleted file mode 100644 index 9e6c60c..0000000 --- a/codeforce/#734/codeforce_734_1.py +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - # c1 + 2*c2 = n, abs(c1-c2)가 최소 - c1, c2 = n // 3, n // 3 - r = n % 3 - if r == 2: - c2 += 1 - elif r == 1: - c1 += 1 - print(c1, c2) diff --git a/codeforce/#734/codeforce_734_2.py b/codeforce/#734/codeforce_734_2.py deleted file mode 100644 index 68dcdd1..0000000 --- a/codeforce/#734/codeforce_734_2.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - s = input().rstrip() - char_set = {chr(i): 0 for i in range(97, 97+26)} - for char in s: - char_set[char] += 1 - flag = 0 - cnt = 0 - for char in char_set: - if char_set[char] >= 2: - cnt += 1 - elif char_set[char] == 1: - if flag: - cnt += 1 - flag = 0 - else: - flag = 1 - print(cnt) \ No newline at end of file diff --git a/codeforce/#734/codeforce_734_3.py b/codeforce/#734/codeforce_734_3.py deleted file mode 100644 index 6df5464..0000000 --- a/codeforce/#734/codeforce_734_3.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - -for test in range(int(input())): - n, k = map(int, input().split()) - arr = list(map(int, input().split())) - num_set = defaultdict(int) - for num in arr: - num_set[num] += 1 - check = {num: 1 for num in num_set} - answer = [0] * n - cnt = [[]] - for i in range(n): - if num_set[arr[i]] >= k: - if check[arr[i]] == k + 1: - continue - answer[i] = check[arr[i]] - check[arr[i]] += 1 - else: - for j in range(len(cnt)): - if arr[i] not in cnt[j]: - break - else: - cnt.append([i]) - continue - print(j) - cnt[j].append(i) - if len(cnt[j]) == k: - color = 1 - while cnt[j]: - answer[cnt[j].pop()] = color - color += 1 - print(*answer) \ No newline at end of file diff --git a/codeforce/#734/codeforce_734_4.py b/codeforce/#734/codeforce_734_4.py deleted file mode 100644 index 3c3a0d1..0000000 --- a/codeforce/#734/codeforce_734_4.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline -from itertools import combinations - - -def check(n): - for string_set in combinations(strings, n): - cnt = {chr(i): 0 for i in range(97,102)} - max_cnt = 0 - sum_count = 0 - for string in string_set: - sum_count += len(string) - for char in string: - cnt[char] += 1 - max_cnt = max(max_cnt, cnt[char]) - if max_cnt * 2 > sum_count: - return True - return False - - -for test in range(int(input())): - n = int(input()) - strings = [input().rstrip() for _ in range(n)] - left = 0 - right = n - answer = 0 - while left <= right: - mid = (left + right) // 2 - if check(mid): - left = mid + 1 - answer = mid - else: - right = mid - 1 - print(answer) diff --git a/codeforce/#734/codeforce_734_5.py b/codeforce/#734/codeforce_734_5.py deleted file mode 100644 index a53761c..0000000 --- a/codeforce/#734/codeforce_734_5.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n, m, k = map(int, input().split()) - if n&1 == k&1 and m>1: - if n&1 == 1 and n*m//2 - k <= n: - print('NO') - continue - print('YES') - continue - print('NO') - - - - diff --git a/codeforce/#739/codeforce_739_1.py b/codeforce/#739/codeforce_739_1.py deleted file mode 100644 index a362bd7..0000000 --- a/codeforce/#739/codeforce_739_1.py +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - - -ans = [0] -for i in range(1667): - if not i%3 or str(i)[-1]=='3': - continue - ans.append(i) - - -for _ in range(int(input())): - k = int(input()) - print(ans[k]) \ No newline at end of file diff --git a/codeforce/#739/codeforce_739_2.py b/codeforce/#739/codeforce_739_2.py deleted file mode 100644 index 30a9e26..0000000 --- a/codeforce/#739/codeforce_739_2.py +++ /dev/null @@ -1,15 +0,0 @@ - - - -for test in range(int(input())): - a, b, c = map(int, input().split()) - # a 건너편에 b 일때 c의 건너편은? - if a > b: - a, b = b, a - cnt = (b - a)*2 - # c가 범위 밖이거나 a, b가 규칙을 깨거나. - if c > cnt or b > cnt: - print(-1) - else: - print((c + cnt//2-1)%cnt+1) - \ No newline at end of file diff --git a/codeforce/#739/codeforce_739_3.py b/codeforce/#739/codeforce_739_3.py deleted file mode 100644 index 62b0f89..0000000 --- a/codeforce/#739/codeforce_739_3.py +++ /dev/null @@ -1,13 +0,0 @@ - - -for test in range(int(input())): - k = int(input()) - # k의 좌표? 제곱수 안쪽 - pivot = int(k**0.5) - # (0,pivot)부터 시작 (pivot,0까지) 총 2*pivot+1개. - if not k - pivot**2: - print(pivot,1) - elif k - pivot**2 <= pivot: - print(k - pivot**2, pivot+1) - else: - print(pivot+1, pivot - ((k - pivot**2)-(pivot+1))+1) \ No newline at end of file diff --git a/codeforce/#739/codeforce_739_4.py b/codeforce/#739/codeforce_739_4.py deleted file mode 100644 index c064895..0000000 --- a/codeforce/#739/codeforce_739_4.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = input().rstrip() - ln = len(n) - # 숫자의 임의의 숫자를 지운다. 오른족에 한자리를 더한다. 둘 중 하나의 작업 수행 가능. - # 두번째 숫자가 0이면 첫번째 자리 숫자 지울 수 없다. - # 2의 거듭제곱을 만들기 위한 최소한의 작업. - # 거듭제곱이 숫자 안에 있을 경우 = 그 제외한 것만 지워주면 됨. - # 거듭제곱과 편집거리를 계산. 변경의 cost가 2. 추가 1, 제거 1 - powers = [] - i = 1 - while i < int(1e18): - s2 = str(i) - powers.append(s2) - i *= 2 - min_change = float('inf') - for power in powers: - lp = len(power) - if lp - ln > min_change: - break - idx1 = 0 - idx2 = 0 - cnt = 0 - while idx1 < lp and idx2 < ln: - if n[idx2] == power[idx1]: - cnt += 1 - idx1 += 1 - idx2 += 1 - else: - idx2 += 1 - min_change = min(min_change,(ln + lp - 2*cnt)) - print(min_change) diff --git a/codeforce/#739/codeforce_739_5.py b/codeforce/#739/codeforce_739_5.py deleted file mode 100644 index 6610a27..0000000 --- a/codeforce/#739/codeforce_739_5.py +++ /dev/null @@ -1,15 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - t = input().rstrip() - re_t = t[::-1] - tmp = 'cab' - idx = 0 - check = 0 - while idx < len(t): - if re_t[idx] not in tmp: - tmp = re_t[idx] + tmp - check = idx - idx += 1 - print(re_t[check][::-1], tmp) \ No newline at end of file diff --git a/codeforce/#744/codeforce_744_1.py b/codeforce/#744/codeforce_744_1.py deleted file mode 100644 index a194e20..0000000 --- a/codeforce/#744/codeforce_744_1.py +++ /dev/null @@ -1,13 +0,0 @@ -import sys -input = sys.stdin.readline - -for t in range(int(input())): - s = input().rstrip() - if len(s)&1: - print('NO') - continue - count = 0 - for char in s: - if char =='B': - count += 1 - print('YES' if count == len(s)//2 else 'NO') diff --git a/codeforce/#744/codeforce_744_2.py b/codeforce/#744/codeforce_744_2.py deleted file mode 100644 index c9aff6b..0000000 --- a/codeforce/#744/codeforce_744_2.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys -input = sys.stdin.readline - -for t in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - # print shifting count - # print each l, r, d in a line - # find 1 -> n - cnt = 0 - commands = [] - for left in range(n): - target = min(arr[left:]) - for right in range(left, n): - if arr[right] == target: - break - if not left == right: - cnt += 1 - arr = arr[:left] + arr[right:] + arr[left: right] - commands.append([left+1, right+1, right - left]) - print(cnt) - for command in commands: - print(*command) \ No newline at end of file diff --git a/codeforce/#744/codeforce_744_3.py b/codeforce/#744/codeforce_744_3.py deleted file mode 100644 index 6751d1a..0000000 --- a/codeforce/#744/codeforce_744_3.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -input = sys.stdin.readline - -for t in range(int(input())): - n, m, k = map(int, input().split()) - matrix = [input().rstrip() for _ in range(n)] - answer = 'YES' - for row in range(n - 1, -1, -1): - if answer =='NO': break - for col in range(m): - if matrix[row][col] == '*': - d = 0 - top = row - 1 - left = col - 1 - right = col + 1 - while 0 <= top and right < m and left >= 0: - if matrix[top][left] == '*' and matrix[top][right] == '*': - d += 1 - else: - break - top -= 1 - left -= 1 - right += 1 - if d < k: - if row != n - 1: - if col != 0: - if matrix[row + 1][col - 1] == '*': - continue - if col != m - 1: - if matrix[row + 1][col + 1] == '*': - continue - answer = 'NO' - break - print(answer) diff --git a/codeforce/#744/codeforce_744_4.py b/codeforce/#744/codeforce_744_4.py deleted file mode 100644 index 31fea43..0000000 --- a/codeforce/#744/codeforce_744_4.py +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop, heappush - -for t in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - check = {i: False for i in range(1, n + 1)} - min_heap = [] - max_heap = [] - for i in range(n): - if arr[i] == 0: - continue - heappush(min_heap, [arr[i], i + 1]) - heappush(max_heap, [-arr[i], i + 1]) - answer = 0 - answer_set = [] - while min_heap and max_heap and min_heap[0][1] != max_heap[0][1] and not check[max_heap[0][1]]: - min_cnt, min_idx = heappop(min_heap) - max_cnt, max_idx = heappop(max_heap) - while min_cnt > 0 and max_cnt <= max_heap[0][0]: - min_cnt -= 1 - max_cnt += 1 - answer += 1 - answer_set.append([min_idx, max_idx]) - - if max_cnt: - heappush(max_heap, [max_cnt, max_idx]) - check[min_idx] = True - print(answer) - for ans in answer_set: - print(*ans) diff --git "a/codeforce/#760/A_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#760/A_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index ec280de..0000000 --- "a/codeforce/#760/A_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,10 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - arr = list(map(int, input().split())) - answer = [] - for i in range(2, 4): - answer.append(arr[-1] - arr[-i]) - answer.append(arr[-1] - sum(answer)) - print(*answer) \ No newline at end of file diff --git "a/codeforce/#760/B_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#760/B_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index d2e11bf..0000000 --- "a/codeforce/#760/B_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,19 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - arr = list(input().split()) - answer = '' - answer += arr[0] - flag = 0 - for i in range(1, n - 2): - if answer[-1] != arr[i][0]: - answer += arr[i] - flag = 1 - else: - answer += arr[i][1] - if flag: - print(answer) - else: - print(answer + 'b') diff --git "a/codeforce/#760/C_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#760/C_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 146ef78..0000000 --- "a/codeforce/#760/C_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,38 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - answer = 0 - even = float('inf') - odd = float('inf') - for idx, num in enumerate(arr): - if idx & 1: - odd = min(odd, num) - else: - even = min(even, num) - for idx, num in enumerate(arr): - if idx & 1: - if not num % even: - break - else: - if num % even: - break - else: - answer = even - - if answer: - print(answer) - continue - - for idx, num in enumerate(arr): - if idx & 1: - if num % odd: - break - else: - if not num % odd: - break - else: - answer = odd - print(answer) \ No newline at end of file diff --git "a/codeforce/#760/D_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#760/D_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index bdcd33e..0000000 --- "a/codeforce/#760/D_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,6 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(int(input())): - n, k = map(int, input().split()) - arr = list(map(int, input().split())) diff --git "a/codeforce/#760/E_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#760/E_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index ba273e7..0000000 --- "a/codeforce/#760/E_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,25 +0,0 @@ -import sys -input = sys.stdin.readline -from heapq import heappop, heappush - - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - heap = [] - for idx, num in enumerate(arr): - heappush(heap, (num, idx)) - total, answer = 0, [] - while heap: - num, idx = heappop(heap) - if total >= num: - answer.append(idx + 1) - else: - answer = [idx + 1] - total += num - answer.sort() - print(len(answer)) - print(*answer) - - diff --git "a/codeforce/#760/F_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#760/F_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 76a9e8c..0000000 --- "a/codeforce/#760/F_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,28 +0,0 @@ -import sys -input = sys.stdin.readline -from collections import defaultdict - - -for test in range(int(input())): - n = int(input()) - arr = list(map(int, input().split())) - counter = defaultdict(int) - for num in arr: - counter[num] += 1 - candidate = set() - for target in counter.values(): - candidate.add(target) - answer = float('inf') - for target in candidate: - total = 0 - for cnt in counter.values(): - if cnt == target: - continue - if target > cnt: - total += cnt - else: - total += cnt - target - if total >= answer: - break - answer = min(answer, total) - print(answer) \ No newline at end of file diff --git "a/codeforce/#760/G_\355\225\234\354\212\271\354\243\274.py" "b/codeforce/#760/G_\355\225\234\354\212\271\354\243\274.py" deleted file mode 100644 index 2ca4fe3..0000000 --- "a/codeforce/#760/G_\355\225\234\354\212\271\354\243\274.py" +++ /dev/null @@ -1,32 +0,0 @@ -import sys -input = sys.stdin.readline -from bisect import bisect_left - -# 풀이 참고했는데 -for test in range(int(input())): - n, m = map(int, input().split()) - arr = list(map(int, input().split())) - prefix_sum, idxes, idx, total = [], [], 0, 0 - for num in arr: - total += num - if not prefix_sum or prefix_sum[-1] < total: - prefix_sum.append(total) - idxes.append(idx) - idx += 1 - x = list(map(int, input().split())) - answer = [] - for target in x: - # 총합이 더해질 수 없고 양의 총합보다 목표치가 높으면 도달할 수 없음 - if prefix_sum[-1] < target and total <= 0: - answer.append(-1) - continue - # 이부분이 이해가 잘 안감. - # 바퀴수 = (목표치 - 양의 최대치 + 총합 - 1) // 총합 ? - # 양의 최대치에서 목표치를 초과할 가능성에 대해 보정해주는건가? - cycle = 0 - if prefix_sum[-1] < target: - cycle = (target - prefix_sum[-1] + total - 1) // total - target -= cycle * total - # 바퀴수 * 크기 + 나머지의 누적합에서의 위치 - answer.append(cycle * n + idxes[bisect_left(prefix_sum, target)]) - print(*answer) \ No newline at end of file diff --git a/codeforce/main.py b/codeforce/main.py deleted file mode 100644 index 00bfc45..0000000 --- a/codeforce/main.py +++ /dev/null @@ -1,22 +0,0 @@ -import sys -input = sys.stdin.readline - -for test in range(1, int(input()) + 1): - N, B, S, P, D = map(int, input().split()) - # B는 기준 0글번호, 1글제목, 2 조회수 - # D가 0이면 오름차순, 1이면 내림차순 - table = [input().rstrip()[1:-1].split(', ') for _ in range(N)] - if B == 0: - table.sort() - elif B == 1: - table.sort(key=lambda x: (x[1], int(x[0]))) - else: - table.sort(key=lambda x: (int(x[2]), int(x[0]))) - - if D == 1: - table = table[::-1] - table = table[S * P - P: P * S] - print(f'#{test}', end=' ') - for i in range(S): - print(table[i][0], end=' ') - print() \ No newline at end of file diff --git a/color_fulling.py b/color_fulling.py index 96a4e72..d6173e5 100644 --- a/color_fulling.py +++ b/color_fulling.py @@ -1,22 +1,22 @@ -""" -N킬로그램 배달해야됨. -봉지는 3,5킬로 단위. -가장 적은 봉지 -""" - -N = int(input()) - -cnt =0 - -while N>0: - if N%5==0: - cnt += N//5 - break - else: - N = N-3 - cnt +=1 - -if N<0: - print(-1) - +""" +N킬로그램 배달해야됨. +봉지는 3,5킬로 단위. +가장 적은 봉지 +""" + +N = int(input()) + +cnt =0 + +while N>0: + if N%5==0: + cnt += N//5 + break + else: + N = N-3 + cnt +=1 + +if N<0: + print(-1) + print(cnt) \ No newline at end of file diff --git a/color_mine.py b/color_mine.py index b1289ba..f56710a 100644 --- a/color_mine.py +++ b/color_mine.py @@ -1,22 +1,22 @@ -T = int(input()) - - -def coloringGraph(): - N,E,M = map(int,input().split()) - - G =[[0 for _ in range(N)]for _ in range(N)] - - for _ in range(E): - x,y = map(int,input().split()) - G[x-1][y-1] = 1 - G[y-1][x-1] = 1 - - for i in range(N): - if sum(G[i]) > M: - return 0 - - return 1 - - -for testcase in range(T): - print("#{} {}".format(testcase+1, coloringGraph())) +T = int(input()) + + +def coloringGraph(): + N,E,M = map(int,input().split()) + + G =[[0 for _ in range(N)]for _ in range(N)] + + for _ in range(E): + x,y = map(int,input().split()) + G[x-1][y-1] = 1 + G[y-1][x-1] = 1 + + for i in range(N): + if sum(G[i]) > M: + return 0 + + return 1 + + +for testcase in range(T): + print("#{} {}".format(testcase+1, coloringGraph())) diff --git a/common_list_number.py b/common_list_number.py index 71eccf3..aa0cb88 100644 --- a/common_list_number.py +++ b/common_list_number.py @@ -1,12 +1,22 @@ -#coding: utf-8 - -#성적 총점 평점. -list1 = [1,3, 6, 78, 35, 55] -list2 = [12,24,35,24,88,120,155] - -#교집합 찾기.= 합집합- 반달1-반달2 -#1:1대응 -def intersect(x,y): - return(set(x)&set(y)) - -print("두 배열의 공통된부분은?:{0}".format(intersect(list1,list2))) \ No newline at end of file +#coding: utf-8 + +#학생별, 과목별 총점 및 평균 구하기 + +scores = [] + +count = int(input("총 학생의 수를 입력하세요:")) + +for i in range(1, count+1): + score = {} + score["name"] = input("학생의 이름을 입력하세요:") + score["kor"] = int(input("{0} 학생의 국어 점수플 입력하세요:".format(score["name"]))) + score["mat"] = int(input("{0} 학생의 수학 점수플 입력하세요:".format(score["name"]))) + score["eng"] = int(input("{0} 학생의 수학 점수플 입력하세요:".format(score["name"]))) + scores.append(score) + +for score in scores: + total = 0 + for key in score: + if key != "name": + total += score[key] + print("{0}학생 => 총점:{1}, 평균 : {2:0.2F}".format(score["name"],total,total/3)) \ No newline at end of file diff --git a/cruise_control.py b/cruise_control.py deleted file mode 100644 index 1c91530..0000000 --- a/cruise_control.py +++ /dev/null @@ -1,28 +0,0 @@ -#검사해서 좌우 두칸에 나보다 작은 숫자만 있으면 됨. - - -TC = int(input()) - - -def speed(): - D, N = list(map(int,input().split())) - if N ==1: - K, S = list(map(int,input().split())) - v = (D*S)/(D-K) - else: - KL = [] - SL = [] - for i in range(N): - K, S = list(map(int,input().split())) - KL.append(K) - SL.append(S) - if (((D-KL[0])/SL[0]) >=((D-KL[1])/SL[1])): - v = (D*SL[0])/(D-KL[0]) - else: - v = (D*SL[1])/(D-KL[1]) - return v - - - -for j in range(TC): - print("#{0} {1}".format(j+1,speed())) \ No newline at end of file diff --git a/dddd.py b/dddd.py deleted file mode 100644 index 9d65051..0000000 --- a/dddd.py +++ /dev/null @@ -1,42 +0,0 @@ -import sys -sys.stdin = open('input.txt') - - -# 열 인덱스로 순열을 만들면 세로로 같은 줄에서 두 개 이상의 숫자를 고를 수 없다는 조건을 만족할 수 있다. -# swea 제한시간 초과 남 -# 백트래킹 조건을 추가 - 합이 최소값을 넘으면 더이상 찾지 않도록 설정 - -def get_per_sum(i, sum_nums): - global min_sum - - - - - # 백트래킹 조건: 현재 합이 최소합을 넘으면 -> 볼 필요 없음. - if sum_nums > min_sum: - return - - if i == n: # 순열 완성 P = [1, 0, 2] - - # sums.append(sum) - min_sum = min(sum_nums, min_sum) - return - - else: - for j in range(i, n): # 자신부터 오른쪽 원소와 교환 - P[i], P[j] = P[j], P[i] - get_per_sum(i + 1, sum_nums + arr[i][P[i]]) - P[i], P[j] = P[j], P[i] - - -T = int(input()) -for tc in range(1, T + 1): - n = int(input()) - arr = [list(map(int, input().split())) for _ in range(n)] - - P = [i for i in range(n)] # 열 인덱스 순열을 만들 리스트 P = [0, 1, 2] - # sums = [] # 합을 모을 리스트 - min_sum = float('inf') # 무한대 - get_per_sum(0, 0) - - print(f'#{tc} {min_sum}') \ No newline at end of file diff --git a/double_linkedList.py b/double_linkedList.py index 4f1b0a1..ea8db2c 100644 --- a/double_linkedList.py +++ b/double_linkedList.py @@ -1,13 +1,13 @@ -class HashTable: - def __init__(self): - self.hash_table = list([0 for i in range(8)]) - def hash_function(self, key): - return key % 8 - def insert(self, key, value): - hash_value = self.hash_function(hash(key)) - self.hash_table[hash_value] = value - def read(self, key): - hash_value = self.hash_function(hash(key)) - return self.hash_table[hash_value] - def print(self): print(self.hash_table) - +class HashTable: + def __init__(self): + self.hash_table = list([0 for i in range(8)]) + def hash_function(self, key): + return key % 8 + def insert(self, key, value): + hash_value = self.hash_function(hash(key)) + self.hash_table[hash_value] = value + def read(self, key): + hash_value = self.hash_function(hash(key)) + return self.hash_table[hash_value] + def print(self): print(self.hash_table) + diff --git a/enjoy_holiday.py b/enjoy_holiday.py deleted file mode 100644 index b0ff23b..0000000 --- a/enjoy_holiday.py +++ /dev/null @@ -1,23 +0,0 @@ -import heapq - - -N = int(input()) -cards =[] -times = 0 - -for _ in range(N): - heapq.heappush(cards,int(input()) - - -if(N==1) - print(0) - else: - while len(cards) > 1: - card1 = heapq.heappop(cards) - card2 = heapq.heappop(cards) - times += card1 + card2 - heapq.heappush(cards,card1+card2) - - -print(times) - diff --git a/find median.py b/find median.py deleted file mode 100644 index 81dde50..0000000 --- a/find median.py +++ /dev/null @@ -1,12 +0,0 @@ - -T = int(input()) -for test_case in range(1,T+1): - N = int(input()) - points = list(map(int,input().split())) - for i in range(N): - for x in points: - points.append(x + points[i]) - - grades = set(points) - answer = len(grades) - print("#{} {}".format(test_case, answer)) \ No newline at end of file diff --git a/find_Mode.py b/find_Mode.py deleted file mode 100644 index 780e840..0000000 --- a/find_Mode.py +++ /dev/null @@ -1,8 +0,0 @@ -#첫줄 N개 출력, n열에 아래로 내려가면서 n-1개 -#n행에 뒤부터 - - -N = int(input()) -matrix = [[0 for _ in range(N)] for _ in range(N)] - -print(matrix) \ No newline at end of file diff --git a/find_long_path.py b/find_long_path.py deleted file mode 100644 index 0e70042..0000000 --- a/find_long_path.py +++ /dev/null @@ -1,31 +0,0 @@ - -def findPath_dfs(v, visted): - global visited - visited.append(v) - for adj in graph[v]: - if not adj in visited: - visited = findPath_dfs(adj,visited) - return visited - - - -for test in range(1,int(input())+1): - graph = {} - N,M = map(int,input().split()) - max_path = 1 - visited = [] - for _ in range(M): - x,y = map(int,input().split()) - graph[x] = graph.get(x,[]) + [y]#딕셔너리에 x키가 있으면 x키의 값을 반환하고 - graph[y] = graph.get(y,[]) + [x]#없으면 디폴트값[]를 내놓는다 +[y] - #리스트 합을 통해 graph[x]에 재저장. - for i in range(1,N+1): - if M==0: - break - else: - findPath_dfs(i,visited) - if max_path < len(visited): - max_path = len(visited) - - print(f"#{test} {max_path}") - \ No newline at end of file diff --git a/find_str_replace_practice.py b/find_str_replace_practice.py index 87b5b9c..a43696d 100644 --- a/find_str_replace_practice.py +++ b/find_str_replace_practice.py @@ -1,19 +1,19 @@ -#coding: utf-8 - -#문자열 찾기 및 조작 - -data_str = "파이썬은 클래스를 이용해 객체를 생성하는 객체지향 프로그래밍 언어입니다." -mask_str = input("마스킹할 문자열을 입력하세요:") -find_str = input("찾을 문자열을 입력하세요:") -idx = -1 -count = 1 -while True: - idx = data_str.find(find_str,idx+1) - if idx != -1: - print("[{0}]~[{1}]".format(idx,idx+len(find_str)-1)) - new_str = data_str.replace(find_str,mask_str,count) - print(new_str) - count += 1 - else: - break +#coding: utf-8 + +#문자열 찾기 및 조작 + +data_str = "파이썬은 클래스를 이용해 객체를 생성하는 객체지향 프로그래밍 언어입니다." +mask_str = input("마스킹할 문자열을 입력하세요:") +find_str = input("찾을 문자열을 입력하세요:") +idx = -1 +count = 1 +while True: + idx = data_str.find(find_str,idx+1) + if idx != -1: + print("[{0}]~[{1}]".format(idx,idx+len(find_str)-1)) + new_str = data_str.replace(find_str,mask_str,count) + print(new_str) + count += 1 + else: + break print(idx) \ No newline at end of file diff --git a/gomgom3.py b/gomgom3.py deleted file mode 100644 index a647fd7..0000000 --- a/gomgom3.py +++ /dev/null @@ -1,12 +0,0 @@ -import sys -input = sys.stdin.readline -from math import ceil - -N = int(input()) -S = input().rstrip() -cnt = 0 -for char in S: - if char != "C": - cnt += 1 -answer = ceil((N - cnt) / (cnt + 1)) -print(answer) \ No newline at end of file diff --git a/gomgom4.py b/gomgom4.py deleted file mode 100644 index a438901..0000000 --- a/gomgom4.py +++ /dev/null @@ -1,16 +0,0 @@ -import sys -input = sys.stdin.readline - - -N = int(input()) -A = list(map(int, input().split())) -s = set() -for num in A: - for num2 in set(s): - tmp = (num + num2) % 7 - s.add(tmp) - s.add(num % 7) - if 4 in s: - print("YES") - exit() -print("NO") \ No newline at end of file diff --git a/gomgom5.py b/gomgom5.py deleted file mode 100644 index 9f0688d..0000000 --- a/gomgom5.py +++ /dev/null @@ -1,27 +0,0 @@ -import sys -input = sys.stdin.readline -sys.setrecursionlimit(10**6) -from collections import defaultdict - - -def dfs(cur_node): - if not graph[cur_node]: - return True - for next_node in graph[cur_node]: - if next_node in gomgom: - continue - if dfs(next_node): - return True - - -N, M = map(int, input().split()) -graph = defaultdict(set) -for _ in range(M): - u, v = map(int, input().split()) - graph[u].add(v) -S = int(input()) -gomgom = set(map(int, input().split())) -if 1 in gomgom: - print("Yes") -else: - print("yes" if dfs(1) else "Yes") \ No newline at end of file diff --git a/grep_1 b/grep_1 deleted file mode 100644 index 40bf0c9..0000000 --- a/grep_1 +++ /dev/null @@ -1,8 +0,0 @@ -def solution(n, text, second): - text = text.replace(" ", "_") - second %= n + len(text) - answer = "_" * n + text - return (answer[second:second + n] + answer[:second])[:n] - - -print(solution(4, "hi bye", 7)) diff --git a/grep_2 b/grep_2 deleted file mode 100644 index 7963557..0000000 --- a/grep_2 +++ /dev/null @@ -1,30 +0,0 @@ -def solution(bricks, n, k): - global answer - answer = float('inf') - # 조합, 좌우를 벽으로 쳤을 때 각 벽과 붙지 않는 것들만 채택. - # 물웅덩이 k 개면 총 k - 1개의 벽이 필요 - walls = [] - check = [False] * len(bricks) - check[0], check[len(bricks) - 1] = True, True - for idx, brick in enumerate(bricks): - if brick >= n: - check[idx] = True - walls.append(idx) - # 조합으로 k - 1 - wall_cnt만큼의 벽을 생성. - def dfs(now, walls, cnt): - global answer - if len(walls) == k - 1: - answer = min(answer, cnt) - return - for i in range(now, len(bricks) - 1): - if not check[i]: - s = [] - for m in range(i - 1, i + 2): - if not check[m]: - check[m] = True - s.append(m) - dfs(i, walls + [i], cnt + (n - bricks[i])) - for m in s: - check[m] = False - dfs(1, walls, 0) - return answer \ No newline at end of file diff --git a/grep_3 b/grep_3 deleted file mode 100644 index 6aee262..0000000 --- a/grep_3 +++ /dev/null @@ -1,27 +0,0 @@ -def solution(replies, n, k): - answer = [] - for reply in replies: - length = len(reply) - # 길이 n 을 k개 - if length < n * k: - answer.append(1) - continue - flag = 0 - # 패턴의 길이가 n이상이기 때문에 길이 n_length는 n에서 length - n은 k가 2회이상인가? - for n_length in range(n, length - n): - if flag: break - # 시작지점부터 패턴이 k개 이어지는지 확인하는 코드 - for idx in range(length - n_length * k + 1): - # tmp는 - tmp = reply[idx:idx+n_length] - if flag : break - for m in range(1, k): - if tmp != reply[idx+n_length*m:idx+(m+1)*n_length]: - break - else: - answer.append(0) - flag = 1 - break - else: - answer.append(1) - return answer \ No newline at end of file diff --git a/grep_4 b/grep_4 deleted file mode 100644 index ca55bed..0000000 --- a/grep_4 +++ /dev/null @@ -1,52 +0,0 @@ -def solution(n, rooks): - global answer - answer = 0 - board = [] - for i in range(n): - board.append([0] * (2 * i + 1)) - - def is_check(x, y): - if y & 1: - for row in range(x): - if 2 * row >= y and board[row][y]: - return False - if 2 * row >= y - 1 and board[row][y - 1]: - return False - tmp = 2 * (x - row) - if y >= tmp and board[row][y - tmp]: - return False - if y >= tmp - 1 and board[row][y - tmp + 1]: - return False - return True - else: - for row in range(x): - if 2 * row >= y and board[row][y]: - return False - if 2 * row >= y + 1 and board[row][y + 1]: - return False - tmp = 2 * (x - row) - if y >= tmp and board[row][y - tmp]: - return False - if y >= tmp + 1 and board[row][y - tmp - 1]: - return False - return True - - def dfs(row, cnt): - global answer - if cnt == rooks: - answer += 1 - return - if row == n: - return - - for col in range(len(board[row])): - if is_check(row, col): - board[row][col] = 1 - dfs(row + 1, cnt + 1) - board[row][col] = 0 - dfs(row + 1, cnt) - - dfs(0, 0) - return answer - -print(solution(5, 3)) diff --git a/hashtable.py b/hashtable.py deleted file mode 100644 index e8ad14b..0000000 --- a/hashtable.py +++ /dev/null @@ -1,15 +0,0 @@ -class HashTable: - def __init__(self): - self.hash_table = list([0 for i in range(8)]) - def hash_function(self, key): - return key % 8 - def insert(self, key, value): - hash_value = self.hash_function(hash(key)) - self.hash_table[hash_value] = value - def read(self, key): - hash_value = self.hash_function(hash(key)) - return self.hash_table[hash_value] - def print(self): print(self.hash_table) - - -# 출처: https://davinci-ai.tistory.com/19 [DAVINCI - AI] diff --git a/hashtable2..py b/hashtable2..py index 91ba31f..1e4a58b 100644 --- a/hashtable2..py +++ b/hashtable2..py @@ -1,24 +1,24 @@ -# 순열 - -def permute(arr): - result = [arr[:]] - c = [0] * len(arr) - i = 0 - while i < len(arr): - if c[i] < i: - if i % 2 == 0: - arr[0], arr[i] = arr[i], arr[0] - else: - arr[c[i]], arr[i] = arr[i], arr[c[i]] - - result.append(arr[:]) - c[i] += 1 - i = 0 - else: - c[i] = 0 - i += 1 - return result - - -def perm(lis, n): result = [] if n > len(lis): return result if n == 1: for li in lis: result.append([li]) elif n > 1: for i in range(len(lis)): tmp = [i for i in lis] tmp.remove(lis[i]) for j in perm(tmp, n-1): result.append([lis[i]]+j) return result n = int(input()) lis = list(i for i in range(1, n+1)) for li in perm(lis,n): print(' '.join(list(map(str, li)))) - +# 순열 + +def permute(arr): + result = [arr[:]] + c = [0] * len(arr) + i = 0 + while i < len(arr): + if c[i] < i: + if i % 2 == 0: + arr[0], arr[i] = arr[i], arr[0] + else: + arr[c[i]], arr[i] = arr[i], arr[c[i]] + + result.append(arr[:]) + c[i] += 1 + i = 0 + else: + c[i] = 0 + i += 1 + return result + + +def perm(lis, n): result = [] if n > len(lis): return result if n == 1: for li in lis: result.append([li]) elif n > 1: for i in range(len(lis)): tmp = [i for i in lis] tmp.remove(lis[i]) for j in perm(tmp, n-1): result.append([lis[i]]+j) return result n = int(input()) lis = list(i for i in range(1, n+1)) for li in perm(lis,n): print(' '.join(list(map(str, li)))) + diff --git a/heap.py b/heap.py deleted file mode 100644 index fb27643..0000000 --- a/heap.py +++ /dev/null @@ -1,65 +0,0 @@ -class Heap: - def __init__(self): - self.array = [] - - def __str__(self): - return str(self.array) - - def insertElement(self, data): - self.array.append(data) - length = len(self.array) - if length > 1: - node_num = length - 1 - while True: - next_node_num = int(node_num/2) - if self.array[next_node_num] < self.array[node_num]: - temp = self.array[node_num] - self.array[node_num] = self.array[next_node_num] - self.array[next_node_num] = temp - else: - break - node_num = int(node_num/2) - if node_num == 0: - break - - def deleteRoot(self): - root_value = self.array[0] - del self.array[0] - - last_index = len(self.array) - 1 - if last_index < 0: - return root_value - tail_value = self.array[last_index] - del self.array[last_index] - - self.array.insert(0, tail_value) - now_index = 0 - next_index = 0 - while True: - now_index = next_index - next_index *= 2 - if next_index + 2 > last_index: - break - if self.array[next_index + 1] > self.array[next_index + 2]: - next_index += 1 - else: - next_index += 2 - if self.array[now_index] < self.array[next_index]: - temp = self.array[now_index] - self.array[now_index] = self.array[next_index] - self.array[next_index] = temp - return root_value - -if __name__ == '__main__': - m_heap = Heap() - m_heap.insertElement(2) - m_heap.insertElement(4) - m_heap.insertElement(5) - m_heap.insertElement(8) - m_heap.insertElement(2) - m_heap.insertElement(3) - print('Heap :', m_heap) - print('Delete Root :', m_heap.deleteRoot()) - print('Delete Root :', m_heap.deleteRoot()) - print('Delete Root :', m_heap.deleteRoot()) - print('Heap :', m_heap) \ No newline at end of file diff --git a/honeybee_already.py b/honeybee_already.py deleted file mode 100644 index a540cee..0000000 --- a/honeybee_already.py +++ /dev/null @@ -1,36 +0,0 @@ - -def sumCheck(): - if sum(queue)<=C: - a = map(lambda x : x**2,queue) - answers.append(sum(a)) - else: - sorted_queue = sorted(queue) - check[0]*M - - - - - return answers - - - - - -for test_case in range(1,int(input())+1): - N,M,C = map(int,input().split()) - honey = [] - sum = 0 - queue = [] - answers = [] - for _ in range(N): - row = list(map(int, input().split())) - honey.append(row) - for i in range(N): - for j in range(N-M+1): - queue.append(honey[i][j]) - if len(queue) > M: - queue.pop(0) - if len(queue) ==M: - sumCheck() - - print("#{} {}".format(test_case,max(answers))) diff --git "a/import heapq # \354\232\260\354\204\240\354\210\234\354\234\204 \355\201\220 \352\265\254\355\230\204\354\235\204 \354\234\204\355\225\250.py" "b/import heapq # \354\232\260\354\204\240\354\210\234\354\234\204 \355\201\220 \352\265\254\355\230\204\354\235\204 \354\234\204\355\225\250.py" deleted file mode 100644 index 7f12cb2..0000000 --- "a/import heapq # \354\232\260\354\204\240\354\210\234\354\234\204 \355\201\220 \352\265\254\355\230\204\354\235\204 \354\234\204\355\225\250.py" +++ /dev/null @@ -1,31 +0,0 @@ -import heapq # 우선순위 큐 구현을 위함 - -def dijkstra(graph, start): - distances = {node: float('inf') for node in graph} # start로 부터의 거리 값을 저장하기 위함 - distances[start] = 0 # 시작 값은 0이어야 함 - queue = [] - heapq.heappush(queue, [distances[start], start]) # 시작 노드부터 탐색 시작 하기 위함. - - while queue: # queue에 남아 있는 노드가 없으면 끝 - current_distance, current_destination = heapq.heappop(queue) # 탐색 할 노드, 거리를 가져옴. - - if distances[current_destination] < current_distance: # 기존에 있는 거리보다 길다면, 볼 필요도 없음 - continue - - for new_destination, new_distance in graph[current_destination].items(): - distance = current_distance + new_distance # 해당 노드를 거쳐 갈 때 거리 - if distance < distances[new_destination]: # 알고 있는 거리 보다 작으면 갱신 - distances[new_destination] = distance - heapq.heappush(queue, [distance, new_destination]) # 다음 인접 거리를 계산 하기 위해 큐에 삽입 - - return distances - - - graph = { - 'A': {'B': 8, 'C': 1, 'D': 2}, - 'B': {}, - 'C': {'B': 5, 'D': 2}, - 'D': {'E': 3, 'F': 5}, - 'E': {'F': 1}, - 'F': {'A': 5} -} \ No newline at end of file diff --git a/infinity_dic.py b/infinity_dic.py index 6d315c1..3f4119d 100644 --- a/infinity_dic.py +++ b/infinity_dic.py @@ -1,25 +1,25 @@ -T = int(input()) - - - -for test_case in range(1, T + 1): - P = list(input()) - Q = list(input()) - - for i in range(len(P)): - if len(Q) == len(P)+1 and Q[-1] == "a": - if P[i] == Q[i]: - answer = 1 - continue - else: - answer = 0 - else: - answer = 0 - break - if answer == 1: - print("#{} N".format(test_case)) - else: - print("#{} Y".format(test_case)) - - +T = int(input()) + + + +for test_case in range(1, T + 1): + P = list(input()) + Q = list(input()) + + for i in range(len(P)): + if len(Q) == len(P)+1 and Q[-1] == "a": + if P[i] == Q[i]: + answer = 1 + continue + else: + answer = 0 + else: + answer = 0 + break + if answer == 1: + print("#{} N".format(test_case)) + else: + print("#{} Y".format(test_case)) + + \ No newline at end of file diff --git a/infinity_dic_pass.py b/infinity_dic_pass.py index 8043f37..31c6eff 100644 --- a/infinity_dic_pass.py +++ b/infinity_dic_pass.py @@ -1,22 +1,22 @@ -N = int(input()) - - -for i in range(1,N+1): - cnt = 0 - number = i - if i>100: - if i//100 ==3 or i//100 ==6 or i//100 ==9: - cnt +=1 - i = i - i//100 *100 - if i>10: - if i//10 ==3 or i//10 ==6 or i//10 ==9: - cnt +=1 - i = i - i//10 *10 - if i == 3 or i ==6 or i ==9: - cnt +=1 - if cnt !=0: - for _ in range(cnt): - print("-", end ="") - print(end = " ") - else: +N = int(input()) + + +for i in range(1,N+1): + cnt = 0 + number = i + if i>100: + if i//100 ==3 or i//100 ==6 or i//100 ==9: + cnt +=1 + i = i - i//100 *100 + if i>10: + if i//10 ==3 or i//10 ==6 or i//10 ==9: + cnt +=1 + i = i - i//10 *10 + if i == 3 or i ==6 or i ==9: + cnt +=1 + if cnt !=0: + for _ in range(cnt): + print("-", end ="") + print(end = " ") + else: print(number, end=" ") \ No newline at end of file diff --git a/ischeckdate.py b/ischeckdate.py deleted file mode 100644 index 98d69aa..0000000 --- a/ischeckdate.py +++ /dev/null @@ -1,22 +0,0 @@ -T = int(input()) - - - -for testcase in range(T): - date = input() - year = date[:4] - month = date[4:6] - day = date[6:] - iyear = int(year) - imonth = int(month) - iday = int(day) - if (imonth == 1 or imonth == 3 or imonth == 5 or imonth == 7 or imonth == 8 or imonth == 10 or imonth == 12) and imonth !=0 and 0 < iday <= 31: - print("#{} {}/{}/{}".format(testcase+1, year, month, day)) - elif imonth == 2 and imonth !=0 and 0 < iday <= 28: - print("#{} {}/{}/{}".format(testcase+1, year, month, day)) - elif (imonth == 4 or imonth == 6 or imonth == 9 or imonth == 11) and imonth !=0 and 0 < iday <= 30: - print("#{} {}/{}/{}".format(testcase+1, year, month, day)) - else: - print("#{} -1".format(testcase+1)) - - \ No newline at end of file diff --git a/ischeckdate_final.py b/ischeckdate_final.py deleted file mode 100644 index 775b06a..0000000 --- a/ischeckdate_final.py +++ /dev/null @@ -1,7 +0,0 @@ -N = int(input()) -numbers = list(map(int,input().split())) -numbers = sorted(numbers) -M = int((N-1)/2) -answer = numbers[M] - -print(answer) \ No newline at end of file diff --git a/kmp algorythm.py b/kmp algorythm.py deleted file mode 100644 index ecb0b72..0000000 --- a/kmp algorythm.py +++ /dev/null @@ -1,31 +0,0 @@ -def make_table(): - length = len(p) - table = [0] * length - j = 0 - for i in range(1, length): - while j > 0 and p[i] != p[j]: - j = table[j - 1] - if p[i] == p[j]: - j += 1 - table[i] = j - return table - - -def kmp(): - table = make_table() - j = 0 - for i in range(len(s)): - while j > 0 and s[i] != p[j]: - j = table[j - 1] - if s[i] == p[j]: - if j == len(p) - 1: - return True - else: - j += 1 - return False - - -if __name__ == "__main__": - s = input() - p = input() - print(1 if kmp() else 0) \ No newline at end of file diff --git a/kmp algorythm222.py b/kmp algorythm222.py deleted file mode 100644 index 21ee617..0000000 --- a/kmp algorythm222.py +++ /dev/null @@ -1,43 +0,0 @@ -def kmp_match(txt: str, pat: str) -> int: - # 스킵테이블 만들기 - def make_skip_table(skip: list): - pt = 1 # txt를 따라가는 인덱스 - pp = 0 # pat를 따라가는 인덱스 - while pt < len(pat): - if pat[pt] == pat[pp]: - pt += 1 - pp += 1 - skip[pt] = pp - elif pp == 0: - pt += 1 - skip[pt] = pp - else: - pp = skip[pp] - - # 부분 문자열 찾기 (이 문제에서는 있는지 없는지만 찾으면 된다.) - def find_match_idx(txt: str, pat: str) -> int: - pt = 0 - pp = 0 - while pt < len(txt) and pp < len(pat): - if txt[pt] == pat[pp]: - pt += 1 - pp += 1 - elif pp == 0: # 더 이상 앞으로 돌아갈 수 없는 경우 - pt += 1 - else: - pp = skip[pp] - if pp == len(pat): - return 1 - else: - return 0 - - skip = [0] * (len(pat) + 1) - make_skip_table(skip) - answer = find_match_idx(txt, pat) - print(answer) - - -if __name__ == '__main__': - S = input() - P = input() - kmp_match(S, P) \ No newline at end of file diff --git a/leetcode648Replace Words_trie.py b/leetcode648Replace Words_trie.py deleted file mode 100644 index 2c14d39..0000000 --- a/leetcode648Replace Words_trie.py +++ /dev/null @@ -1,41 +0,0 @@ -class Solution: - def replaceWords(self, dictionary: List[str], sentence: str) -> str: - # 트라이 자료구조 만들기 - root = {} - for dic in dictionary: - t = root - for c in dic: - if c not in t: - t[c] = {} - t = t[c] - t['*'] = True - - answer = [] - for word in sentence.split(): - t = root - res = '' - - if len(word) == 1: - if word in t: - answer.append(word) - continue - - flag = 0 - for c in word: - if '*' in t: - answer.append(res) - flag = 1 - break - - if c not in t: - answer.append(word) - flag = 1 - break - - t = t[c] - res += c - - if flag == 0: - answer.append(res) - - return " ".join(answer) \ No newline at end of file diff --git a/length_make_mountain.py b/length_make_mountain.py index f63d0b5..e305550 100644 --- a/length_make_mountain.py +++ b/length_make_mountain.py @@ -1,18 +1,18 @@ -#coding: utf-8 - - -T = int(input()) - -def LISDP(): - a = list(map(int,input().split())) - LIS = [0]*(a[0]+1) - for i in range(1,a[0]+1): - LIS[i] = 1 - for j in range(1,i): - if a[j] LIS[i]: - LIS[i] = 1+LIS[j] - return max(LIS) - - -for k in range(T): +#coding: utf-8 + + +T = int(input()) + +def LISDP(): + a = list(map(int,input().split())) + LIS = [0]*(a[0]+1) + for i in range(1,a[0]+1): + LIS[i] = 1 + for j in range(1,i): + if a[j] LIS[i]: + LIS[i] = 1+LIS[j] + return max(LIS) + + +for k in range(T): print("#{0} {1}".format(k+1, LISDP())) \ No newline at end of file diff --git a/line2022/1.py b/line2022/1.py deleted file mode 100644 index af8b153..0000000 --- a/line2022/1.py +++ /dev/null @@ -1,23 +0,0 @@ -from typing import List -from collections import defaultdict - -def solution(queries: List[List[int]]): - answer = 0 - counter = defaultdict(int) - level = {} - for idx, cnt in queries: - new_cnt = counter[idx] + cnt - if idx not in level: - level[idx] = 1 - if new_cnt >= level[idx]: - answer += counter[idx] - while new_cnt > level[idx]: - level[idx] *= 2 - counter[idx] = new_cnt - - return answer - - - - -print(solution([[2, 10], [7, 1], [2, 5], [2, 9], [7, 32]])) \ No newline at end of file diff --git a/line2022/2.py b/line2022/2.py deleted file mode 100644 index a9c2449..0000000 --- a/line2022/2.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import List - -def solution(k: int, dic: List[str], chat: str): - answer = [] - bad_words = set() - # 미리 k개 만큼 .으로 변환시킨 단어를 저장 - for word in dic: - tmp = [] - tmp.append(word) - # 1개 ~ max개까지 - for dot_cnt in range(len(word)//k): - for resource in tmp: - # dot을 넣을 위치 - for idx in range(len(resource)): - # dot의 size - for dot_size in range(1, k + 1): - if not '.' in resource[idx: idx + dot_size]: - tmp.append(resource[:idx] + "." + resource[dot_size + idx:]) - - for each_word in tmp: - bad_words.add(each_word) - for word in chat.split(): - if word in bad_words: - answer.append('#' * len(word)) - else: - answer.append(word) - answer = ' '.join(answer) - return answer - - - - -print(solution(2, ["slang", "badword"], "badword ab.cd bad.ord .word sl.. bad.word")) \ No newline at end of file diff --git a/line2022/3.py b/line2022/3.py deleted file mode 100644 index e1fc89f..0000000 --- a/line2022/3.py +++ /dev/null @@ -1,29 +0,0 @@ -from typing import List - -def solution(n: int, m: int, fires: List[List[int]], ices: List[List[int]]): - answer = [[0 for _ in range(n)] for _ in range(n)] - - for i in range(n): - for j in range(n): - for x, y in fires: - x -= 1 - y -= 1 - dist = max(abs(i - x), abs(j - y)) - if dist == 0: - answer[i][j] -= 1 - if m >= dist: - answer[i][j] += m - dist + 1 - for x, y in ices: - x -= 1 - y -= 1 - dist = abs(i-x) + abs(j-y) - if dist == 0: - answer[i][j] += 1 - if m >= dist: - answer[i][j] -= (m - dist + 1) - return answer - - - - -print(solution(3, 2, [[1, 1]], [[3, 3]])) \ No newline at end of file diff --git a/line2022/4.py b/line2022/4.py deleted file mode 100644 index a2ae976..0000000 --- a/line2022/4.py +++ /dev/null @@ -1,47 +0,0 @@ -from typing import List -from collections import deque - - -delta = ((0, 1), (1, 0), (-1, 0), (0, -1), (-2, 0), (0, 2), (0, -2), (0, 3), (0, -3), (-1, 1), (-1, -1)) - -def solution(wall: List[str]): - n = len(wall) - m = len(wall[0]) - cnts = [[0 for _ in range(m)] for _ in range(n)] - queue = deque() - queue.append((n - 1, 0)) - cnts[n - 1][0] = 1 - while queue: - x, y = queue.popleft() - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < n and 0 <= ny < m and wall[nx][ny] == 'H' and cnts[nx][ny] == 0: - if dx == -2 and wall[x - 1][y] == '.': - queue.append((nx, ny)) - elif dy == 2 and wall[x][y + 1] == '.' and x - 1 >= 0 and wall[x - 1][y + 1] == '.': - queue.append((nx, ny)) - elif dy == -2 and wall[x][y - 1] == '.' and x - 1 >= 0 and wall[x - 1][y - 1] == '.': - queue.append((nx, ny)) - elif dy == -3 and wall[x][y - 1] == '.' and x - 1 >= 0 and wall[x - 1][y - 1] == '.' and wall[x][y - 2] == '.' and wall[x - 1][y - 2] == '.': - queue.append((nx, ny)) - elif dy == 3 and wall[x][y + 1] == '.' and x - 1 >= 0 and wall[x - 1][y + 1] == '.' and wall[x][y + 2] == '.' and wall[x - 1][y + 2] == '.': - queue.append((nx, ny)) - elif dx == -1 and dy == 1 and wall[x][y + 1] == '.' and wall[x - 1][y] == '.': - queue.append((nx, ny)) - elif dx == -1 and dy == -1 and wall[x][y - 1] == '.' and wall[x - 1][y] == '.': - queue.append((nx, ny)) - elif abs(dx + dy) == 1: - queue.append((nx, ny)) - else: - continue - cnts[nx][ny] = cnts[x][y] + 1 - - for i in range(n): - for j in range(m): - if wall[i][j] == 'H' and cnts[i][j] == 0: - cnts[i][j] = -1 - return cnts - - - -print(solution(["H.H", ".HX", "H.H"])) \ No newline at end of file diff --git a/linkedList.py b/linkedList.py deleted file mode 100644 index a4a7b25..0000000 --- a/linkedList.py +++ /dev/null @@ -1,97 +0,0 @@ -#Single Linked List - -class Node(object): - def __init__(self, data, next = None): - self.data = data - self.next = next - -class SList(object): - def __init__(self): - self.head = Node(None) - self.size = 0 - - def listSize(self): - return self.size - - def is_empty(self): - if self.size != 0: - return False - else: - return True - - def selectNode(self, idx): - if idx >= self.size: - print("Index Error") - return None - if idx == 0: - return self.head - else: - target = self.head - for cnt in range(idx): - target = target.next - return target - - def appendleft(self, value): - if self.is_empty(): - self.head = Node(value) - else: - self.head = Node(value, self.head) - self.size += 1 - - def append(self, value): - if self.is_empty(): - self.head = Node(value) - self.size += 1 - else: - target = self.head - while target.next != None: - target = target.next - newtail = Node(value) - target.next = newtail - self.size += 1 - - def insert(self, value, idx): - if self.is_empty(): - self.head = Node(value) - self.size += 1 - elif idx == 0: - self.head = Node(value, self.head) - self.size += 1 - else: - target = self.selectNode(idx-1) - if target == None: - return - newNode = Node(value) - tmp = target.next - target.next = newNode - newNode.next = tmp - self.size += 1 - - def delete(self, idx): - if self.is_empty(): - print('Underflow: Empty Linked List Error') - return - elif idx >= self.size: - print('Overflow: Index Error') - return - elif idx == 0: - target = self.head - self.head = target.next - del(target) - self.size -= 1 - else: - target = self.selectNode(idx-1) - deltarget = target.next - target.next = target.next.next - del(deltarget) - self.size -= 1 - - def printlist(self): - target = self.head - while target: - if target.next != None: - print(target.data, '-> ', end='') - target = target.next - else: - print(target.data) - target = target.next \ No newline at end of file diff --git a/list_practice.py b/list_practice.py index c6fe043..c090d9f 100644 --- a/list_practice.py +++ b/list_practice.py @@ -1,10 +1,10 @@ -#coding: utf-8 - - -arr =list(map(int,input().split()) - -for i in range(1<보물, 다른 보물상자의 키들이 하나 이상 들어있다. -#어떤 키가 들어있는지는 열기 전에 이미 알고있음. -#나는 이미 K개의 키를 가지고있음. - -#=> 모든상자를 열수있는가? 열수있다면 사전 순 최소인 방법을 출력하라. - - -""" -출력 -열수없으면 IMPOSSIBLE -있으면 상자 여는 순서 N개 정수. 여러개면 사전순 최소인 순서를 출력 -""" - -#결국 DFS구현(가다가 아니면 돌아옴) -#인덱스를 상자넘버(키종류) -#그래프 구현 -#dfs 구현 -#입출력 - - - - -def DFS_find_treasure(v, discovered=[]): - - for w in boxes[v]: - if not w in discovered: - discovered.append(w) - discovered = DFS_find_treasure(w,discovered) - return discovered - -T = int(input()) - -for test_case in range(T): - K, N = map(int,input().split()) - boxes = {} - boxes[0] = list(map(int,input().split())) - for Box_Num in range(N): - Ti_Ki_TiNo = list(map(int,input().split())) - Ti = Ti_Ki_TiNo[0] - Ki = Ti_Ki_TiNo[1] - TiNo = [0]*Ki - for i in range(2,Ki+2): - TiNo[i-2] = Ti_Ki_TiNo[i] - boxes[Ti] = TiNo - - if N != len(DFS_find_treasure(0)): - print("IMPOSSIBLE") - else: - print("#{} {}".format(test_case+1,DFS_find_treasure(0))) \ No newline at end of file diff --git a/lotto_numbering_module.py b/lotto_numbering_module.py index bb82256..db62b6f 100644 --- a/lotto_numbering_module.py +++ b/lotto_numbering_module.py @@ -1,23 +1,23 @@ -#coding: utf-8 - -#성적 총점 평점. - -scores = [] - -count = int(input("총 학생 수를 입력하세요:")) - -for i in range(1, count+1): - score = [] - kor = int(input("학생{0}의 국어점수를 입력하세요:".format(i))) - score.append(kor) - mat = int(input("학생{0}의 수학점수를 입력하세요:".format(i))) - score.append(mat) - eng = int(input("학생{0}의 영어점수를 입력하세요:".format(i))) - score.append(eng) - scores.append(score) - -for score in scores: - total = 0 - for s in score: - total += s - print("총점: {0}, 평균:{1:0.2F}".format(total, total/len(score))) +#coding: utf-8 + +#성적 총점 평점. + +scores = [] + +count = int(input("총 학생 수를 입력하세요:")) + +for i in range(1, count+1): + score = [] + kor = int(input("학생{0}의 국어점수를 입력하세요:".format(i))) + score.append(kor) + mat = int(input("학생{0}의 수학점수를 입력하세요:".format(i))) + score.append(mat) + eng = int(input("학생{0}의 영어점수를 입력하세요:".format(i))) + score.append(eng) + scores.append(score) + +for score in scores: + total = 0 + for s in score: + total += s + print("총점: {0}, 평균:{1:0.2F}".format(total, total/len(score))) diff --git a/make7_number_answer.py b/make7_number_answer.py deleted file mode 100644 index 8e7646f..0000000 --- a/make7_number_answer.py +++ /dev/null @@ -1,24 +0,0 @@ -def dfs(lst, start, count, string): - global result - if count == 7: - result.add(string) - return - - for i in range(4): - ny, nx = start[0] + dy[i], start[1] + dx[i] - if 0 <= ny < 4 and 0 <= nx < 4: - dfs(lst, [ny, nx], count + 1, string + lst[ny][nx]) - - - - -T = int(input()) -dy = [1, -1, 0, 0] -dx = [0, 0, 1, -1] -for test_case in range(1, T + 1): - lst = [list(map(str, input().split())) for _ in range(4)] - result = set() - for i in range(4): - for j in range(4): - dfs(lst, [i, j], 1, lst[i][j]) - print('#{} {}'.format(test_case, len(result))) \ No newline at end of file diff --git a/make7number.py b/make7number.py deleted file mode 100644 index bf88795..0000000 --- a/make7number.py +++ /dev/null @@ -1,3 +0,0 @@ -N = int(input()) -for i in range(N,-1,-1): - print(f"{i}",end=" ") \ No newline at end of file diff --git a/make_game.py b/make_game.py deleted file mode 100644 index 257bc9d..0000000 --- a/make_game.py +++ /dev/null @@ -1,126 +0,0 @@ -import random - - - -T = int(input()) - - -def move(): - global i,j - if direction == 'right': - j +=1 - if j==C: - j=0 - if direction == 'left': - j -=1 - if j==-1: - j=C-1 - if direction == 'up': - i -=1 - if i==-1: - i=R-1 - if direction == 'down': - i +=1 - if i==R: - i=0 - - - - -for test in range(1,T+1): - memory = 0 - R,C = map(int,input().split()) - game = [list(input()) for _ in range(R)] - check = [] - - i,j=0,0 - direction = 'right' - answer = 0 - - if all('@' not in l for l in game): - answer = 'NO' - - while 1: - - if answer == 'NO': - break - - if (i,j,direction,memory) in check and game[i][j] != '?': - answer = 'NO' - break - else: - check.append((i,j,direction,memory)) - - if game[i][j] =='<': - direction ='left' - move() - - if game[i][j] =='>': - direction ='right' - move() - - if game[i][j] =='^': - direction = 'up' - move() - - if game[i][j] =='v': - direction = 'down' - move() - - - if game[i][j] =='_': - if memory == 0: - direction ='right' - else: - direction ='left' - move() - - if game[i][j] =='|': - if memory == 0: - direction = 'down' - else: - direction = 'up' - move() - - if game[i][j] =='?': - if game[(i+1)%R][j] == '@' or game[(i-1)%R][j] == '@' or game[i][(j+1)%C] == '@' or game[i][(j-1)%C] == '@': - answer = 'YES' - break - ran_num = random.randint(0,3) - if ran_num==0: - direction ='right' - elif ran_num==1: - direction ='left' - elif ran_num==2: - direction = 'down' - else: - direction = 'up' - move() - - if game[i][j].isdigit(): - memory = int(game[i][j]) - move() - - if game[i][j] =='+': - memory += 1 - if memory == 16: - memory = 0 - move() - - if game[i][j] =='-': - memory -= 1 - if memory == -1: - memory = 15 - move() - - if game[i][j] =='.': - move() - - if game[i][j] == '@': - answer = 'YES' - break - - - - - print(f"#{test} {answer}") diff --git a/make_game_another.py b/make_game_another.py deleted file mode 100644 index 574959f..0000000 --- a/make_game_another.py +++ /dev/null @@ -1,132 +0,0 @@ -direction = '<>^v|_' -memory = '0123456789' -operator = '+-' -ee = 0 - -def dfs(mem, rDir, cDir, dirct): - global ans - global visited - global ee - - pattern = hyuk[rDir][cDir] - tmp = mem+str(rDir)+str(cDir)+dirct - if ee == 1: - return - #print("##",pattern,"%%",[mem,rDir, cDir, dirct]) - if tmp in visited: - #ee = 1 - #print('duplic') - return - else: - visited.append(tmp) - - if pattern == '@': - ee = 1 - ans = 'YES' - return - #print(pattern, "!!", visited, "@@", [mem, rDir, cDir, dirct]) - if pattern in operator: - if pattern == '+': - mem = str((int(mem)+1)%16) - else: - mem = str((int(mem)-1)%16) - if pattern in memory: - mem = pattern - - - if pattern == '?': - if hyuk[(rDir+1)%row][cDir] == '@' or hyuk[(rDir-1)%row][cDir] == '@' or hyuk[rDir][(cDir+1)%col] == '@' or hyuk[rDir][(cDir-1)%col] == '@': - ans = 'YES' - ee = 1 - return - else: - for i in range(4): - if i == 0: - #rDir = (rDir+1)%row - dirct = 'down' - dfs(mem, (rDir+1)%row, cDir, dirct) - if i == 1: - #rDir = (rDir-1)%row - dirct = 'up' - dfs(mem, (rDir-1)%row, cDir, dirct) - if i == 2: - #col = (cDir+1)%col - dirct = 'right' - dfs(mem, rDir, (cDir+1)%col, dirct) - if i == 3: - #col = (cDir-1)%col - dirct = 'left' - dfs(mem, rDir, (cDir-1)%col, dirct) - #print("?",[r, c, dirct]) - #dfs(mem, r, c, dirct) - - else: - if pattern in direction: - if pattern == '>': - dirct = 'right' - elif pattern == '<': - dirct = 'left' - elif pattern == '^': - dirct = 'up' - elif pattern == 'v': - dirct = 'down' - elif pattern == '|': - if mem == '0': - dirct = 'down' - else: - dirct = 'up' - elif pattern == '_': - if mem == '0': - dirct = 'right' - else: - dirct = 'left' - - if dirct == 'right': - cDir = (cDir+1)%col - elif dirct == 'left': - cDir = (cDir-1)%col - elif dirct == 'up': - rDir = (rDir-1)%row - elif dirct == 'down': - rDir = (rDir+1)%row - - - dfs(mem, rDir, cDir, dirct) - - -numtest = int(input()) -for testCnt in range(numtest): - row, col = input().split() - row = int(row) - col = int(col) - flag = 0 - hyuk = [['']*col for i in range(row)] - #visited = [[['-1',-1,-1,'X']]*col for i in range(row)] - visited = [] - ans = 'NO' - ee = 0 - - ''' - hyuk = [a for a in input().split()] - for item in hyuk: - if '@' in item: - flag = 1 - ''' - for rowcnt in range(row): - hyuk[rowcnt] = input() - if '@' in hyuk[rowcnt]: - flag = 1 - - for i in range(row): - for j in range(col): - if hyuk[i][j] == '@': - if hyuk[(i-1)%row][j] != 'v' and hyuk[(i-1)%row][j] in direction and hyuk[(i+1)%row][j] != '^' and hyuk[(i+1)%row][j] in direction and hyuk[i][(j-1)%col] != '>' and hyuk[i][(j-1)%col] in direction and hyuk[i][(j+1)%col] != '<' and hyuk[i][(j+1)%col] in direction: - flag = 0 - break - - - #visited[0][0] = ['0',0,0,'right'] - if flag == 1: - dfs('0', 0, 0, 'right') - - print("#%d %s" % (testCnt+1, ans)) \ No newline at end of file diff --git a/make_game_another2.py b/make_game_another2.py deleted file mode 100644 index 41349ad..0000000 --- a/make_game_another2.py +++ /dev/null @@ -1,70 +0,0 @@ -def dfs(x, y, memo, d): - global ans - if ans == 'YES': return - - tgt = arr[x][y] - if tgt == '@': - ans = 'YES' - return - - wrap = (x, y, memo, d) - if wrap in visited: return - visited[wrap] = True - if tgt in direction: - if tgt == '<': d = 0 - elif tgt == '>': d = 1 - elif tgt == '^': d = 2 - elif tgt == 'v': d = 3 - - elif tgt == '_': d = 1 if memo == 0 else 0 - elif tgt == '|': d = 3 if memo == 0 else 2 - - elif tgt.isdigit(): memo = int(tgt) - elif tgt == '+': memo = (memo + 1) % 16 - elif tgt == '-': memo = (memo - 1) % 16 - - if tgt == '?': - if arr[(x + 1) % R][y] == '@' or arr[(x - 1) % R][y] == '@' \ - or arr[x][(y + 1) % C] == '@' or arr[x][(y - 1) % C] == '@': - ans = 'YES' - return - - for i in range(4): - dx, dy = delta[i] - tx, ty = (x + dx) % R, (y + dy) % C - dfs(tx, ty, memo, i) - - else: - dx, dy = delta[d] - dfs((x + dx) % R, (y + dy) % C, memo, d) - - -direction = '<>^v_|' -delta = ((0, -1), (0, 1), (-1, 0), (1, 0)) -TCs = int(input()) -for T in range(1, TCs+1): - R, C = map(int, input().split()) - arr = [] - - atExists = False - for i in range(R): - arr.append(list(input())) - if '@' in arr[i]: atExists = True - - for i in range(R): - for j in range(C): - if arr[i][j] == '@': - if arr[(i - 1) % R][j] != 'v' and arr[(i - 1) % R][j] in direction \ - and arr[(i + 1) % R][j] != '^' and arr[(i + 1) % R][j] in direction \ - and arr[i][(j - 1) % C] != '>' and arr[i][(j - 1) % C] in direction \ - and arr[i][(j + 1) % C] != '<' and arr[i][(j + 1) % C] in direction: - atExists = False - break - - ans = 'NO' - print(f'#{T}', end=' ') - if atExists: - visited = {} - dfs(0, 0, 0, 1) - - print(ans) \ No newline at end of file diff --git a/make_game_another3.py b/make_game_another3.py deleted file mode 100644 index 80b8be0..0000000 --- a/make_game_another3.py +++ /dev/null @@ -1,219 +0,0 @@ -num = 0 -end_flag = False - - -def get_status(map_, i, j, status): - global num - - if map_[i][j] == ">": - return "right" - elif map_[i][j] == "<": - return "left" - elif map_[i][j] == "v": - return "down" - elif map_[i][j] == "^": - return "up" - elif map_[i][j] == "-": - if num == 0: - num = 15 - return status - else: - num -= 1 - return status - - elif map_[i][j] == "+": - if num == 15: - num = 0 - return status - else: - num += 1 - return status - - elif map_[i][j] == "_": - if num == 0: - return "right" - else: - return "left" - elif map_[i][j] == ".": - return status - elif map_[i][j] == "@": - return "end" - elif map_[i][j] == "?": - return "all" - elif map_[i][j] == "|": - if num == 0: - return "down" - else: - return "up" - - elif map_[i][j].isnumeric(): - num = int(map_[i][j]) - return status - - else: - return "right" - - -def search(map_, i, j, r, c, status, vi_dict): - global end_flag - - if status == "right": - if j + 1 < c and not end_flag: - s = get_status(map_, i, j + 1, status) - if not str(i) + "." + str(j + 1) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(j + 1) + "." + status + "." + str(num)] = 1 - search(map_, i, j + 1, r, c, s, vi_dict) - else: - return - elif j + 1 >= c: - s = get_status(map_, i, 0, status) - if not str(i) + "." + str(0) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(0) + "." + status + "." + str(num)] = 1 - search(map_, i, 0, r, c, s, vi_dict) - else: - return - - elif status == "left": - if j - 1 >= 0 and not end_flag: - s = get_status(map_, i, j - 1, status) - if not str(i) + "." + str(j - 1) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(j - 1) + "." + status + "." + str(num)] = 1 - search(map_, i, j - 1, r, c, s, vi_dict) - else: - return - elif j - 1 < 0: - s = get_status(map_, i, c - 1, status) - if not str(i) + "." + str(c - 1) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(c - 1) + "." + status + "." + str(num)] = 1 - search(map_, i, c - 1, r, c, s, vi_dict) - else: - return - - elif status == "down": - if i + 1 < r and not end_flag: - s = get_status(map_, i + 1, j, status) - if not str(i + 1) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i + 1) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, i + 1, j, r, c, s, vi_dict) - else: - return - elif i + 1 >= r: - s = get_status(map_, 0, j, status) - if not str(0) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(0) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, 0, j, r, c, s, vi_dict) - else: - return - - elif status == "up": - if i - 1 >= 0 and not end_flag: - s = get_status(map_, i - 1, j, status) - if not str(i - 1) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i - 1) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, i - 1, j, r, c, s, vi_dict) - else: - return - elif i - 1 < 0: - s = get_status(map_, r - 1, j, status) - if not str(r - 1) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(r - 1) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, r - 1, j, r, c, s, vi_dict) - else: - return - - elif status == "all": - if j + 1 < c and not end_flag: - s = get_status(map_, i, j + 1, "right") - if not str(i) + "." + str(j + 1) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(j + 1) + "." + status + "." + str(num)] = 1 - search(map_, i, j + 1, r, c, s, vi_dict) - else: - return - elif j + 1 >= c: - s = get_status(map_, i, 0, "right") - if not str(i) + "." + str(0) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(0) + "." + status + "." + str(num)] = 1 - search(map_, i, 0, r, c, s, vi_dict) - else: - return - - if j - 1 >= 0 and not end_flag: - s = get_status(map_, i, j - 1, "left") - if not str(i) + "." + str(j - 1) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(j - 1) + "." + status + "." + str(num)] = 1 - search(map_, i, j - 1, r, c, s, vi_dict) - else: - return - elif j - 1 < 0: - s = get_status(map_, i, c - 1, "left") - if not str(i) + "." + str(c - 1) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i) + "." + str(c - 1) + "." + status + "." + str(num)] = 1 - search(map_, i, c - 1, r, c, s, vi_dict) - else: - return - - if i + 1 < r and not end_flag: - s = get_status(map_, i + 1, j, "down") - if not str(i + 1) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i + 1) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, i + 1, j, r, c, s, vi_dict) - else: - return - elif i + 1 > r: - s = get_status(map_, 0, j, "down") - if not str(0) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(0) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, 0, j, r, c, s, vi_dict) - else: - return - - if i - 1 >= 0 and not end_flag: - s = get_status(map_, i - 1, j, "up") - if not str(i - 1) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(i - 1) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, i - 1, j, r, c, s, vi_dict) - else: - return - elif i - 1 < 0: - s = get_status(map_, r - 1, j, "up") - if not str(r - 1) + "." + str(j) + "." + status + "." + str(num) in vi_dict: - vi_dict[str(r - 1) + "." + str(j) + "." + status + "." + str(num)] = 1 - search(map_, r - 1, j, r, c, s, vi_dict) - else: - return - - elif status == "end": - end_flag = True - return - - -def main(): - global num, end_flag - - tc = int(input()) - for t in range(1, tc+1): - r, c = map(int, input().split()) - map_ = [[0]*c for _ in range(r)] - - for i in range(r): - line = input() - for j in range(c): - map_[i][j] = line[j] - - if map_[0][0].isnumeric(): - num = int(map_[0][0]) - else: - num = 0 - - end_flag = False - vi_dict = {} - search(map_, 0, 0, r, c, get_status(map_, 0, 0, "right"), vi_dict) - - if end_flag: - print("#%d YES" %(t)) - else: - print("#%d NO" %(t)) - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/make_game_another4.py b/make_game_another4.py deleted file mode 100644 index 52a226d..0000000 --- a/make_game_another4.py +++ /dev/null @@ -1,63 +0,0 @@ -from collections import deque -dx = [0, 1, 0, -1] -dy = [1, 0, -1, 0] -for tc in range(1,int(input()) + 1): - R, C = map(int, input().split()) - data = [input() for _ in range(R)] - visit = [[[[True] * 16 for j in range(4)] for i in range(C)] for _ in range(R)] - ans = False - memory = 0 - Q = deque() - Q.append((0, 0, 0)) - visit[0][0][0][memory] = False - while Q: - x, y, direction = Q.popleft() - chk = False - if '0' <= data[x][y] <= '9': - memory = int(data[x][y]) - elif data[x][y] == '+': - memory = (memory + 1) % 16 - elif data[x][y] == '-': - memory = (memory - 1) % 16 - elif data[x][y] == '<': - direction = 2 - elif data[x][y] == '>': - direction = 0 - elif data[x][y] == '^': - direction = 3 - elif data[x][y] == 'v': - direction = 1 - elif data[x][y] == '_': - if memory == 0: - direction = 0 - else: - direction = 2 - elif data[x][y] == '|': - if memory == 0: - direction = 1 - else: - direction = 3 - elif data[x][y] == '?': - chk = True - elif data[x][y] == '@': - ans = True - Q.clear() - if chk: - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - nx %= R - ny %= C - if visit[nx][ny][i][memory]: - visit[nx][ny][i][memory] = False - Q.append((nx, ny, i)) - else: - nx, ny = x + dx[direction], y + dy[direction] - nx %= R - ny %= C - if visit[nx][ny][direction][memory]: - visit[nx][ny][direction][memory] = False - Q.append((nx, ny, direction)) - if ans: - print('#{} YES'.format(tc)) - else: - print('#{} NO'.format(tc)) \ No newline at end of file diff --git a/make_purple section_practice.py b/make_purple section_practice.py index 219f941..4670a6d 100644 --- a/make_purple section_practice.py +++ b/make_purple section_practice.py @@ -1,18 +1,18 @@ -#coding: utf-8 - - -T = int(input()) - -def LISDP(): - a = list(map(int,input().split())) - LIS = [] - for i in range(1,a[0]): - LIS[i] = 1 - for j in range(1,i): - if a[j] LIS[i]: - LIS[i] = 1+LIS[j] - return max(LIS) - - -for k in range(T): +#coding: utf-8 + + +T = int(input()) + +def LISDP(): + a = list(map(int,input().split())) + LIS = [] + for i in range(1,a[0]): + LIS[i] = 1 + for j in range(1,i): + if a[j] LIS[i]: + LIS[i] = 1+LIS[j] + return max(LIS) + + +for k in range(T): print("#{0} {1}".format(k+1, LISDP())) \ No newline at end of file diff --git a/map,filter,lambda,eval_practice.py b/map,filter,lambda,eval_practice.py index e378ce3..be751d9 100644 --- a/map,filter,lambda,eval_practice.py +++ b/map,filter,lambda,eval_practice.py @@ -1,50 +1,50 @@ -#coding: utf-8 - -#Lotto.py - -import random - -lotto = random.sample(range(1,46,1),6) - -print(sorted(lotto)) - -def input_start(): - start = 0 - try: - start = int(input("로또 번호의 시작 번호를 입력하세요(기본값1):")) - except: - start = 1 - finally: - return start - -def input_end(): - try: - end = int(input("로또 번호의 끝 번호를 입력하세요(기본값45):")) - except: - end = 45 - finally: - return end - -def input_count(): - count = 0 - try: - count = int(input("로또 공의 개수를 입력하세요(기본값6):")) - except: - count = 6 - finally: - return count - -def print_lotto(start, end, count): - lotto = random.sample(range(start,end+1,1), count) - print("행운의 로또 번호는", end="") - print(sorted(lotto), end = "") - #리스트 기호[]삭제 - for i, num in enumerate(sorted(lotto)): - if i == len(lotto) -1:#마지막일시 - print("{0}".format(num),end="") - else:#마지막이 아닐시 - print("{0}".format(num),end="") - - print("입니다.") - +#coding: utf-8 + +#Lotto.py + +import random + +lotto = random.sample(range(1,46,1),6) + +print(sorted(lotto)) + +def input_start(): + start = 0 + try: + start = int(input("로또 번호의 시작 번호를 입력하세요(기본값1):")) + except: + start = 1 + finally: + return start + +def input_end(): + try: + end = int(input("로또 번호의 끝 번호를 입력하세요(기본값45):")) + except: + end = 45 + finally: + return end + +def input_count(): + count = 0 + try: + count = int(input("로또 공의 개수를 입력하세요(기본값6):")) + except: + count = 6 + finally: + return count + +def print_lotto(start, end, count): + lotto = random.sample(range(start,end+1,1), count) + print("행운의 로또 번호는", end="") + print(sorted(lotto), end = "") + #리스트 기호[]삭제 + for i, num in enumerate(sorted(lotto)): + if i == len(lotto) -1:#마지막일시 + print("{0}".format(num),end="") + else:#마지막이 아닐시 + print("{0}".format(num),end="") + + print("입니다.") + print_lotto(1,45,6) \ No newline at end of file diff --git a/mapping.py b/mapping.py index 3a413c2..2f85570 100644 --- a/mapping.py +++ b/mapping.py @@ -1,38 +1,38 @@ -from collections import deque -import sys -def bfs(q, cnt = 0): - dx, dy = [0, 0, 1, -1], [1, -1, 0, 0] - while q: - cnt += 1 - for _ in range(len(q)): - x, y = q.popleft() - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - if nx >= N or nx < 0 or ny >= M or ny < 0 or arr[nx][ny] != 0: - continue - arr[nx][ny] = 1 - q.append((nx,ny)) - if check(arr): - return cnt - 1 - else: - return -1 - -def check(arr): - for i in range(N): - for j in range(M): - if arr[i][j] == 0: - return False - break - return 1 - -if __name__ == "__main__": - input = sys.stdin.readline - M, N = map(int,input().split()) - q = deque([]) - arr = [] - for i in range(N): - arr.append(list(map(int,input().split()))) - for j in range(M): - if arr[i][j] == 1: - q.append((i,j)) +from collections import deque +import sys +def bfs(q, cnt = 0): + dx, dy = [0, 0, 1, -1], [1, -1, 0, 0] + while q: + cnt += 1 + for _ in range(len(q)): + x, y = q.popleft() + for i in range(4): + nx, ny = x + dx[i], y + dy[i] + if nx >= N or nx < 0 or ny >= M or ny < 0 or arr[nx][ny] != 0: + continue + arr[nx][ny] = 1 + q.append((nx,ny)) + if check(arr): + return cnt - 1 + else: + return -1 + +def check(arr): + for i in range(N): + for j in range(M): + if arr[i][j] == 0: + return False + break + return 1 + +if __name__ == "__main__": + input = sys.stdin.readline + M, N = map(int,input().split()) + q = deque([]) + arr = [] + for i in range(N): + arr.append(list(map(int,input().split()))) + for j in range(M): + if arr[i][j] == 1: + q.append((i,j)) print(bfs(q)) \ No newline at end of file diff --git a/maxPrize.py b/maxPrize.py deleted file mode 100644 index d473409..0000000 --- a/maxPrize.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -리스트 크기5 -교환2(무조건) -MAX값.(내림차순 정렬) -""" -T = int(input()) - -def maxPrize(): - numbers = list(map(int, input().split())) - N1 = list(str(numbers[0])) - digits = list(map(int, N1)) - t=0 - - for j in range(len(digits)): - for k in range(j+1,len(digits)): - if digits[j]=minft: - cnt += 1 - minft = j - -print(cnt) +""" +N개의 회의 +ST, FT 주어짐. +회의실 사용 최대로. +""" + +N = int(input()) +meetings = [[0]*2 for _ in range(N)] + +for i in range(N): + st, ft = map(int, input().split()) + meetings[i][0] = st + meetings[i][1] = ft + +minsort = sorted(meetings,key = lambda a:a[0]) +minsort = sorted(meetings,key = lambda a:a[1]) + +minft = 0 +cnt=0 +for i,j in minsort: + if i>=minft: + cnt += 1 + minft = j + +print(cnt) diff --git a/minimize_path_way.py b/minimize_path_way.py deleted file mode 100644 index 873e668..0000000 --- a/minimize_path_way.py +++ /dev/null @@ -1,37 +0,0 @@ -""" -출발S(0,0), 도착G(n-1,n-1) -깊이D에 비례하는 시간t -min(sum(t))=?? - - -""" -def findway_DFS(x,y,cnt): - check[x][y]=1 - - for i in range(4): - X = x +dx[i] - Y = y +dy[i] - if 0<=X d[x][y]+a[nx][ny]: - d[nx][ny] = d[x][y]+a[nx][ny] - q.append((nx,ny)) - else: - continue -for t in range(int(input())): - n = int(input()) - a = [list(map(int,list(input()))) for _ in range(n)] - d = [[-1]*(n) for _ in range(n)] - dfs(0,0) - print('#{} {}'.format(t+1,d[n-1][n-1])) \ No newline at end of file diff --git a/minimize_path_way_deque2.py b/minimize_path_way_deque2.py deleted file mode 100644 index cda90b1..0000000 --- a/minimize_path_way_deque2.py +++ /dev/null @@ -1,35 +0,0 @@ -from _collections import deque - - -def check(a, b): - return True if 0 <= a < n and 0 <= b < n else False - - -if __name__ == "__main__": - - for tc in range(1, int(input())+1): - n = int(input()) - matrix = [list(map(int, input())) for _ in range(n)] - INF = float('inf') - cost = [[INF] * n for _ in range(n)] - # visit = [[0] * n for _ in range(n)] - - cost[0][0] = 0 - queue = deque() - queue.append((0, 0)) - # visit[0][0] = 1 - - while queue: - cr, cc = queue.popleft() - - for dr, dc in [(0, 1), (1, 0), (-1, 0), (0, -1)]: - nr = dr + cr - nc = dc + cc - - if check(nr, nc) and cost[nr][nc] > matrix[nr][nc] + cost[cr][cc]: - cost[nr][nc] = matrix[nr][nc] + cost[cr][cc] - # visit[nr][nc] = 1 - queue.append((nr, nc)) - - - print("#{} {}".format(tc, cost[n-1][n-1])) \ No newline at end of file diff --git a/minimize_path_way_dijkstra.py b/minimize_path_way_dijkstra.py deleted file mode 100644 index 6da24c0..0000000 --- a/minimize_path_way_dijkstra.py +++ /dev/null @@ -1,27 +0,0 @@ -import heapq - -def dijkstra(lst, n, r, c): - distances = [[float('inf') for _ in range(n)] for _ in range(n)] - distances[r][c] = 0 - queue = [] - heapq.heappush(queue, [0, r, c]) - while queue: - current_distance, y, x = heapq.heappop(queue) - if distances[y][x] < current_distance: - continue - for i in range(4): - ny, nx = y + dy[i], x + dx[i] - if 0 <= ny < n and 0 <= nx < n: - distance = current_distance + int(lst[ny][nx]) - if distance < distances[ny][nx]: - distances[ny][nx] = distance - heapq.heappush(queue, [distance, ny, nx]) - return distances[n-1][n-1] - -T = int(input()) -dy = [-1, 0, 1, 0] -dx = [0, 1, 0, -1] -for test_case in range(1, T + 1): - N = int(input()) - lst = [list(input()) for _ in range(N)] - print('#{} {}'.format(test_case, dijkstra(lst, N, 0, 0))) diff --git a/nQueen.py b/nQueen.py index 6d0a5a2..64e86eb 100644 --- a/nQueen.py +++ b/nQueen.py @@ -1,16 +1,16 @@ -T = int(input()) - - - -for test_case in range(1, T + 1): - edge = list(input()) - Numerator = 1 - Demorator = 1 - - for i in range(len(edge)): - if edge[i] == "L": - Demorator += Numerator - else: - Numerator += Demorator - +T = int(input()) + + + +for test_case in range(1, T + 1): + edge = list(input()) + Numerator = 1 + Demorator = 1 + + for i in range(len(edge)): + if edge[i] == "L": + Demorator += Numerator + else: + Numerator += Demorator + print("#{} {} {}".format(test_case, Numerator, Demorator)) \ No newline at end of file diff --git a/object_oriented_practice.py b/object_oriented_practice.py index fa277f9..d0dea41 100644 --- a/object_oriented_practice.py +++ b/object_oriented_practice.py @@ -1,24 +1,24 @@ -#coding: utf-8 - -def get_max(init_num): - my_max = init_num[0] - for i in range(1, len(init_num)): - if my_max < init_num[i]: - my_max = init_num[i] - - return my_max - -def get_min(init_num): - my_min = init_num[0] - for i in range(1,len(init_num)): - if my_min > init_num[i]: - my_min = init_num[i] - - return my_min - -TC = int(input()) -for tc in range(1, TC+1): - N = int(input()) - init_num = list(map(int, input().split())) - result = get_max(init_num) - get_min(init_num) +#coding: utf-8 + +def get_max(init_num): + my_max = init_num[0] + for i in range(1, len(init_num)): + if my_max < init_num[i]: + my_max = init_num[i] + + return my_max + +def get_min(init_num): + my_min = init_num[0] + for i in range(1,len(init_num)): + if my_min > init_num[i]: + my_min = init_num[i] + + return my_min + +TC = int(input()) +for tc in range(1, TC+1): + N = int(input()) + init_num = list(map(int, input().split())) + result = get_max(init_num) - get_min(init_num) print(f'#{tc} {result}') \ No newline at end of file diff --git a/paskal_triangle.py b/paskal_triangle.py index 56cb1d0..87f5833 100644 --- a/paskal_triangle.py +++ b/paskal_triangle.py @@ -1,15 +1,15 @@ -import itertools as it - -T = int(input()) -for test in range(T): - N = int(input()) - s = [] - print("#{}\n1".format(test+1)) - for i in range(N-1): - s.append(i) - - for j in range(i+2): - com = list(it.combinations(s,j)) - num = len(com) - print(num, end = " ") +import itertools as it + +T = int(input()) +for test in range(T): + N = int(input()) + s = [] + print("#{}\n1".format(test+1)) + for i in range(N-1): + s.append(i) + + for j in range(i+2): + com = list(it.combinations(s,j)) + num = len(com) + print(num, end = " ") print("") \ No newline at end of file diff --git a/patternMatching.py b/patternMatching.py index 54780dc..3c805b0 100644 --- a/patternMatching.py +++ b/patternMatching.py @@ -1,70 +1,70 @@ -# 본 코드는 text안에 찾는 pattern 이 있으면 1 없으면 0 을 출력해주는 코드이다 - -# 보이어무어 알고리즘을 적용했다. - - - -# 보이어무어 알고리즘이란 다음과 같다 - -# pattern의 오른쪽 끝 문자와 text의 현재 위치의 문자가 일치하는지 검사 -# 끝이 일치하면 pattern과 text를 다 검사한다. 마지막까지 일치하지 않으면 패턴길이만큼 skip -# 끝이 일치하지않으면 text의 현재위치 문자가 skip배열에 있는지 확인. 있으면 인덱스만큼 skip, 없으면 패턴길이만큼 skip -# 텍스트 끝 도달할 때까지 반복 - -text = 'a pattern matching algorithm' -pattern = 'rithm' -s = pattern[::-1] -skip = list(range((len(pattern)))) - -i = len(pattern)-1 -result = 0 - -while i < len(text): - nxt = len(s) - j = 0 - if s[j] == text[i]: - while j < len(s): - if s[j] != text[i-j]: - break - j += 1 - if j == len(s): - result = 1 - else: - while j < len(s): - if s[j] == text[i]: - nxt = min(j, nxt) - break - j += 1 - if result: - break - i += nxt - -print(result) - - -# 고지식한 패턴검색 알고리즘 = Brute Force. 텍스트의 모든 위치에서 패턴비교 O(MN) - -# KMP 알고리즘. 불일치 발생한 앞부분 대해 다시 비교하지 않고 매칭 수행 O(M+N)=O(N) -# next 배열을 생성해 불일치 발생하면 이동할 다음위치 저장. -# 패턴 왼쪽에서 오른쪽으로 비교 - -# 보이어 무어 알고리즘. 앞부분보다 끝부분가서 불일치 일어날 확률이 높다는 것 이용 -# 일반적으로는 O(N) 보다 적은 수행시간. 최악일땐 O(MN) -# skip 배열 생성해서 일치하는 칸으로 몇칸 이동해야하는지 저장 -# 패턴 오른쪽에서 왼쪽으로 비교. - -# 그러면 3가지 패턴매칭 알고리즘을 비교해보자. M은 패턴의 길이, N은 텍스트의 길이 -# Brute Force(=고지식한 패턴검색 알고리즘) -# 텍스트의 모든 위치에서 패턴 비교하고 한칸씩 이동한다. -# 시간복잡도 O(MN) -# KMP -# 불일치 발생한 앞부분에 대해 다시 비교하지 않고 매칭 수행 -# next배열을 생성해 불일치 발생하면 이동할 다음 위치 저장 -# 패턴의 왼쪽에서 오른쪽으로 비교 -# 시간복잡도 O(M+N) = O(N) -# 보이어무어 -# 앞부분보다 끝부분가서 불일치 일어날 확률이 높다는 것 이용 -# skip 배열 생성해서 일치하는 칸으로 몇 칸 이동해야하는지 저장 -# 패턴의 오른쪽에서 왼쪽으로 비교 -# 상용화된 제품이나 서비스에 가장 많이 적용됨 +# 본 코드는 text안에 찾는 pattern 이 있으면 1 없으면 0 을 출력해주는 코드이다 + +# 보이어무어 알고리즘을 적용했다. + + + +# 보이어무어 알고리즘이란 다음과 같다 + +# pattern의 오른쪽 끝 문자와 text의 현재 위치의 문자가 일치하는지 검사 +# 끝이 일치하면 pattern과 text를 다 검사한다. 마지막까지 일치하지 않으면 패턴길이만큼 skip +# 끝이 일치하지않으면 text의 현재위치 문자가 skip배열에 있는지 확인. 있으면 인덱스만큼 skip, 없으면 패턴길이만큼 skip +# 텍스트 끝 도달할 때까지 반복 + +text = 'a pattern matching algorithm' +pattern = 'rithm' +s = pattern[::-1] +skip = list(range((len(pattern)))) + +i = len(pattern)-1 +result = 0 + +while i < len(text): + nxt = len(s) + j = 0 + if s[j] == text[i]: + while j < len(s): + if s[j] != text[i-j]: + break + j += 1 + if j == len(s): + result = 1 + else: + while j < len(s): + if s[j] == text[i]: + nxt = min(j, nxt) + break + j += 1 + if result: + break + i += nxt + +print(result) + + +# 고지식한 패턴검색 알고리즘 = Brute Force. 텍스트의 모든 위치에서 패턴비교 O(MN) + +# KMP 알고리즘. 불일치 발생한 앞부분 대해 다시 비교하지 않고 매칭 수행 O(M+N)=O(N) +# next 배열을 생성해 불일치 발생하면 이동할 다음위치 저장. +# 패턴 왼쪽에서 오른쪽으로 비교 + +# 보이어 무어 알고리즘. 앞부분보다 끝부분가서 불일치 일어날 확률이 높다는 것 이용 +# 일반적으로는 O(N) 보다 적은 수행시간. 최악일땐 O(MN) +# skip 배열 생성해서 일치하는 칸으로 몇칸 이동해야하는지 저장 +# 패턴 오른쪽에서 왼쪽으로 비교. + +# 그러면 3가지 패턴매칭 알고리즘을 비교해보자. M은 패턴의 길이, N은 텍스트의 길이 +# Brute Force(=고지식한 패턴검색 알고리즘) +# 텍스트의 모든 위치에서 패턴 비교하고 한칸씩 이동한다. +# 시간복잡도 O(MN) +# KMP +# 불일치 발생한 앞부분에 대해 다시 비교하지 않고 매칭 수행 +# next배열을 생성해 불일치 발생하면 이동할 다음 위치 저장 +# 패턴의 왼쪽에서 오른쪽으로 비교 +# 시간복잡도 O(M+N) = O(N) +# 보이어무어 +# 앞부분보다 끝부분가서 불일치 일어날 확률이 높다는 것 이용 +# skip 배열 생성해서 일치하는 칸으로 몇 칸 이동해야하는지 저장 +# 패턴의 오른쪽에서 왼쪽으로 비교 +# 상용화된 제품이나 서비스에 가장 많이 적용됨 # 시간복잡도 일반적으로 O(N) 이하. 최학일땐 O(MN) \ No newline at end of file diff --git a/possible_grades.py b/possible_grades.py deleted file mode 100644 index f03f741..0000000 --- a/possible_grades.py +++ /dev/null @@ -1,22 +0,0 @@ - -for test_case in range(1,int(input())+1): - N = int(input()) - student = [] - for _ in range(N): - s,d = map(int,input().split()) - student.append([s,d]) - student = sorted(student,key = lambda a : a[0]) - student = sorted(student,key = lambda a : a[1]) - check = [0]*N - cnt = 0 - while sum(check) != N: - last = 0 - for i in range(N): - if student[i][0] >= last and check[i] ==0: - last = student[i][1] - check[i] = 1 - cnt+=1 - print("#{} {}".format(test_case, cnt)) - - - diff --git a/priority.queue.py b/priority.queue.py deleted file mode 100644 index 3475d48..0000000 --- a/priority.queue.py +++ /dev/null @@ -1,24 +0,0 @@ -import heapq -import sys - - -N = int(input()) -cards =[] -times = 0 - -for _ in range(N): - heapq.heappush(cards,int(sys.stdin.readline())) - - -if len(cardes) == 1: - print(0) -else: - while len(cards) > 1: - card1 = heapq.heappop(cards) - card2 = heapq.heappop(cards) - times += card1 + card2 - heapq.heappush(cards,card1+card2) - - -print(times) - diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 N\354\247\204\354\210\230 \352\262\214\354\236\204.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 N\354\247\204\354\210\230 \352\262\214\354\236\204.py" deleted file mode 100644 index a20d4e8..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 N\354\247\204\354\210\230 \352\262\214\354\236\204.py" +++ /dev/null @@ -1,23 +0,0 @@ -def solution(n, t, m, p): - answer = '' - parse_table = {i: hex(i)[2:].upper() for i in range(16)} - p -= 1 - tmp = '0' - num = 1 - while len(tmp) < p + t * m: - k = 1 - while num >= k: - k *= n - k //= n - now = num - while k: - a = now // k - tmp += parse_table[a] - now -= a * k - k //= n - num += 1 - for i in range(p, p + t * m, m): - answer+= tmp[i] - return answer - -print(solution(16, 16, 2, 1)) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \353\211\264\354\212\244 \355\201\264\353\237\254\354\212\244\355\204\260\353\247\201.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \353\211\264\354\212\244 \355\201\264\353\237\254\354\212\244\355\204\260\353\247\201.py" deleted file mode 100644 index 0443a72..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \353\211\264\354\212\244 \355\201\264\353\237\254\354\212\244\355\204\260\353\247\201.py" +++ /dev/null @@ -1,17 +0,0 @@ -def make_set(s): - a = set() - for i in range(len(s) - 1): - now = s[i:i+2] - if now.isalpha(): - while now in a: - now += '1' - a.add(now) - return a - -def solution(str1, str2): - str1, str2 = str1.lower(), str2.lower() - a = make_set(str1) - b = make_set(str2) - if not a | b: - return 65536 - return len(a & b) * 65536 // len(a | b) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \353\260\251\352\270\210\352\267\270\352\263\241.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \353\260\251\352\270\210\352\267\270\352\263\241.py" deleted file mode 100644 index fa1aa07..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \353\260\251\352\270\210\352\267\270\352\263\241.py" +++ /dev/null @@ -1,27 +0,0 @@ -parse_set = {'C#': 'a', 'D#': 'b', 'F#': 'c', 'G#': 'd', 'A#': 'e', 'E#': 'k'} - -def parse_scale(music): - parsed = [] - for idx in range(len(music)): - if music[idx] == '#': - parsed.append(parse_set[parsed.pop()+music[idx]]) - else: - parsed.append(music[idx]) - return ''.join(parsed) - -def make_time(time): - a, b = time.split(':') - return int(a) * 60 + int(b) - -def solution(m, musicinfos): - answer, play_time = '', 0 - m = parse_scale(m) - for play in musicinfos: - start, end, title, music = play.split(',') - start, end, music = make_time(start), make_time(end), parse_scale(music) - length, total_length = len(music), end - start - music = music * (total_length // length) + music[:total_length % length] - if play_time < total_length and m in music: - answer = title - play_time = total_length - return answer if answer else '(None)' \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \354\272\220\354\213\234.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \354\272\220\354\213\234.py" deleted file mode 100644 index 1259da0..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \354\272\220\354\213\234.py" +++ /dev/null @@ -1,14 +0,0 @@ -def solution(cacheSize, cities): - cache = [] - total_cost = 0 - for city in cities: - lo_city = city.lower() - if lo_city not in cache: - cache.append(lo_city) - total_cost += 5 - if len(cache) > cacheSize: - cache.pop(0) - else: - cache.append(cache.pop(cache.index(lo_city))) - total_cost += 1 - return total_cost \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \355\214\214\354\235\274\353\252\205\354\240\225\353\240\254.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \355\214\214\354\235\274\353\252\205\354\240\225\353\240\254.py" deleted file mode 100644 index 84052d4..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \355\214\214\354\235\274\353\252\205\354\240\225\353\240\254.py" +++ /dev/null @@ -1,23 +0,0 @@ -from heapq import heappop, heappush - -def solution(files): - answer = [] - sort_arr = [] - for pos, each_file in enumerate(files): - tmp = each_file + 'f' - flag = 0 - for idx, char in enumerate(tmp): - if not flag and char.isdigit(): - start = idx - flag = 1 - elif flag and not char.isdigit(): - end = idx - break - head, number = each_file[:start], each_file[start:end] - heappush(sort_arr, (head.lower(), int(number), pos)) - while sort_arr: - h, n, p = heappop(sort_arr) - answer.append(files[p]) - return answer - -print(solution(["img12.png", "img10.png", "img02.png", "img1.png", "IMG01.GIF", "img2.JPG"])) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \355\224\204\353\240\214\354\246\2104\353\270\224\353\241\235.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \355\224\204\353\240\214\354\246\2104\353\270\224\353\241\235.py" deleted file mode 100644 index 82a34e2..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/KAKAO 2018 \355\224\204\353\240\214\354\246\2104\353\270\224\353\241\235.py" +++ /dev/null @@ -1,31 +0,0 @@ - -def bomb_block(b, m, n): - block = set() - for i in range(m - 1): - for j in range(n - 1): - if b[i][j] and b[i][j] == b[i][j + 1] == b[i + 1][j] == b[i + 1][j + 1]: - for dx, dy in [(0, 0), (1, 0), (0, 1), (1, 1)]: - nx, ny = i + dx, j + dy - block.add((nx, ny)) - if not block: - return 0, 0 - for x, y in block: - b[x][y] = 0 - new_board = [[0] * n for _ in range(m)] - for j in range(n): - idx = m - 1 - for i in range(m - 1, -1, -1): - if b[i][j]: - new_board[idx][j] = b[i][j] - idx -= 1 - return new_board, len(block) - -def solution(m, n, board): - board = [list(row) for row in board] - count = 0 - while board: - board, cnt = bomb_block(board, m, n) - count += cnt - return count - -print(solution(4, 5, ["CCBDE", "AAADE", "AAABF", "CCBBF"])) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/kakao 2018 \354\225\225\354\266\225.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/kakao 2018 \354\225\225\354\266\225.py" deleted file mode 100644 index 44d0251..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/kakao 2018 \354\225\225\354\266\225.py" +++ /dev/null @@ -1,19 +0,0 @@ -def solution(msg): - msg += '.' - answer = [] - dic = {chr(i + ord('A')): i + 1 for i in range(26)} - idx, last_idx = 0, len(msg) - 1 - new_hash = 27 - while idx < last_idx: - start = msg[idx] - while idx < last_idx and start in dic: - idx += 1 - start += msg[idx] - answer.append(dic[start[:-1]]) - dic[start] = new_hash - new_hash += 1 - - return answer - - -print(solution('KAKAO')) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\353\211\264\354\212\244\355\201\264\353\237\254\354\212\244\355\204\260\353\247\201.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\353\211\264\354\212\244\355\201\264\353\237\254\354\212\244\355\204\260\353\247\201.py" deleted file mode 100644 index f2c18be..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\353\211\264\354\212\244\355\201\264\353\237\254\354\212\244\355\204\260\353\247\201.py" +++ /dev/null @@ -1,33 +0,0 @@ -from collections import Counter - -def solution(str1, str2): - str1 = str1.lower() - str2 = str2.lower() - - str1_elements_set = [] - str2_elements_set = [] - # 두글자씩 끊어 원소집합으로 만듦(둘다 알파뱃일 경우만.) - for i in range(len(str1)-1): - if str1[i].isalpha() and str1[i+1].isalpha(): - str1_elements_set.append(str1[i] + str1[i+1]) - for j in range(len(str2)-1): - if str2[j].isalpha() and str2[j+1].isalpha(): - str2_elements_set.append(str2[j] + str2[j+1]) - # 각 원소 집합에 대해 카운터 객체 생성. - Counter1 = Counter(str1_elements_set) - Counter2 = Counter(str2_elements_set) - # 교집합(양쪽 다 원소의 갯수가 같은만큼만 원소추출) - inter_strs = list((Counter1 & Counter2).elements()) - # 합집합(모든 원소) - union_strs = list((Counter1 | Counter2).elements()) - # 유사도는 교집합 크기/합집합 크기 * 65536 의 소숫점 버림. - # ex - # Counter({'aa': 2}) Counter({'aa': 3}) - # ['aa', 'aa'] ['aa', 'aa', 'aa'] - # 43690 - if len(union_strs) == 0 and len(inter_strs) == 0: - return 65536 - else: - return int(len(inter_strs) / len(union_strs) * 65536) - -print(solution('aa1+aa2','AAAA12')) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\205\224\355\213\200\353\262\204\354\212\244.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\205\224\355\213\200\353\262\204\354\212\244.py" deleted file mode 100644 index cdfa047..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\205\224\355\213\200\353\262\204\354\212\244.py" +++ /dev/null @@ -1,18 +0,0 @@ -def solution(n, t, m, timetable): - answer = 0 - crewTime = [int(time[:2])*60 + int(time[3:]) for time in timetable] - crewTime.sort() - busTime = [9*60 + t*i for i in range(n)] - idx = 0 - for bus_stop in busTime: - cnt = 0 - while cnt < m and idx < len(crewTime) and crewTime[idx] <= bus_stop: - idx += 1 - cnt += 1 - if cnt < m: - answer = bus_stop - else: - answer = crewTime[idx - 1] - 1 - return str(answer//60).zfill(2) + ":" + str(answer%60).zfill(2) - -print(solution(1,1,5,["08:00", "08:01", "08:02", "08:03"])) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\266\224\354\204\235\355\212\270\353\236\230\355\224\275.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\266\224\354\204\235\355\212\270\353\236\230\355\224\275.py" deleted file mode 100644 index d86b8a9..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\266\224\354\204\235\355\212\270\353\236\230\355\224\275.py" +++ /dev/null @@ -1,51 +0,0 @@ - - -def get_times(log): - temp = log.split(" ") - end_time = temp[1].split(':') - end_time = int(end_time[0]) * 3600000 + int(end_time[1]) * 60000 + int(end_time[2].replace('.', '')) - start_time = end_time - int(float(temp[2].replace('s', ''))*1000) + 1 - return (start_time, end_time) if start_time > 0 else (0, end_time) - - -def solution(lines): - answer = 0 - total_times = [] - for i in range(len(lines)): - start_time, end_time = get_times(lines[i]) - total_times.append((start_time, end_time, i)) - - for i in range(len(total_times)): - count = 1 - end_time = total_times[i][1] - for j in range(len(total_times)): - if i == j: - continue - t_start_time = total_times[j][0] - t_end_time = total_times[j][1] - if t_start_time >= end_time and t_start_time < end_time + 1000: - count += 1 - elif t_end_time >= end_time and t_end_time < end_time + 1000: - count += 1 - elif end_time >= t_start_time and end_time + 1000 <= t_end_time: - count += 1 - if count > answer: - answer = count - - return answer - - - - -print(solution([ -"2016-09-15 20:59:57.421 0.351s", -"2016-09-15 20:59:58.233 1.181s", -"2016-09-15 20:59:58.299 0.8s", -"2016-09-15 20:59:58.688 1.041s", -"2016-09-15 20:59:59.591 1.412s", -"2016-09-15 21:00:00.464 1.466s", -"2016-09-15 21:00:00.741 1.581s", -"2016-09-15 21:00:00.748 2.31s", -"2016-09-15 21:00:00.966 0.381s", -"2016-09-15 21:00:02.066 2.62s" -])) \ No newline at end of file diff --git "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\272\220\354\213\234.py" "b/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\272\220\354\213\234.py" deleted file mode 100644 index c200eb1..0000000 --- "a/programmers/2018 \354\271\264\354\271\264\354\230\244/\354\271\264\354\271\264\354\230\244\352\270\260\354\266\2342018\354\272\220\354\213\234.py" +++ /dev/null @@ -1,35 +0,0 @@ - -def solution(cacheSize, cities): - cache = [] - total_cost = 0 - for city in cities: - lo_city = city.lower() - if lo_city not in cache: - cache.append(lo_city) - total_cost += 5 - if len(cache) > cacheSize: - cache.pop(0) - else: - cache.append(cache.pop(cache.index(lo_city))) - total_cost += 1 - return total_cost - -# 남의 풀이 -def solution(cacheSize, cities): - import collections - cache = collections.deque(maxlen=cacheSize) - time = 0 - for i in cities: - s = i.lower() - if s in cache: - cache.remove(s) - cache.append(s) - time += 1 - else: - cache.append(s) - time += 5 - return time - - - -print(solution(3,["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"])) \ No newline at end of file diff --git "a/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \354\213\244\355\214\250\354\234\250.py" "b/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \354\213\244\355\214\250\354\234\250.py" deleted file mode 100644 index cd8cb43..0000000 --- "a/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \354\213\244\355\214\250\354\234\250.py" +++ /dev/null @@ -1,16 +0,0 @@ -from bisect import bisect_left, bisect_right -from heapq import heappush, heappop - -def solution(N, stages): - answer = [] - stages = sorted(stages) - cnts = [] - for i in range(1, N + 1): - left = bisect_left(stages, i) - right = bisect_right(stages, i) - total = len(stages) - left - failure_rate = (right - left) / total if total else 0 - heappush(cnts, (-failure_rate, i)) - while cnts: - answer.append(heappop(cnts)[1]) - return answer \ No newline at end of file diff --git "a/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" "b/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" deleted file mode 100644 index 28def9b..0000000 --- "a/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" +++ /dev/null @@ -1,17 +0,0 @@ -def solution(record): - answer = [] - users = {} - for log in record: - command, *user = log.split() - if command == 'Enter' or command == 'Change': - user_id, nickname = user - users[user_id] = nickname - for log in record: - command, *user = log.split() - if command == 'Enter': - user_id, nickname = user - answer.append(f'{users[user_id]}님이 들어왔습니다.') - elif command == 'Leave': - answer.append(f'{users[user.pop()]}님이 나갔습니다.') - - return answer \ No newline at end of file diff --git "a/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \355\233\204\353\263\264\355\202\244.py" "b/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \355\233\204\353\263\264\355\202\244.py" deleted file mode 100644 index d98ce2c..0000000 --- "a/programmers/2019 \354\271\264\354\271\264\354\230\244/kakao 2019 \355\233\204\353\263\264\355\202\244.py" +++ /dev/null @@ -1,32 +0,0 @@ -from itertools import combinations - -def solution(relation): - n = len(relation[0]) - cnt = 0 - checked = set() - for i in range(1, n + 1): - for comb in combinations([k for k in range(n)], i): - dicts = set() - tmp = [] - for row in relation: - tmp.append(''.join(row[each] for each in comb)) - flag = 0 - for c in tmp: - if flag: break - if c not in dicts: - dicts.add(c) - else: - flag = 1 - break - if not flag: - flag = 0 - for i in range(1, len(comb)): - if flag: break - for com in combinations(list(comb), i): - if com in checked: - flag = 1 - break - if not flag: - checked.add(comb) - cnt += 1 - return cnt \ No newline at end of file diff --git "a/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2020 \352\264\204\355\230\270\353\263\200\355\231\230.py" "b/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2020 \352\264\204\355\230\270\353\263\200\355\231\230.py" deleted file mode 100644 index 4b4f300..0000000 --- "a/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2020 \352\264\204\355\230\270\353\263\200\355\231\230.py" +++ /dev/null @@ -1,32 +0,0 @@ -def solution(p): - if not p: - return p - n = len(p) - left, right = 0, 0 - for i in range(n): - if p[i] == '(': - left += 1 - else: - right += 1 - if left == right: - break - u = p[:i+1] - v = p[i+1:] - stack = [] - for char in u: - if char == '(': - stack.append(char) - else: - if stack: - stack.pop() - else: - new_u = u[1:-1] - tmp = '' - for char in new_u: - if char == '(': - tmp += ')' - else: - tmp += '(' - return '(' + solution(v) + ')' + tmp - else: - return u + solution(v) \ No newline at end of file diff --git "a/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2020 \353\254\270\354\236\220\354\227\264\354\225\225\354\266\225.py" "b/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2020 \353\254\270\354\236\220\354\227\264\354\225\225\354\266\225.py" deleted file mode 100644 index 2fab1f0..0000000 --- "a/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2020 \353\254\270\354\236\220\354\227\264\354\225\225\354\266\225.py" +++ /dev/null @@ -1,20 +0,0 @@ -# git commit -m "code: Solve programmers 문자열 압축 (seungjoo)" -def solution(s): - n = len(s) - answer = n - for unit in range(1, n//2 + 1): - cnt = 1 - now = s[:unit] - tmp_answer = '' - for i in range(unit, n + unit, unit): - if s[i:i + unit] == now: - cnt += 1 - else: - if cnt > 1: - tmp_answer += str(cnt) + now - else: - tmp_answer += now - now = s[i:i + unit] - cnt = 1 - answer = min(answer, len(tmp_answer)) - return answer \ No newline at end of file diff --git "a/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2021 \354\210\234\354\234\204\352\262\200\354\203\211.py" "b/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2021 \354\210\234\354\234\204\352\262\200\354\203\211.py" deleted file mode 100644 index 91f1922..0000000 --- "a/programmers/2020 \354\271\264\354\271\264\354\230\244/kakao 2021 \354\210\234\354\234\204\352\262\200\354\203\211.py" +++ /dev/null @@ -1,59 +0,0 @@ -# from collections import defaultdict -# from bisect import bisect_left - -# def solution(info, query): -# answer = [] -# lang_set = defaultdict(set) -# job_set = defaultdict(set) -# stat_set = defaultdict(set) -# food_set = defaultdict(set) -# score_set = {} -# for idx, each in enumerate(info): -# lang, job, stat, food, score = each.split() -# lang_set[lang].add(idx) -# job_set[job].add(idx) -# stat_set[stat].add(idx) -# food_set[food].add(idx) -# score_set[idx] = int(score) -# for each in query: -# lang, job, stat, last = each.split(' and ') -# food, score = last.split() -# pivot = set([i for i in range(len(info))]) -# if lang != '-': -# pivot &= lang_set[lang] -# if job != '-': -# pivot &= job_set[job] -# if stat != '-': -# pivot &= stat_set[stat] -# if food != '-': -# pivot &= food_set[food] -# tmp = sorted([score_set[idx] for idx in pivot]) -# left = bisect_left(tmp, int(score)) -# answer.append(len(tmp) - left) -# return answer - -from collections import defaultdict -from bisect import bisect_left - -def solution(info, query): - score_set = defaultdict(list) - answer = [] - for each in info: - lang, job, stat, food, score = each.split() - for l in (lang, '-'): - for j in (job, '-'): - for s in (stat, '-'): - for f in (food, '-'): - score_set[(l, j, s, f)] += [int(score)] - - for value in score_set.values(): - value.sort() - - for each in query: - lang, job, stat, last = each.split(' and ') - food, score = last.split() - target_set = score_set[(lang, job, stat, food)] - index = bisect_left(target_set, int(score)) - answer.append(len(target_set) - index) - - return answer \ No newline at end of file diff --git "a/programmers/2021 \354\271\264\354\271\264\354\230\244\354\261\204\354\232\251\354\227\260\352\263\204/\352\261\260\353\246\254\353\221\220\352\270\260 \355\231\225\354\235\270\355\225\230\352\270\260.py" "b/programmers/2021 \354\271\264\354\271\264\354\230\244\354\261\204\354\232\251\354\227\260\352\263\204/\352\261\260\353\246\254\353\221\220\352\270\260 \355\231\225\354\235\270\355\225\230\352\270\260.py" deleted file mode 100644 index ea6aa81..0000000 --- "a/programmers/2021 \354\271\264\354\271\264\354\230\244\354\261\204\354\232\251\354\227\260\352\263\204/\352\261\260\353\246\254\353\221\220\352\270\260 \355\231\225\354\235\270\355\225\230\352\270\260.py" +++ /dev/null @@ -1,32 +0,0 @@ - -delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) - -def is_check(place): - q = [] - for i in range(5): - for j in range(5): - if place[i][j] == 'P': - q.append((i, j, 0, set())) - while q: - x, y, dist, visited = q.pop() - visited.add((x, y)) - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < 5 and 0 <= ny < 5 and (nx, ny) not in visited: - if place[nx][ny] == 'X': - continue - elif place[nx][ny] == 'O': - if dist < 2: - q.append((nx, ny, dist + 1, visited)) - else: - if dist < 2: - return False - return True - - -def solution(places): - answer = [] - for place in places: - ret = 1 if is_check(place) else 0 - answer.append(ret) - return answer \ No newline at end of file diff --git "a/programmers/2021 \354\271\264\354\271\264\354\230\244\354\261\204\354\232\251\354\227\260\352\263\204/\355\221\234 \355\216\270\354\247\221.py" "b/programmers/2021 \354\271\264\354\271\264\354\230\244\354\261\204\354\232\251\354\227\260\352\263\204/\355\221\234 \355\216\270\354\247\221.py" deleted file mode 100644 index 7a4d501..0000000 --- "a/programmers/2021 \354\271\264\354\271\264\354\230\244\354\261\204\354\232\251\354\227\260\352\263\204/\355\221\234 \355\216\270\354\247\221.py" +++ /dev/null @@ -1,40 +0,0 @@ - -from heapq import heappop, heappush - -def solution(n, k, cmd): - left, right, delete = [-i for i in range(k-1, -1, -1)], [i for i in range(k, n)], [] - for command in cmd: - c, *num = command.split() - if c == 'U': - cnt = int(num.pop()) - for _ in range(cnt): - heappush(right, -heappop(left)) - elif c == 'D': - cnt = int(num.pop()) - for _ in range(cnt): - heappush(left, -heappop(right)) - elif c == 'C': - delete.append(heappop(right)) - if not right: - heappush(right, -heappop(left)) - else: - now = delete.pop() - if now > right[0]: - heappush(right, now) - else: - heappush(left, -now) - answer, idx = '', 0 - while left: - heappush(right, -heappop(left)) - while right: - now = heappop(right) - while idx != now: - idx += 1 - answer += 'X' - answer += 'O' - idx += 1 - while idx != n: - answer += 'X' - idx += 1 - return answer - \ No newline at end of file diff --git "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_1.py" "b/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_1.py" deleted file mode 100644 index 44ffaad..0000000 --- "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_1.py" +++ /dev/null @@ -1,24 +0,0 @@ - - -def solution(id_list, report, k): - user_list = {user: [0,[]] for user in id_list} - mail_cnt = {user: 0 for user in id_list} - # 각 유저 한번에 한명 신고 가능. 한 유저 여러번 신고 가능하나 명당 1번 카운트. - for repo in report: - a, b = repo.split() - if a not in user_list[b][1]: - user_list[b][1].append(a) - user_list[b][0] += 1 - for user in user_list: - if user_list[user][0] >= k: - for send_mail in user_list[user][1]: - mail_cnt[send_mail] += 1 - answer = [] - for mail in mail_cnt: - answer.append(mail_cnt[mail]) - return answer - # k번 신고되면 게시판 정지. 해당 유저 신고한 모든 유저에게 정지사실을 메일로 발송. - # 정지 돼도 신고 가능. - - -print(solution(["muzi", "frodo", "apeach", "neo"],["muzi frodo","apeach frodo","frodo neo","muzi neo","apeach muzi"],2)) \ No newline at end of file diff --git "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_2.py" "b/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_2.py" deleted file mode 100644 index 90d184a..0000000 --- "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_2.py" +++ /dev/null @@ -1,28 +0,0 @@ - - -def is_prime(n): - if n <= 1: - return False - m = int(n**0.5)+1 - for i in range(2,m): - if not n%i: - return False - return True - - -def solution(n, k): - # 정수 n을 k진수로 바꿨을 때 - # 소수 양쪽에 0, 한쪽에만 0, 양쪽에 아무것도 없는 경우, 단 소수는 0을 포함하지 않는 소수. - # ex) 437674를 3진수? -> 211020101011여기서 찾을 수 있는 소수 211 2 11 소수의 갯수를 return - answer = '' - while n: - n, b = n//k, n%k - answer = str(b) + answer - cnt = 0 - for num in answer.split('0'): - if num and is_prime(int(num)): - cnt += 1 - return cnt - - -print(solution(437674,3)) \ No newline at end of file diff --git "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_3.py" "b/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_3.py" deleted file mode 100644 index c21ae42..0000000 --- "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_3.py" +++ /dev/null @@ -1,41 +0,0 @@ -from collections import defaultdict -from math import ceil -def solution(fees, records): - count_dict = defaultdict(str) - total_time = defaultdict(int) - answer = [] - for record in records: - time, car_id, command = record.split() - if not count_dict[car_id]: - count_dict[car_id] = time - else: - hour, minute = map(int, count_dict[car_id].split(':')) - parse_start_min = hour*60 + minute - hour, minute = map(int, time.split(':')) - parse_end_min = hour*60 + minute - use_time = parse_end_min - parse_start_min - total_time[car_id] += use_time - del(count_dict[car_id]) - - for car_id in count_dict: - hour, minute = map(int, count_dict[car_id].split(':')) - parse_start_min = hour*60 + minute - last_time = 23*60 + 59 - use_time = last_time - parse_start_min - total_time[car_id] += use_time - - for car_id in total_time: - if total_time[car_id] <= fees[0]: - answer.append([int(car_id),fees[1]]) - else: - answer.append([int(car_id), ceil((total_time[car_id] - fees[0])/fees[2])*fees[3] + fees[1]]) - - answer.sort() - answer = list(map(list, zip(*answer)))[1] - - return answer - - - - -print(solution([180, 5000, 10, 600],["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"])) diff --git "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_4.py" "b/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_4.py" deleted file mode 100644 index 893f1df..0000000 --- "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_4.py" +++ /dev/null @@ -1,44 +0,0 @@ - -def check_winner(hit): - lion_cnt = 0 - apeach_cnt = 0 - for i in range(11): - if hit[i] > apeach_info[i]: - lion_cnt += 10-i - elif apeach_info[i]: - apeach_cnt += 10-i - return lion_cnt - apeach_cnt - - - -def dfs(cnt,target,hit): - global max_gap,answer - if cnt==target: - gap = check_winner(hit) - if max_gap < gap: - max_gap = gap - answer = hit[:] - return - for i in range(11): - hit[i] += 1 - gap = check_winner(hit) - dfs(cnt+1,target,hit) - hit[i] -= 1 - - -def solution(n, info): - global max_gap,apeach_info,answer - # 가장 큰 점수차로 라이언이 이겨야함. - # 총 n발. - # info는 10점부터 0점까지 맞춘 숫자의 counter - # 라이언이 이길수 없는(지거나 비기면 [-1]리턴.) - # 가장 큰 점수차를 만들 방법이 여러가지 안경우 낮은 점수를 더 많이 맞춘 경우를 return - apeach_info = info - lion_info = [0,0,0,0,0,0,0,0,0,0,0] - max_gap = -float('inf') - answer = [] - dfs(0,n,lion_info) - return answer if max_gap > 0 else [-1] - - -print(solution(5,[2,1,1,1,0,0,0,0,0,0,0])) \ No newline at end of file diff --git "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_5.py" "b/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_5.py" deleted file mode 100644 index 214275b..0000000 --- "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_5.py" +++ /dev/null @@ -1,37 +0,0 @@ -from collections import deque - - -def bfs(start,n,info,graph): - queue = deque() - queue.append([start,1,0,1]) - max_sheep = 1 - next_time = [] - while queue: - cur_node, sheep, wolf,visited = queue.popleft() - if sheep > max_sheep: - max_sheep = sheep - for i in range(n): - if visited & (1< wolf + info[next_node]: - if info[next_node]: - queue.append([next_node, sheep, wolf+1,visited|(1< 0: answer += 1 - - return answer \ No newline at end of file diff --git "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_7.py" "b/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_7.py" deleted file mode 100644 index 46421ac..0000000 --- "a/programmers/2022 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/\354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\2342022_7.py" +++ /dev/null @@ -1,47 +0,0 @@ -from collections import deque -from copy import deepcopy - -def solution(board, aloc, bloc): - # 각 플레이어 캐릭터 하나씩 - # 각 격자는 발판이 있거나 없거나 - # 이동 시 밟고 있던 발판은 사라짐. - # 움직일 차례인데 상하좌우 못움직이면 해당 플레이어 패배. - # 같은 발판인데 상대가 먼저 움직여 발판이 사라지면 패배 - # A먼저 시작. 최적의 플레이. - N = len(board) - M = len(board[0]) - dx = [0,0,-1,1] - dy = [1,-1,0,0] - queue = deque() - ax,ay = aloc - bx,by = bloc - if ax==bx and ay==by: - return 0 - min_cnt = float('inf') - queue.append([ax,ay,bx,by,board,0]) - while queue: - ax,ay,bx,by,new_board,cnt = queue.popleft() - tmp = deepcopy(new_board) - flag_x = 0 - for i in range(4): - nax = ax + dx[i] - nay = ay + dy[i] - if 0<=nax deliveries[idx]: - tmp_d -= deliveries[idx] - elif tmp_d == deliveries[idx]: - tmp_d -= deliveries[idx] - else: - while deliveries[idx]: - deliveries[idx] -= tmp_d - if deliveries[idx] > tmp_d: - d_turn.append(idx) - tmp_d = cap - if pickups[idx]: - if tmp_p == cap: - p_turn.append(idx) - if tmp_p > pickups[idx]: - tmp_p -= pickups[idx] - elif tmp_p == pickups[idx]: - tmp_p -= pickups[idx] - else: - while pickups[idx]: - pickups[idx] -= tmp_p - if pickups[idx] > tmp_p: - p_turn.append(idx) - tmp_p = cap - max_length = min(p_turn, d_turn) - for i in range(max_length): - answer += 2 * max(p_turn[i], d_turn[i]) - - - return answer -print(solution(4, 5, [1, 0, 3, 1, 2], [0, 3, 0, 4, 0])) \ No newline at end of file diff --git "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/3.py" "b/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/3.py" deleted file mode 100644 index c1d7d45..0000000 --- "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/3.py" +++ /dev/null @@ -1,30 +0,0 @@ -def solution(users, emoticons): - global max_cnt, max_buying - max_cnt, max_buying = 0, 0 - - def dfs(depth, comb_percents): - global max_cnt, max_buying - if depth == len(emoticons): - cnt = 0 - total_buying = 0 - for user in users: - buying = 0 - for idx, percent in enumerate(comb_percents): - if user[0] <= percent: - buying += (emoticons[idx] * (100 - percent)) // 100 - if buying >= user[1]: - cnt += 1 - else: - total_buying += buying - if cnt > max_cnt: - max_cnt = cnt - max_buying = total_buying - elif cnt == max_cnt and total_buying > max_buying: - max_buying = total_buying - return - for percent in [10, 20, 30, 40]: - dfs(depth + 1, comb_percents + [percent]) - - dfs(0, []) - return [max_cnt, max_buying] -print(solution([[40, 10000], [25, 10000]], [7000, 9000])) \ No newline at end of file diff --git "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/4.py" "b/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/4.py" deleted file mode 100644 index 69e50d6..0000000 --- "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/4.py" +++ /dev/null @@ -1,34 +0,0 @@ -def solution(numbers): - answer = [] - bin_numbers = [] - for number in numbers: - bin_numbers.append(bin(number)[2:]) - - def dfs(num, idx, level, start, end, key): - if level == 0: - return True - if key and num[idx] == '1': - return False - if num[idx] == '0': - key = 1 - if dfs(num, (idx + start) // 2, level - 1, start, idx, key) and dfs(num, (idx + end) // 2, level - 1, idx, end, key): - return True - return False - - for number in bin_numbers: - k = len(number) - cnt = 0 - while k: - k //= 2 - cnt += 1 - number = '0' * (2**cnt - 1 - len(number)) + number - # 모든 리프노드가 0이면 x - # dfs 타다가 0나오면 쭉 타다가 1나오면 안됨. 0나오고 1나오면 안됨. - if dfs(number, len(number) // 2, cnt, -1, len(number), 0): - answer.append(1) - continue - answer.append(0) - - return answer - -print(solution([15, 58, 63, 111, 95, 14, 42, 10, 104])) \ No newline at end of file diff --git "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/5.py" "b/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/5.py" deleted file mode 100644 index 5793269..0000000 --- "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/5.py" +++ /dev/null @@ -1,4 +0,0 @@ -def solution(commands): - answer = [] - return answer -print(solution([15, 58, 63, 111, 95, 14])) \ No newline at end of file diff --git "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/6.py" "b/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/6.py" deleted file mode 100644 index 4e5e92d..0000000 --- "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/6.py" +++ /dev/null @@ -1,40 +0,0 @@ -from collections import deque - -def solution(n, m, x, y, r, c, k): - answer = '' - min_dist = abs(r-x) + abs(c-y) - if min_dist > k or (k - min_dist) & 1: - return 'impossible' - answer = '' - if r > x: - answer += 'd' * (r - x) - k -= (r - x) - if c < y: - answer += 'l' * (y - c) - k -= (y - c) - if c > y: - answer += 'r' * (c - y) - k -= (c - y) - if r < x: - answer += 'u' * (x - r) - k -= (x - r) - if k: - for idx, char in enumerate(answer): - if char == 'u': - if idx == 0: - if x == n - 1: - answer = answer[:1] + 'du' * (k // 2) + answer[1:] - else: - answer = 'du' * (k // 2) + answer - else: - if x == n - 1: - if y == 0: - answer = answer[:1] + 'lr' * (k // 2) + answer[1:] - else: - answer = 'du' * (k // 2) + answer[idx:] - - - - return answer - -print(solution(3, 4, 2, 3, 3, 1, 5)) \ No newline at end of file diff --git "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/7.py" "b/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/7.py" deleted file mode 100644 index 7d48836..0000000 --- "a/programmers/2023 \354\271\264\354\271\264\354\230\244\353\270\224\353\235\274\354\235\270\353\223\234/7.py" +++ /dev/null @@ -1,4 +0,0 @@ -def solution(edges, target): - answer = [] - return answer -print(solution([15, 58, 63, 111, 95, 14])) \ No newline at end of file diff --git a/programmers/uplus2022/1.py b/programmers/uplus2022/1.py deleted file mode 100644 index 913f443..0000000 --- a/programmers/uplus2022/1.py +++ /dev/null @@ -1,9 +0,0 @@ -def solution(arr): - anagrams = set() - for num in arr: - counter = [0] * 10 - for char in str(num): - counter[int(char)] += 1 - anagrams.add(tuple(counter)) - - return len(anagrams) \ No newline at end of file diff --git a/programmers/uplus2022/2.py b/programmers/uplus2022/2.py deleted file mode 100644 index ef665d1..0000000 --- a/programmers/uplus2022/2.py +++ /dev/null @@ -1,23 +0,0 @@ -def solution(compressed): - number = {str(i) for i in range(10)} - alphas = {chr(i) for i in range(97, 123)} - nums = [] - words = [''] - tmp_n = [] - for char in compressed: - if char in number: - if not tmp_n: - words.append('') - tmp_n.append(char) - elif char == '(': - nums.append(int(''.join(tmp_n))) - tmp_n = [] - elif char in alphas: - words.append(words.pop() + char) - else: - tmp = '' - for _ in range(len(words) - len(nums)): - tmp += words.pop() - words.append(tmp * nums.pop()) - return ''.join(words) -print(solution('xxx2(3(hi)co)')) \ No newline at end of file diff --git a/programmers/uplus2022/3.py b/programmers/uplus2022/3.py deleted file mode 100644 index e69de29..0000000 diff --git a/programmers/uplus2022/4.py b/programmers/uplus2022/4.py deleted file mode 100644 index e69de29..0000000 diff --git "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programers.py" "b/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programers.py" deleted file mode 100644 index 4da3122..0000000 --- "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programers.py" +++ /dev/null @@ -1,16 +0,0 @@ -# 완주하지 못한 선수 - -def solution(participant, completion): hash ={} for i in participant: if i in hash: hash[i] += 1 else: hash[i] = 1 for i in completion: if hash[i] == 1: del hash[i] else: hash[i] -= 1 answer = list(hash.keys())[0] return answer - -# 전화번호 목록 - -def solution(phone_book): answer = True finish = False phone_book = sorted(phone_book, key=len) for i in range(0, len(phone_book)): if finish: break current = phone_book[i] for j in range(i+1, len(phone_book)): comp = phone_book[j] if len(current)= 90: result += 'A' - elif mean >= 80: result += 'B' - elif mean >= 70: result += 'C' - elif mean >= 50: result += 'D' - else: result += 'F' - return result - - -# .풀이 2 -solution = lambda scores: "".join(map(lambda m: "FDDCBAA"[max(int(sum(m) / len(m) / 10) - 4, 0)], map(lambda m: (m[0], *m[1]) if min(m[1]) <= m[0] <= max(m[1]) else m[1], ((s[i], s[:i] + s[i+1:]) for i, s in enumerate(zip(*scores)))))) - - -# 풀이3 -def solution(scores) : - - avgs=[] - - score=[ [i[j] for i in scores] for j in range(len(scores))] - - for idx,i in enumerate(score) : - - avg=sum(i) ; length=len(i) - - if i[idx] == max(i) or i[idx] == min(i) : - - if i.count(i[idx]) == 1 : - - avg-=i[idx] ; length-=1 - - avgs.append(avg/length) - - return "".join([ avg>=90 and "A" or avg>=80 and "B" or avg>=70 and "C" or avg>=50 and "D" or "F" for avg in avgs ]) - - -# 풀이 4 -def solution(scores): - answer = '' - - for i, score in enumerate(zip(*scores)): - avg = (sum(score) - score[i]) / (len(score) - 1) if score[i] in (min(score), max(score)) and score.count(score[i]) == 1 else sum(score) / len(score) - answer += "%s" % ( - "A" if 90 <= avg else - "B" if 80 <= avg else - "C" if 70 <= avg else - "D" if 50 <= avg else - "F" - ) - - return answer - - diff --git "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programmers \355\215\274\354\246\220\354\241\260\352\260\201\354\261\204\354\232\260\352\270\260 copy.py" "b/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programmers \355\215\274\354\246\220\354\241\260\352\260\201\354\261\204\354\232\260\352\270\260 copy.py" deleted file mode 100644 index 01fb29d..0000000 --- "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programmers \355\215\274\354\246\220\354\241\260\352\260\201\354\261\204\354\232\260\352\270\260 copy.py" +++ /dev/null @@ -1,83 +0,0 @@ -from collections import defaultdict, deque - -def solution(game_board, table): - answer = 0 - - n = len(game_board) - delta = ((-1, 0), (0, 1), (1, 0), (0, -1)) - - def bfs(graph, start_x, start_y, num): - ret = [(0, 0)] - q = deque() - q.append((start_x, start_y, 0, 0)) - graph[start_x][start_y] = -1 - while q: - x, y, pre_x, pre_y = q.popleft() - for dx, dy in delta: - nx, ny, n_pre_x, n_pre_y = x + dx, y + dy, pre_x + dx, pre_y + dy - if 0 <= nx < n and 0 <= ny < n and graph[nx][ny] == num: - graph[nx][ny] = -1 - q.append((nx, ny, n_pre_x, n_pre_y)) - ret.append((n_pre_x, n_pre_y)) - return ret - # 빈칸 모양 찾기 - blanks = defaultdict(int) - for i in range(n): - for j in range(n): - if not game_board[i][j]: - game_board[i][j] = -1 - blanks[tuple(bfs(game_board, i, j, 0))] += 1 - - # 회전시켜 blanks 맞추기 - for _ in range(4): - table = [list(row)[::-1] for row in zip(*table)] - rotated_table = [row[:] for row in table] - - for i in range(n): - for j in range(n): - if rotated_table[i][j] == 1: - rotated_table[i][j] = -1 - block = tuple(bfs(rotated_table, i, j, 1)) - if block in blanks: - answer += len(block) - blanks[block] -= 1 - if not blanks[block]: - del blanks[block] - table = [row[:] for row in rotated_table] - else: - rotated_table = [row[:] for row in table] - return answer - - -print(solution( - [ - [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0], - [1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0], - [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0], - [1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1], - [0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0], - [0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1], - [0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0], - [0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0], - [1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0], - [0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1], - [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0] - ], - [ - [1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1], - [1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1], - [1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0], - [0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0], - [1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0], - [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], - [1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1], - [1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1], - [0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1], - [1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1], - [1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1], - [1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1] - - ] - ) - ) \ No newline at end of file diff --git "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programmers \355\215\274\354\246\220\354\241\260\352\260\201\354\261\204\354\232\260\352\270\260.py" "b/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programmers \355\215\274\354\246\220\354\241\260\352\260\201\354\261\204\354\232\260\352\270\260.py" deleted file mode 100644 index 71bb41e..0000000 --- "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/programmers \355\215\274\354\246\220\354\241\260\352\260\201\354\261\204\354\232\260\352\270\260.py" +++ /dev/null @@ -1,354 +0,0 @@ -import copy - -def solution(game_board, table): - answer = 0 - - n = len(game_board) - delta = ((0, 1), (1, 0), (-1, 0), (0, -1)) - - def dfs(graph, x, y, position, num): - ret = [position] - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < n and 0 <= ny < n and graph[nx][ny] == num: - graph[nx][ny] = 2 - ret += dfs(graph, nx, ny, [position[0] + dx, position[1] + dy], num) - return ret - - # 빈칸 찾기 - block = [] - for i in range(n): - for j in range(n): - if not game_board[i][j]: - game_board[i][j] = 1 - result = dfs(game_board, i, j, [0, 0], n, 0)[1:] - block.append(result) - - # 회전시켜 block 맞추기 - for rotation in range(4): - rotated_table = [list(row)[::-1] for row in zip(*table)] - - for i in range(n): - for j in range(n): - if rotated_table[i][j] == 1: - rotated_table[i][j] = 2 - result = dfs(rotated_table, i, j, [0, 0], n, 1)[1:] - if result in block: - block.pop(block.index(result)) - answer += (len(result) + 1) - table = copy.deepcopy(rotated_table) - else: - rotated_table = copy.deepcopy(table) - return answer - - - -# 2 -from collections import Counter -from dataclasses import dataclass -from itertools import product - - -@dataclass(frozen=True) -class Pos: - x: int - y: int - - def neighbors(self): - return [ - Pos(self.x, self.y - 1), - Pos(self.x + 1, self.y), - Pos(self.x, self.y + 1), - Pos(self.x - 1, self.y), - ] - - -def make_tile_from_positions(positions): - """Smallest possible representation with rotation""" - - def rotate90(tile): - return tuple( - tuple(tile[i][j] for i in range(len(tile))) - for j in reversed(range(len(tile[0]))) - ) - - positions = set(positions) - - xs = [pos.x for pos in positions] - min_x = min(xs) - max_x = max(xs) - - ys = [pos.y for pos in positions] - min_y = min(ys) - max_y = max(ys) - - tile_representations = [ - tuple( - tuple(Pos(i, j) in positions for j in range(min_y, max_y + 1)) - for i in range(min_x, max_x + 1) - ) - ] - - for __ in range(3): - tile_representations.append(rotate90(tile_representations[-1])) - - return min(tile_representations) - - -def get_tile_size(tile): - return sum(sum(row) for row in tile) - - -def parse_tiles(board, tile_value=1): - n = len(board) - - # Add sentinel boundaries - sentinel = 1 - tile_value - - board = [ - [sentinel] * (n + 2), - *([sentinel] + row + [sentinel] for row in board), - [sentinel] * (n + 2), - ] - - # Detect tiles - tile_positions = [] - for i, j in product(range(1, n + 1), range(1, n + 1)): - if board[i][j] == tile_value: - stack = [Pos(i, j)] - squares = [] - while stack: - curr = stack.pop() - board[curr.x][curr.y] = sentinel - squares.append(curr) - for neighbor in curr.neighbors(): - if board[neighbor.x][neighbor.y] == tile_value: - stack.append(neighbor) - tile_positions.append(squares) - - # Make tiles - tiles = [make_tile_from_positions(p) for p in tile_positions] - - return tiles - - -def solution(game_board, table): - tiles = parse_tiles(table, 1) - empty_spaces = parse_tiles(game_board, 0) - - tile_counter = Counter(tiles) - empty_space_counter = Counter(empty_spaces) - - used_tiles = tile_counter & empty_space_counter - - return sum(get_tile_size(tile) * occ for tile, occ in used_tiles.items()) - -import numpy as np -from collections import deque - - -def pull_left_top(d:np.array): - while np.count_nonzero(d[:, :1]) == 0: - d = np.roll(d, shift=-1) - while np.count_nonzero(d[:1, :]) == 0: - d = np.roll(d, shift=-1, axis=0) - return d - - -def block_split(block, x, y): - q = deque() - q.append((x, y, 0)) - visit = np.zeros_like(block) - visit[x][y] = 1 - dx = [0, 0, -1, 1] - dy = [-1, 1, 0, 0] - l = len(block) - - while q: - x, y, d = q.popleft() - for k in range(4): - nx = x + dx[k] - ny = y + dy[k] - if nx < 0 or ny < 0 or nx >= l or ny >= l: - continue - if block[nx][ny] == 1 and visit[nx][ny] == 0: # 이어진 2\1 - q.append((nx, ny, d+1)) - visit[nx][ny] = 1 - block[nx][ny] = 0 - - return pull_left_top(visit) - - -def match(hole, block): - for _ in range(4): - block = pull_left_top(np.rot90(block)) - tmp = hole - block - if np.count_nonzero(tmp) == 0: - return True - return False - - -def solution(game_board, block): - # blocks - block = np.array(block, int) - blocks = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[]} - for i in range(len(block)): - for j in range(len(block)): - if block[i][j] == 1: - b = block_split(block, i, j) - blocks[np.count_nonzero(b)].append(b) - - # holes - hole = 1 - np.array(game_board, int) - holes = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[]} - for i in range(len(block)): - for j in range(len(block)): - if hole[i][j] == 1: - h = block_split(hole, i, j) - holes[np.count_nonzero(h)].append(h) - result = 0 - - for i in range(1, 7): - for h in holes[i]: - for j, b in enumerate(blocks[i]): - if match(h, b): - result += i - blocks[i].pop(j) - break - - return result - - - -# 3 -from collections import defaultdict - -block_hashs = [0] * 4 -block_size = 0 - -def solution(game_board, table): - N = len(game_board) - row_base = 1 << 1 - column_base = 1 << N - dx = [1, 0, -1, 0] - dy = [0, 1, 0, -1] - global block_hashs - - def dfs(board, x, y): - visited[x][y] = 1 - global block_size, block_hashs - block_size += 1 - row_exponent = [x, N - y, N - x, y] - column_exponent = [y, x, N - y, N - x] - for k in range(4): - block_hashs[k] += ((row_base ** row_exponent[k]) * - (column_base ** column_exponent[k])) - for i in range(4): - nx = x + dx[i] - ny = y + dy[i] - if not (0 <= nx < N and 0 <= ny < N): - continue - if not board[nx][ny] or visited[nx][ny]: - continue - dfs(board, nx, ny) - - def process_hash(hash_values): - for i, hash_value in enumerate(hash_values): - for hash_base in [row_base, column_base]: - while hash_value % hash_base == 0: - hash_value //= hash_base - hash_values[i] = hash_value - return min(hash_values) - - visited = [[0] * N for _ in range(N)] - game_board_inverted = [[1 - x for x in row] for row in game_board] - game_board_hash = defaultdict(int) - block_size_by_hash = {} - for x in range(N): - for y in range(N): - if not game_board_inverted[x][y] or visited[x][y]: - continue - block_hashs = [0] * 4 - global block_size - block_size = 0 - dfs(game_board_inverted, x, y) - block_hash = process_hash(block_hashs) - game_board_hash[block_hash] += 1 - block_size_by_hash[block_hash] = block_size - - visited = [[0] * N for _ in range(N)] - answer = 0 - for x in range(N): - for y in range(N): - if not table[x][y] or visited[x][y]: - continue - block_hashs = [0] * 4 - dfs(table, x, y) - block_hash = process_hash(block_hashs) - if game_board_hash[block_hash] > 0: - game_board_hash[block_hash] -= 1 - answer += block_size_by_hash[block_hash] - return answer - - -def rotate(piece): - return [[x[i] for x in reversed(piece)] for i in range(len(piece[0]))] - -def seek(board, target): - pieces = [] - length = len(board) - for i in range(length): - for j in range(length): - if board[i][j] == target: - coord = [] - stack = [[i, j]] - while stack: - pivot = stack.pop() - coord.append(pivot) - board[pivot[0]][pivot[1]] = 1 - target - if pivot[0] != 0: - if board[pivot[0]-1][pivot[1]] == target: - stack.append([pivot[0]-1, pivot[1]]) - if pivot[1] != 0: - if board[pivot[0]][pivot[1]-1] == target: - stack.append([pivot[0], pivot[1]-1]) - if pivot[0] != length-1: - if board[pivot[0]+1][pivot[1]] == target: - stack.append([pivot[0]+1, pivot[1]]) - if pivot[1] != length-1: - if board[pivot[0]][pivot[1]+1] == target: - stack.append([pivot[0], pivot[1]+1]) - max_row = max([x[0] for x in coord]) - min_row = min([x[0] for x in coord]) - max_col = max([x[1] for x in coord]) - min_col = min([x[1] for x in coord]) - coord = [[x[0]-min_row, x[1]-min_col] for x in coord] - piece = [[1 if [i, j] in coord else 0 for j in range(max_col-min_col+1)] for i in range(max_row-min_row+1)] - pieces.append(piece) - return pieces - -def match(blank, piece): - if len(blank) == len(piece) and len(blank[0]) == len(piece[0]): - if blank == piece: - return True - if blank == rotate(rotate(piece)): - return True - if len(blank) == len(piece[0]) and len(blank[0]) == len(piece): - if blank == rotate(piece): - return True - if blank == rotate(rotate(rotate(piece))): - return True - return False - -def solution(game_board, table): - answer = 0 - blanks = seek(game_board, 0) - pieces = seek(table, 1) - while pieces: - piece = pieces.pop() - for i in range(len(blanks)): - if match(blanks[i], piece): - del blanks[i] - answer += sum([sum(x) for x in piece]) - break - return answer \ No newline at end of file diff --git "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\236\205\354\213\244\355\207\264\354\213\244.py" "b/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\236\205\354\213\244\355\207\264\354\213\244.py" deleted file mode 100644 index eee830e..0000000 --- "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\236\205\354\213\244\355\207\264\354\213\244.py" +++ /dev/null @@ -1,59 +0,0 @@ - - -def solution(enter, leave): - n = len(enter) - answer = [0] * (n+1) - enter_idx = 0 - leave_idx = 0 - room = set() - while leave_idx < n: - if leave[leave_idx] in room: - room.discard(leave[leave_idx]) - leave_idx += 1 - continue - if enter[enter_idx] not in room: - for man in room: - answer[man] += 1 - answer[enter[enter_idx]] = len(room) - room.add(enter[enter_idx]) - enter_idx += 1 - return answer[1:] - -print(solution([1,3,2], [1,2,3])) - - -from collections import defaultdict - -def solution(enter, leave): - n = len(enter) - answer = [0] * (n+1) - enter_idx = 0 - leave_idx = 0 - room = defaultdict(set) - check = {i: False for i in range(1, n+1)} - while leave_idx < n: - if check[enter[enter_idx]]: - enter_idx += 1 - continue - if enter[enter_idx] == leave[leave_idx]: - if enter[enter_idx] not in room: - for man in room: - room[man].add(enter[enter_idx]) - answer[enter[enter_idx]] += len(room) - check[enter[enter_idx]] = True - else: - answer[enter[enter_idx]] += len(room[enter[enter_idx]]) - check[enter[enter_idx]] = True - del(room[enter[enter_idx]]) - enter_idx = 0 - leave_idx += 1 - else: - room[enter[enter_idx]] - for man in room: - if not enter[enter_idx] == man: - room[man].add(enter[enter_idx]) - room[enter[enter_idx]].add(man) - enter_idx += 1 - return answer[1:] - -# print(solution([1,3,2], [1,2,3])) \ No newline at end of file diff --git a/quickSoreted.py b/quickSoreted.py index e6277ca..9b39ce3 100644 --- a/quickSoreted.py +++ b/quickSoreted.py @@ -1,42 +1,42 @@ -# 퀵정렬 - - -def quick_sort(arr): - if len(arr) <= 1: - return arr - pivot = arr[len(arr) // 2] - lesser_arr, equal_arr, greater_arr = [], [], [] - for num in arr: - if num < pivot: - lesser_arr.append(num) - elif num > pivot: - greater_arr.append(num) - else: - equal_arr.append(num) - return quick_sort(lesser_arr) + equal_arr + quick_sort(greater_arr) - - - -# 큇정렬 최적화(inplace)\ -def quick_sort(arr): - def sort(low, high): - if high <= low: - return - - mid = partition(low, high) - sort(low, mid - 1) - sort(mid, high) - - def partition(low, high): - pivot = arr[(low + high) // 2] - while low <= high: - while arr[low] < pivot: - low += 1 - while arr[high] > pivot: - high -= 1 - if low <= high: - arr[low], arr[high] = arr[high], arr[low] - low, high = low + 1, high - 1 - return low - +# 퀵정렬 + + +def quick_sort(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + lesser_arr, equal_arr, greater_arr = [], [], [] + for num in arr: + if num < pivot: + lesser_arr.append(num) + elif num > pivot: + greater_arr.append(num) + else: + equal_arr.append(num) + return quick_sort(lesser_arr) + equal_arr + quick_sort(greater_arr) + + + +# 큇정렬 최적화(inplace)\ +def quick_sort(arr): + def sort(low, high): + if high <= low: + return + + mid = partition(low, high) + sort(low, mid - 1) + sort(mid, high) + + def partition(low, high): + pivot = arr[(low + high) // 2] + while low <= high: + while arr[low] < pivot: + low += 1 + while arr[high] > pivot: + high -= 1 + if low <= high: + arr[low], arr[high] = arr[high], arr[low] + low, high = low + 1, high - 1 + return low + return sort(0, len(arr) - 1) \ No newline at end of file diff --git a/safety_film.py b/safety_film.py deleted file mode 100644 index 4ef4607..0000000 --- a/safety_film.py +++ /dev/null @@ -1,49 +0,0 @@ -def testPerformance(A): - for c in range(W): - cnt = 1 - for r in range(1, D): - if A[r][c] == A[r-1][c]: - cnt += 1 - else: - cnt = 1 - if cnt >= K: - break - if cnt < K: - return False - return True - -def comb(depth, k, pick): - global result - if depth > result: - return - for i in range(k, D): - select.append(i) - for d in range(2): - select.append(i) - film[i] = drugs[d] - if testPerformance(film): - result = min(result, depth+1) - select.pop() - film[i] = raw[i] - else: - comb(depth+1, i+1, pick) - film[i] = raw[i] - select.pop() - -# main -T = int(input()) -for tc in range(T): - D, W, K = map(int, input().split()) - film = [list(map(int, input().split())) for _ in range(D)] - raw = [f[:] for f in film] - if testPerformance(film): - result = 0 - else: - result = float('inf') - select = [] - drugs = [[0] * W, [1] * W] - for pick in range(1, D+1): - comb(0, 0, pick) - if result < float('inf'): - break - print("#{} {}".format(tc+1, result)) \ No newline at end of file diff --git a/score set_practice.py b/score set_practice.py index 87b5b9c..a43696d 100644 --- a/score set_practice.py +++ b/score set_practice.py @@ -1,19 +1,19 @@ -#coding: utf-8 - -#문자열 찾기 및 조작 - -data_str = "파이썬은 클래스를 이용해 객체를 생성하는 객체지향 프로그래밍 언어입니다." -mask_str = input("마스킹할 문자열을 입력하세요:") -find_str = input("찾을 문자열을 입력하세요:") -idx = -1 -count = 1 -while True: - idx = data_str.find(find_str,idx+1) - if idx != -1: - print("[{0}]~[{1}]".format(idx,idx+len(find_str)-1)) - new_str = data_str.replace(find_str,mask_str,count) - print(new_str) - count += 1 - else: - break +#coding: utf-8 + +#문자열 찾기 및 조작 + +data_str = "파이썬은 클래스를 이용해 객체를 생성하는 객체지향 프로그래밍 언어입니다." +mask_str = input("마스킹할 문자열을 입력하세요:") +find_str = input("찾을 문자열을 입력하세요:") +idx = -1 +count = 1 +while True: + idx = data_str.find(find_str,idx+1) + if idx != -1: + print("[{0}]~[{1}]".format(idx,idx+len(find_str)-1)) + new_str = data_str.replace(find_str,mask_str,count) + print(new_str) + count += 1 + else: + break print(idx) \ No newline at end of file diff --git a/score_aver,total_practice.py b/score_aver,total_practice.py index 71eccf3..f67b38b 100644 --- a/score_aver,total_practice.py +++ b/score_aver,total_practice.py @@ -1,12 +1,12 @@ -#coding: utf-8 - -#성적 총점 평점. -list1 = [1,3, 6, 78, 35, 55] -list2 = [12,24,35,24,88,120,155] - -#교집합 찾기.= 합집합- 반달1-반달2 -#1:1대응 -def intersect(x,y): - return(set(x)&set(y)) - +#coding: utf-8 + +#성적 총점 평점. +list1 = [1,3, 6, 78, 35, 55] +list2 = [12,24,35,24,88,120,155] + +#교집합 찾기.= 합집합- 반달1-반달2 +#1:1대응 +def intersect(x,y): + return(set(x)&set(y)) + print("두 배열의 공통된부분은?:{0}".format(intersect(list1,list2))) \ No newline at end of file diff --git a/show_me_the_code_A.py b/show_me_the_code_A.py deleted file mode 100644 index 267bf01..0000000 --- a/show_me_the_code_A.py +++ /dev/null @@ -1,31 +0,0 @@ -import sys -input = sys.stdin.readline - - -def dfs(depth, people, health, start, attack): - global answer - if depth == n: - answer = max(answer, people) - return - for next_node in range(start, n): - acc_attack = attack + attacks[next_node] - new_health = health - acc_attack - if new_health < 0: - answer = max(answer, people) - continue - acc_attack = attack + attacks[next_node] - dfs(depth + 1, people + populations[next_node], new_health, next_node + 1, acc_attack) - -n, K = map(int, input().split()) -attacks = list(map(int, input().split())) -populations = list(map(int, input().split())) -new_attacks = [] -for i in range(n): - new_attacks.append((attacks[i], populations[i])) -new_attacks.sort() -for i in range(n): - attacks[i] = new_attacks[i][0] - populations[i] = new_attacks[i][1] -answer = 0 -dfs(0, 0, K, 0, 0) -print(answer) diff --git a/show_me_the_code_B.py b/show_me_the_code_B.py deleted file mode 100644 index cb06ce3..0000000 --- a/show_me_the_code_B.py +++ /dev/null @@ -1,2 +0,0 @@ -import sys -input = sys.stdin.readline diff --git a/show_me_the_code_C.py b/show_me_the_code_C.py deleted file mode 100644 index 173ed93..0000000 --- a/show_me_the_code_C.py +++ /dev/null @@ -1,14 +0,0 @@ -import sys -input = sys.stdin.readline - -n = int(input()) -A = list(map(int, input().split())) -B = list(map(int, input().split())) -li = [] -for i in range(n): - li.append(A[i] - B[i]) -dp = [] -dp.append(li[0]) -for i in range(1, n): - dp.append(dp[i - 1] + li[i]) -print(dp) \ No newline at end of file diff --git a/snail.py b/snail.py deleted file mode 100644 index fdf1739..0000000 --- a/snail.py +++ /dev/null @@ -1,26 +0,0 @@ -for tc in range(1, int(input())+1): - N = int(input()) - arr = [[0 for _ in range(N)] for _ in range(N)] - - row = 0 - col = -1 - cnt = 1 - trans = 1 - while N: - # 가로 - for _ in range(N): - col += trans - arr[row][col] = cnt - cnt += 1 - N -= 1 - # 세로 - for _ in range(N): - row += trans - arr[row][col] = cnt - cnt += 1 - trans *= -1 - print('#{}'.format(tc)) - for line in arr: - for i in line: - print(i, end=' ') - print() \ No newline at end of file diff --git a/snail_number.py b/snail_number.py index c009aec..0903290 100644 --- a/snail_number.py +++ b/snail_number.py @@ -1,19 +1,22 @@ -T = int(input()) - - - -for testcase in range(T): - date = input() - year = int(date[:4]) - month = int(date[4:6]) - day = int(date[6:]) - if (month == 1 or 3 or 5 or 7 or 8 or 10 or 12) and month !=0 and 0 < day <= 31: - print("#{} {}/{}/{}".format(testcase+1, year, month, day)) - elif month == 2 and month !=0 and 0 < day <= 28: - print("#{} {}/{}/{}".format(testcase+1, year, month, day)) - elif (month == 4 or 6 or 9 or 11) and month !=0 and 0 < day <= 30: - print("#{} {}/{}/{}".format(testcase+1, year, month, day)) - else: - print("#{} -1") - - \ No newline at end of file +T = int(input()) + + +def coloringGraph(): + N,E,M = map(int,input().split()) + + G =[[0 for _ in range(N)]for _ in range(N)] + + for _ in range(E): + x,y = map(int,input().split()) + G[x-1][y-1] = 1 + G[y-1][x-1] = 1 + + for i in range(N): + if sum(G[i]) > M: + return 0 + + return 1 + + +for testcase in range(T): + print("#{} {}".format(testcase+1, coloringGraph())) \ No newline at end of file diff --git a/snail_number_final.py b/snail_number_final.py deleted file mode 100644 index fdf1739..0000000 --- a/snail_number_final.py +++ /dev/null @@ -1,26 +0,0 @@ -for tc in range(1, int(input())+1): - N = int(input()) - arr = [[0 for _ in range(N)] for _ in range(N)] - - row = 0 - col = -1 - cnt = 1 - trans = 1 - while N: - # 가로 - for _ in range(N): - col += trans - arr[row][col] = cnt - cnt += 1 - N -= 1 - # 세로 - for _ in range(N): - row += trans - arr[row][col] = cnt - cnt += 1 - trans *= -1 - print('#{}'.format(tc)) - for line in arr: - for i in line: - print(i, end=' ') - print() \ No newline at end of file diff --git a/stack_bracket.py b/stack_bracket.py deleted file mode 100644 index 4e81e61..0000000 --- a/stack_bracket.py +++ /dev/null @@ -1,16 +0,0 @@ - - -N,K = map(int,input().split()) -coins = [] -cnt = 0 - -for _ in range(N): - coins.append(int(input())) - -for i in range(1,N): - cnt += K // coins[-i] - K = K % coins[-i] - -print(cnt) - - \ No newline at end of file diff --git a/sudoku.py b/sudoku.py deleted file mode 100644 index 342e3fa..0000000 --- a/sudoku.py +++ /dev/null @@ -1,39 +0,0 @@ - - - - -sudoku = [list(map(int,input().split())) for _ in range(9)] -check = [[0]*9 for _ in range(9)] -sum_check_square = 0 -sum_square = 0 -cnt = 0 -check_cnt=0 -for i in range(9): - for j in range(9): - if sudoku[i][j] ==0: - check[i][j] =1 - cnt +=1 - -while cnt != check_cnt: - for i in range(9): - for j in range(9): - if check[i][j]==1: - if sum(check[i])==1: - sudoku[i][j] = 45-sum(sudoku[i]) - check[i][j] =0 - check_cnt +=1 - if sum([check[n][j] for n in range(9)]) ==1: - sudoku[i][j] = 45- sum([sudoku[m][j] for m in range(9)]) - check[i][j] =0 - check_cnt +=1 - for p in range((i//3)*3,(i//3)*3+3): - for q in range((j//3)*3,(j//3)*3+3): - sum_check_square +=check[p][q] - sum_square +=sudoku[p][q] - if sum_check_square ==1: - sudoku[i][j] = 45-sum_square - check[i][j] = 0 - check_cnt +=1 - -for row in sudoku: - print(*row) diff --git a/sudoku2.py b/sudoku2.py deleted file mode 100644 index 55bd673..0000000 --- a/sudoku2.py +++ /dev/null @@ -1,46 +0,0 @@ -sudoku = [list(map(int, input().split())) for _ in range(9)] -#해결해야될 칸만 받음 -zeros = [(i, j) for i in range(9) for j in range(9) if sudoku[i][j] == 0] - -def is_promising(i, j): - promising = [1,2,3,4,5,6,7,8,9] - - #행열 검사 - for k in range(9): - if sudoku[i][k] in promising: - promising.remove(sudoku[i][k]) - if sudoku[k][j] in promising: - promising.remove(sudoku[k][j]) - - #3*3 박스 검사 - i //= 3 - j //= 3 - for p in range(i*3, (i+1)*3): - for q in range(j*3, (j+1)*3): - if sudoku[p][q] in promising: - promising.remove(sudoku[p][q]) - - return promising - -flag = False #답이 출력되었는가? -def dfs(x): - global flag - - if flag: #이미 답이 출력된 경우 - return - - if x == len(zeros): #마지막 0까지 다 채웠을 경우 - for row in sudoku: - print(*row) - flag = True #답 출력 - return - - else: - (i, j) = zeros[x] - promising = is_promising(i, j) #유망한 숫자들을 받음 - - for num in promising: - sudoku[i][j] = num #유망한 숫자 중 하나를 넣어줌 - dfs(x + 1) #다음 0으로 넘어감 - sudoku[i][j] = 0 #초기화 (정답이 없을 경우를 대비) -dfs(0) \ No newline at end of file diff --git a/sudoku3.py b/sudoku3.py deleted file mode 100644 index b6b1f59..0000000 --- a/sudoku3.py +++ /dev/null @@ -1,46 +0,0 @@ -import sys - -sdk = [list(map(int, input().split())) for _ in range(9)] -zeros = [(i, j) for i in range(9) for j in range(9) if sdk[i][j] == 0] - -def sdoku(index): - - # 한 바퀴에서 모든 경우를 다 보았으면 출력 - if index == len(zeros): - for row in sdk: - print(*row) - sys.exit(0) - else: - x = zeros[index][0] - y = zeros[index][1] - dx = (x//3) * 3 - dy = (y//3) * 3 - - # 사용할 수 있는 숫자 9개 - num_list = [False] + [True for _ in range(9)] - - for j in range(9): - # 가로 검사 - # 세로 검사 - if(sdk[x][j]): - num_list[sdk[x][j]] = False - if(sdk[j][y]): - num_list[sdk[j][y]] = False - - # 3*3 box 검사 - for i in range(dx, dx + 3): - for j in range(dy, dy + 3): - check_num = sdk[i][j] - if(check_num): - num_list[check_num] = False - - # 현재 가능한 수만 가져옴 - # 가능한 수를 가져왔으면, 이전에 다뤄왔던 백트래킹을 사용하면 됨 - candidate_list = [i for i, k in enumerate(num_list) if k] #k가 true즉 나오지 않은 숫자들의 i 즉 숫자를 후보군에 넣음 - - # 경우의 수 고려 - for num in candidate_list: #후보군의 숫자들을 스도쿠에 넣고 다음 빈칸으로 넘어감. - sdk[x][y] = num - sdoku(index + 1) - sdk[x][y] = 0 -sdoku(0) \ No newline at end of file diff --git a/sugar_delievery2839.py b/sugar_delievery2839.py index 6d14bd7..f0ee4be 100644 --- a/sugar_delievery2839.py +++ b/sugar_delievery2839.py @@ -1,13 +1,13 @@ -""" -N명의 사람들 줄서있음. -i번 사람이 인출하는데 Pi분 걸림. -""" -N = int(input()) -P = list(map(int,input().split())) - -mintime = sorted(P) -answer = 0 -for i in range(N): - answer += (N-i)*mintime[i] - +""" +N명의 사람들 줄서있음. +i번 사람이 인출하는데 Pi분 걸림. +""" +N = int(input()) +P = list(map(int,input().split())) + +mintime = sorted(P) +answer = 0 +for i in range(N): + answer += (N-i)*mintime[i] + print(answer) \ No newline at end of file diff --git a/sum_diagonal.py b/sum_diagonal.py deleted file mode 100644 index 8ead63d..0000000 --- a/sum_diagonal.py +++ /dev/null @@ -1,31 +0,0 @@ - -def findPath_dfs(v, visted): - global visited - visited.append(v) - for adj in graph[v]: - if not adj in visited: - visited = findPath_dfs(adj,visited) - return visited - - - -for test in range(1,int(input())+1): - graph = {} - N,M = map(int,input().split()) - max_path = 1 - visited = [] - for _ in range(M): - x,y = map(int,input().split()) - graph[x] = graph.get(x,[]) + [y] - graph[y] = graph.get(y,[]) + [x] - - for i in range(1,N+1): - if M==0: - break - else: - findPath_dfs(i,visited) - if max_path < len(visited): - max_path = len(visited) - - print(f"#{test} {graph}") - \ No newline at end of file diff --git a/sum_new.py b/sum_new.py deleted file mode 100644 index 2c95504..0000000 --- a/sum_new.py +++ /dev/null @@ -1,16 +0,0 @@ -o=[] -for t in range(10): - N = int(input()) - M = [list(map(int, input().split())) for _ in range(100)] - A = [0]*100 - B, C, D = A[:], 0, 0 - - for i in range(100): - C += M[i][i] - D += M[99-i][i] - for j in range(100): - A[i] += M[i][j] - B[i] += M[j][i] - - o.append(f"#{N} {max(A+B+[C,D])}\n") -print(''.join(o)) \ No newline at end of file diff --git a/treee.py b/treee.py deleted file mode 100644 index 2a0b310..0000000 --- a/treee.py +++ /dev/null @@ -1,275 +0,0 @@ -# 이진트리 -class Node: - def __init__(self, data): - self.data = data - self.left = None - self.right = None - - def __str__(self): - return str(self.data) - -class Tree: - def __init__(self): - self.root = None - - def preorderTraversal(self, node): - print(node, end='') - if not node.left == None : self.preorderTraversal(node.left) - if not node.right == None : self.preorderTraversal(node.right) - - def inorderTraversal(self, node): - if not node.left == None : self.inorderTraversal(node.left) - print(node, end='') - if not node.right == None : self.inorderTraversal(node.right) - - def postorderTraversal(self, node): - if not node.left == None : self.postorderTraversal(node.left) - if not node.right == None : self.postorderTraversal(node.right) - print(node, end='') - - def makeRoot(self, node, left_node, right_node): - if self.root == None: - self.root = node - node.left = left_node - node.right = right_node - -if __name__ == "__main__": - node = [] - node.append(Node('-')) - node.append(Node('*')) - node.append(Node('/')) - node.append(Node('A')) - node.append(Node('B')) - node.append(Node('C')) - node.append(Node('D')) - - m_tree = Tree() - for i in range(int(len(node)/2)): - m_tree.makeRoot(node[i],node[i*2+1],node[i*2+2]) - - print( '전위 순회 : ', end='') ; m_tree.preorderTraversal(m_tree.root) - print('\n' + '중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) - print('\n' + '후위 순회 : ', end='') ; m_tree.postorderTraversal(m_tree.root) - - - - # 스레드 이진트리 - class Node: - def __init__(self, data): - self.data = data - self.left = None - self.right = None - self.is_thread_right = None - - def __str__(self): - return str(self.data) - -class ThreadTree: - def __init__(self): - self.root = None - - def inorderTraversal(self, node): - while not node.left == None: - node = node.left - print(node, end='') - while True: - node = self.findThread(node) - print(node, end='') - if node.right == None: - break - - def findThread(self, node): - pre_node = node - node = node.right - if node == None: - return node - if pre_node.is_thread_right: - return node - while not node.left == None: - node = node.left - return node - - def makeRoot(self, node, left_node, right_node, thread): - if self.root == None: - self.root = node - node.left = left_node - node.right = right_node - node.is_thread_right = thread - -if __name__ == "__main__": - node = [] - node.append(Node('-')) - node.append(Node('*')) - node.append(Node('/')) - node.append(Node('A')) - node.append(Node('B')) - node.append(Node('C')) - node.append(Node('D')) - - m_tree = ThreadTree() - for i in range(int(len(node)/2)): - m_tree.makeRoot(node[i],node[i*2+1],node[i*2+2], False) - - m_tree.makeRoot(node[3], None, None, True) - m_tree.makeRoot(node[4], None, None, True) - m_tree.makeRoot(node[5], None, None, True) - - node[3].right = node[1] - node[4].right = node[0] - node[5].right = node[2] - - print('중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) - - # 이진탐색트리 - import random - -class Node: - def __init__(self, data): - self.data = data - self.right = None - self.left = None - - def __str__(self): - return str(self.data) - -class SearchTree: - def __init__(self): - self.root = None - - def insertElement(self, data): - new_node = Node(data) - if self.root == None: - self.root = new_node - - node = self.root - while True: - pre_node = node - if node.data > new_node.data: - node = node.left - if node == None: - node = new_node - pre_node.left = node - elif node.data < new_node.data: - node = node.right - if node == None: - node = new_node - pre_node.right = node - else: return - - def searchElement(self, data): - node = self.root - while True: - if node.data > data: - node = node.left - elif node.data < data: - node = node.right - elif node.data == data: - break - else: - return Node('탐색 결과 없음') - - return node - - def preorderTraversal(self, node): - print(node, end=' ') - if not node.left == None : self.preorderTraversal(node.left) - if not node.right == None : self.preorderTraversal(node.right) - - def inorderTraversal(self, node): - if not node.left == None : self.inorderTraversal(node.left) - print(node, end=' ') - if not node.right == None : self.inorderTraversal(node.right) - - def postorderTraversal(self, node): - if not node.left == None : self.postorderTraversal(node.left) - if not node.right == None : self.postorderTraversal(node.right) - print(node, end=' ') - -if __name__ == "__main__": - m_tree = SearchTree() - - m_tree.insertElement(250) - for i in range(20): - m_tree.insertElement(random.randint(0,500)) - - print( '전위 순회 : ', end='') ; m_tree.preorderTraversal(m_tree.root) - print('\n' + '중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) - print('\n' + '후위 순회 : ', end='') ; m_tree.postorderTraversal(m_tree.root) - - node = m_tree.searchElement(250) - print('\n' + '탐색한 노드의 값 :', node) - print( '노드의 왼쪽 서브 트리 :', node.left) - print( '노드의 오른쪽 서브 트리 :', node.right) - - node = m_tree.searchElement(node.left.data) - print('\n' + '탐색한 노드의 값 :', node) - print( '노드의 왼쪽 서브 트리 :', node.left) - print( '노드의 오른쪽 서브 트리 :', node.right) - - - # 힙구조 - class Heap: - def __init__(self): - self.array = [] - - def __str__(self): - return str(self.array) - - def insertElement(self, data): - self.array.append(data) - length = len(self.array) - if length > 1: - node_num = length - 1 - while True: - next_node_num = int(node_num/2) - if self.array[next_node_num] < self.array[node_num]: - temp = self.array[node_num] - self.array[node_num] = self.array[next_node_num] - self.array[next_node_num] = temp - else: - break - node_num = int(node_num/2) - if node_num == 0: - break - - def deleteRoot(self): - root_value = self.array[0] - del self.array[0] - - last_index = len(self.array) - 1 - if last_index < 0: - return root_value - tail_value = self.array[last_index] - del self.array[last_index] - - self.array.insert(0, tail_value) - now_index = 0 - next_index = 0 - while True: - now_index = next_index - next_index *= 2 - if next_index + 2 > last_index: - break - if self.array[next_index + 1] > self.array[next_index + 2]: - next_index += 1 - else: - next_index += 2 - if self.array[now_index] < self.array[next_index]: - temp = self.array[now_index] - self.array[now_index] = self.array[next_index] - self.array[next_index] = temp - return root_value - -if __name__ == '__main__': - m_heap = Heap() - m_heap.insertElement(2) - m_heap.insertElement(4) - m_heap.insertElement(5) - m_heap.insertElement(8) - m_heap.insertElement(2) - m_heap.insertElement(3) - print('Heap :', m_heap) - print('Delete Root :', m_heap.deleteRoot()) - print('Delete Root :', m_heap.deleteRoot()) - print('Delete Root :', m_heap.deleteRoot()) - print('Heap :', m_heap) \ No newline at end of file diff --git "a/tree\354\240\225\353\246\254.py" "b/tree\354\240\225\353\246\254.py" index e8a843c..cfbc34b 100644 --- "a/tree\354\240\225\353\246\254.py" +++ "b/tree\354\240\225\353\246\254.py" @@ -1,275 +1,275 @@ -# 이진트리 -class Node: - def __init__(self, data): - self.data = data - self.left = None - self.right = None - - def __str__(self): - return str(self.data) - -class Tree: - def __init__(self): - self.root = None - - def preorderTraversal(self, node): - print(node, end='') - if not node.left == None : self.preorderTraversal(node.left) - if not node.right == None : self.preorderTraversal(node.right) - - def inorderTraversal(self, node): - if not node.left == None : self.inorderTraversal(node.left) - print(node, end='') - if not node.right == None : self.inorderTraversal(node.right) - - def postorderTraversal(self, node): - if not node.left == None : self.postorderTraversal(node.left) - if not node.right == None : self.postorderTraversal(node.right) - print(node, end='') - - def makeRoot(self, node, left_node, right_node): - if self.root == None: - self.root = node - node.left = left_node - node.right = right_node - -if __name__ == "__main__": - node = [] - node.append(Node('-')) - node.append(Node('*')) - node.append(Node('/')) - node.append(Node('A')) - node.append(Node('B')) - node.append(Node('C')) - node.append(Node('D')) - - m_tree = Tree() - for i in range(int(len(node)/2)): - m_tree.makeRoot(node[i],node[i*2+1],node[i*2+2]) - - print( '전위 순회 : ', end='') ; m_tree.preorderTraversal(m_tree.root) - print('\n' + '중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) - print('\n' + '후위 순회 : ', end='') ; m_tree.postorderTraversal(m_tree.root) - - - - # 스레드 이진트리 -class Node: - def __init__(self, data): - self.data = data - self.left = None - self.right = None - self.is_thread_right = None - - def __str__(self): - return str(self.data) - -class ThreadTree: - def __init__(self): - self.root = None - - def inorderTraversal(self, node): - while not node.left == None: - node = node.left - print(node, end='') - while True: - node = self.findThread(node) - print(node, end='') - if node.right == None: - break - - def findThread(self, node): - pre_node = node - node = node.right - if node == None: - return node - if pre_node.is_thread_right: - return node - while not node.left == None: - node = node.left - return node - - def makeRoot(self, node, left_node, right_node, thread): - if self.root == None: - self.root = node - node.left = left_node - node.right = right_node - node.is_thread_right = thread - -if __name__ == "__main__": - node = [] - node.append(Node('-')) - node.append(Node('*')) - node.append(Node('/')) - node.append(Node('A')) - node.append(Node('B')) - node.append(Node('C')) - node.append(Node('D')) - - m_tree = ThreadTree() - for i in range(int(len(node)/2)): - m_tree.makeRoot(node[i],node[i*2+1],node[i*2+2], False) - - m_tree.makeRoot(node[3], None, None, True) - m_tree.makeRoot(node[4], None, None, True) - m_tree.makeRoot(node[5], None, None, True) - - node[3].right = node[1] - node[4].right = node[0] - node[5].right = node[2] - - print('중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) - - # 이진탐색트리 -import random - -class Node: - def __init__(self, data): - self.data = data - self.right = None - self.left = None - - def __str__(self): - return str(self.data) - -class SearchTree: - def __init__(self): - self.root = None - - def insertElement(self, data): - new_node = Node(data) - if self.root == None: - self.root = new_node - - node = self.root - while True: - pre_node = node - if node.data > new_node.data: - node = node.left - if node == None: - node = new_node - pre_node.left = node - elif node.data < new_node.data: - node = node.right - if node == None: - node = new_node - pre_node.right = node - else: return - - def searchElement(self, data): - node = self.root - while True: - if node.data > data: - node = node.left - elif node.data < data: - node = node.right - elif node.data == data: - break - else: - return Node('탐색 결과 없음') - - return node - - def preorderTraversal(self, node): - print(node, end=' ') - if not node.left == None : self.preorderTraversal(node.left) - if not node.right == None : self.preorderTraversal(node.right) - - def inorderTraversal(self, node): - if not node.left == None : self.inorderTraversal(node.left) - print(node, end=' ') - if not node.right == None : self.inorderTraversal(node.right) - - def postorderTraversal(self, node): - if not node.left == None : self.postorderTraversal(node.left) - if not node.right == None : self.postorderTraversal(node.right) - print(node, end=' ') - -if __name__ == "__main__": - m_tree = SearchTree() - - m_tree.insertElement(250) - for i in range(20): - m_tree.insertElement(random.randint(0,500)) - - print( '전위 순회 : ', end='') ; m_tree.preorderTraversal(m_tree.root) - print('\n' + '중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) - print('\n' + '후위 순회 : ', end='') ; m_tree.postorderTraversal(m_tree.root) - - node = m_tree.searchElement(250) - print('\n' + '탐색한 노드의 값 :', node) - print( '노드의 왼쪽 서브 트리 :', node.left) - print( '노드의 오른쪽 서브 트리 :', node.right) - - node = m_tree.searchElement(node.left.data) - print('\n' + '탐색한 노드의 값 :', node) - print( '노드의 왼쪽 서브 트리 :', node.left) - print( '노드의 오른쪽 서브 트리 :', node.right) - - - # 힙구조 -class Heap: - def __init__(self): - self.array = [] - - def __str__(self): - return str(self.array) - - def insertElement(self, data): - self.array.append(data) - length = len(self.array) - if length > 1: - node_num = length - 1 - while True: - next_node_num = int(node_num/2) - if self.array[next_node_num] < self.array[node_num]: - temp = self.array[node_num] - self.array[node_num] = self.array[next_node_num] - self.array[next_node_num] = temp - else: - break - node_num = int(node_num/2) - if node_num == 0: - break - - def deleteRoot(self): - root_value = self.array[0] - del self.array[0] - - last_index = len(self.array) - 1 - if last_index < 0: - return root_value - tail_value = self.array[last_index] - del self.array[last_index] - - self.array.insert(0, tail_value) - now_index = 0 - next_index = 0 - while True: - now_index = next_index - next_index *= 2 - if next_index + 2 > last_index: - break - if self.array[next_index + 1] > self.array[next_index + 2]: - next_index += 1 - else: - next_index += 2 - if self.array[now_index] < self.array[next_index]: - temp = self.array[now_index] - self.array[now_index] = self.array[next_index] - self.array[next_index] = temp - return root_value - -if __name__ == '__main__': - m_heap = Heap() - m_heap.insertElement(2) - m_heap.insertElement(4) - m_heap.insertElement(5) - m_heap.insertElement(8) - m_heap.insertElement(2) - m_heap.insertElement(3) - print('Heap :', m_heap) - print('Delete Root :', m_heap.deleteRoot()) - print('Delete Root :', m_heap.deleteRoot()) - print('Delete Root :', m_heap.deleteRoot()) +# 이진트리 +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + def __str__(self): + return str(self.data) + +class Tree: + def __init__(self): + self.root = None + + def preorderTraversal(self, node): + print(node, end='') + if not node.left == None : self.preorderTraversal(node.left) + if not node.right == None : self.preorderTraversal(node.right) + + def inorderTraversal(self, node): + if not node.left == None : self.inorderTraversal(node.left) + print(node, end='') + if not node.right == None : self.inorderTraversal(node.right) + + def postorderTraversal(self, node): + if not node.left == None : self.postorderTraversal(node.left) + if not node.right == None : self.postorderTraversal(node.right) + print(node, end='') + + def makeRoot(self, node, left_node, right_node): + if self.root == None: + self.root = node + node.left = left_node + node.right = right_node + +if __name__ == "__main__": + node = [] + node.append(Node('-')) + node.append(Node('*')) + node.append(Node('/')) + node.append(Node('A')) + node.append(Node('B')) + node.append(Node('C')) + node.append(Node('D')) + + m_tree = Tree() + for i in range(int(len(node)/2)): + m_tree.makeRoot(node[i],node[i*2+1],node[i*2+2]) + + print( '전위 순회 : ', end='') ; m_tree.preorderTraversal(m_tree.root) + print('\n' + '중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) + print('\n' + '후위 순회 : ', end='') ; m_tree.postorderTraversal(m_tree.root) + + + + # 스레드 이진트리 + class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.is_thread_right = None + + def __str__(self): + return str(self.data) + +class ThreadTree: + def __init__(self): + self.root = None + + def inorderTraversal(self, node): + while not node.left == None: + node = node.left + print(node, end='') + while True: + node = self.findThread(node) + print(node, end='') + if node.right == None: + break + + def findThread(self, node): + pre_node = node + node = node.right + if node == None: + return node + if pre_node.is_thread_right: + return node + while not node.left == None: + node = node.left + return node + + def makeRoot(self, node, left_node, right_node, thread): + if self.root == None: + self.root = node + node.left = left_node + node.right = right_node + node.is_thread_right = thread + +if __name__ == "__main__": + node = [] + node.append(Node('-')) + node.append(Node('*')) + node.append(Node('/')) + node.append(Node('A')) + node.append(Node('B')) + node.append(Node('C')) + node.append(Node('D')) + + m_tree = ThreadTree() + for i in range(int(len(node)/2)): + m_tree.makeRoot(node[i],node[i*2+1],node[i*2+2], False) + + m_tree.makeRoot(node[3], None, None, True) + m_tree.makeRoot(node[4], None, None, True) + m_tree.makeRoot(node[5], None, None, True) + + node[3].right = node[1] + node[4].right = node[0] + node[5].right = node[2] + + print('중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) + + # 이진탐색트리 + import random + +class Node: + def __init__(self, data): + self.data = data + self.right = None + self.left = None + + def __str__(self): + return str(self.data) + +class SearchTree: + def __init__(self): + self.root = None + + def insertElement(self, data): + new_node = Node(data) + if self.root == None: + self.root = new_node + + node = self.root + while True: + pre_node = node + if node.data > new_node.data: + node = node.left + if node == None: + node = new_node + pre_node.left = node + elif node.data < new_node.data: + node = node.right + if node == None: + node = new_node + pre_node.right = node + else: return + + def searchElement(self, data): + node = self.root + while True: + if node.data > data: + node = node.left + elif node.data < data: + node = node.right + elif node.data == data: + break + else: + return Node('탐색 결과 없음') + + return node + + def preorderTraversal(self, node): + print(node, end=' ') + if not node.left == None : self.preorderTraversal(node.left) + if not node.right == None : self.preorderTraversal(node.right) + + def inorderTraversal(self, node): + if not node.left == None : self.inorderTraversal(node.left) + print(node, end=' ') + if not node.right == None : self.inorderTraversal(node.right) + + def postorderTraversal(self, node): + if not node.left == None : self.postorderTraversal(node.left) + if not node.right == None : self.postorderTraversal(node.right) + print(node, end=' ') + +if __name__ == "__main__": + m_tree = SearchTree() + + m_tree.insertElement(250) + for i in range(20): + m_tree.insertElement(random.randint(0,500)) + + print( '전위 순회 : ', end='') ; m_tree.preorderTraversal(m_tree.root) + print('\n' + '중위 순회 : ', end='') ; m_tree.inorderTraversal(m_tree.root) + print('\n' + '후위 순회 : ', end='') ; m_tree.postorderTraversal(m_tree.root) + + node = m_tree.searchElement(250) + print('\n' + '탐색한 노드의 값 :', node) + print( '노드의 왼쪽 서브 트리 :', node.left) + print( '노드의 오른쪽 서브 트리 :', node.right) + + node = m_tree.searchElement(node.left.data) + print('\n' + '탐색한 노드의 값 :', node) + print( '노드의 왼쪽 서브 트리 :', node.left) + print( '노드의 오른쪽 서브 트리 :', node.right) + + + # 힙구조 + class Heap: + def __init__(self): + self.array = [] + + def __str__(self): + return str(self.array) + + def insertElement(self, data): + self.array.append(data) + length = len(self.array) + if length > 1: + node_num = length - 1 + while True: + next_node_num = int(node_num/2) + if self.array[next_node_num] < self.array[node_num]: + temp = self.array[node_num] + self.array[node_num] = self.array[next_node_num] + self.array[next_node_num] = temp + else: + break + node_num = int(node_num/2) + if node_num == 0: + break + + def deleteRoot(self): + root_value = self.array[0] + del self.array[0] + + last_index = len(self.array) - 1 + if last_index < 0: + return root_value + tail_value = self.array[last_index] + del self.array[last_index] + + self.array.insert(0, tail_value) + now_index = 0 + next_index = 0 + while True: + now_index = next_index + next_index *= 2 + if next_index + 2 > last_index: + break + if self.array[next_index + 1] > self.array[next_index + 2]: + next_index += 1 + else: + next_index += 2 + if self.array[now_index] < self.array[next_index]: + temp = self.array[now_index] + self.array[now_index] = self.array[next_index] + self.array[next_index] = temp + return root_value + +if __name__ == '__main__': + m_heap = Heap() + m_heap.insertElement(2) + m_heap.insertElement(4) + m_heap.insertElement(5) + m_heap.insertElement(8) + m_heap.insertElement(2) + m_heap.insertElement(3) + print('Heap :', m_heap) + print('Delete Root :', m_heap.deleteRoot()) + print('Delete Root :', m_heap.deleteRoot()) + print('Delete Root :', m_heap.deleteRoot()) print('Heap :', m_heap) \ No newline at end of file diff --git a/using_lotto.py b/using_lotto.py index 2b18f82..8d3e213 100644 --- a/using_lotto.py +++ b/using_lotto.py @@ -1,7 +1,7 @@ -from lotto_numbering_module import * - -start = input_start() -end = input_end() -count = input_count() - +from lotto_numbering_module import * + +start = input_start() +end = input_end() +count = input_count() + print_lotto(start, end, count) \ No newline at end of file diff --git a/view_practice.py b/view_practice.py deleted file mode 100644 index e2602c2..0000000 --- a/view_practice.py +++ /dev/null @@ -1,14 +0,0 @@ -#검사해서 좌우 두칸에 나보다 작은 숫자만 있으면 됨. - - -def view(): - width = int(input()) - building = list(map(int,input().split())) - cnt = 0 - for i in range(2, len(building)): - if building[i]>building[i-1] and building[i]>building[i-2] and building[i]>building[i+1] and building[i]>building[i+2]: - cnt += min(building[i]-building[i-1],building[i]-building[i-2],building[i]-building[i+1],building[i]-building[i+2]) - return cnt - -for j in range(1,11): - print("#{0} {1}".format(j, view())) \ No newline at end of file diff --git "a/\352\262\214\354\236\204\353\247\265\354\265\234\353\213\250\352\261\260\353\246\254_PM.py" "b/\352\262\214\354\236\204\353\247\265\354\265\234\353\213\250\352\261\260\353\246\254_PM.py" deleted file mode 100644 index 4796144..0000000 --- "a/\352\262\214\354\236\204\353\247\265\354\265\234\353\213\250\352\261\260\353\246\254_PM.py" +++ /dev/null @@ -1,21 +0,0 @@ -from collections import deque - - -def solution(maps): - return bfs(maps) - - -def bfs(maps): - dy, dx = [1,-1,0,0], [0,0,1,-1] - dist = [[-1] * len(maps[0]) for _ in range(len(maps))] - dist[0][0] = 1 - q = deque([(0, 0)]) - while q: - cy, cx = q.popleft() - for d in range(4): - ny, nx = cy + dy[d], cx + dx[d] - if 0 <= ny < len(maps) and 0 <= nx < len(maps[0]): - if dist[ny][nx] == -1 and maps[ny][nx] == 1: - dist[ny][nx] = dist[cy][cx] + 1 - q.append((ny, nx)) - return dist[-1][-1] \ No newline at end of file diff --git "a/\352\270\260\353\212\245\352\260\234\353\260\234.py" "b/\352\270\260\353\212\245\352\260\234\353\260\234.py" index bd99d47..debb425 100644 --- "a/\352\270\260\353\212\245\352\260\234\353\260\234.py" +++ "b/\352\270\260\353\212\245\352\260\234\353\260\234.py" @@ -1,33 +1,33 @@ -def solution(progresses, speeds): - N = len(speeds) - dp = [0]*N - count=0 - answer = [] - - for i in range(N): - dp[i] = ((100 - progresses[i])//speeds[i]) - if((100 - progresses[i])%speeds[i]) != 0: - dp[i]+=1 - - max = dp[0] - for i in range(N): - if max>=dp[i]: - count+=1 - else: - answer.append(count) - count=1 - max=dp[i] - answer.append(count) - return answer - -# 다른사람 풀이 -# -((p-100)//s)는 올림한 양수 -# zip은 동일개수 자료형을 튜플로 묶어주는 함수 -def solution(progresses, speeds): - Q=[] - for p, s in zip(progresses, speeds): - if len(Q)==0 or Q[-1][0]<-((p-100)//s): - Q.append([-((p-100)//s),1]) - else: - Q[-1][1]+=1 +def solution(progresses, speeds): + N = len(speeds) + dp = [0]*N + count=0 + answer = [] + + for i in range(N): + dp[i] = ((100 - progresses[i])//speeds[i]) + if((100 - progresses[i])%speeds[i]) != 0: + dp[i]+=1 + + max = dp[0] + for i in range(N): + if max>=dp[i]: + count+=1 + else: + answer.append(count) + count=1 + max=dp[i] + answer.append(count) + return answer + +# 다른사람 풀이 +# -((p-100)//s)는 올림한 양수 +# zip은 동일개수 자료형을 튜플로 묶어주는 함수 +def solution(progresses, speeds): + Q=[] + for p, s in zip(progresses, speeds): + if len(Q)==0 or Q[-1][0]<-((p-100)//s): + Q.append([-((p-100)//s),1]) + else: + Q[-1][1]+=1 return [q[1] for q in Q] \ No newline at end of file diff --git "a/\352\270\260\354\264\210\354\210\230\354\213\235.py" "b/\352\270\260\354\264\210\354\210\230\354\213\235.py" deleted file mode 100644 index 846a9e0..0000000 --- "a/\352\270\260\354\264\210\354\210\230\354\213\235.py" +++ /dev/null @@ -1,48 +0,0 @@ -# return 이 하나면 1의 연산이라 보면 됨. -# T(n) = T(n-1) + n = T(0) + n(n+1)/2 => n^2연산 -# T(n) = T(n/2) + 1 = log n + 2 => log n 연산 -# T(n) = 2 * T(n/2) + n = n^(log(b)a) * log n = n * log n (a=2, b=2) -# T(n) = T(n-1) + 1/n = T(0) + 시그마(1/k)고 시그마(1/k)는 1~n까지 1/x의 적분 보다 같거나 작은데 이는 1+ log n - log 1 보다 작음을 의미. -# = T(0) + log n + 1 = log n -def fibo(n): - sqrt_5 = 5 ** (0.5) - ans = (((1 + sqrt_5) / 2) ** n - ((1 - sqrt_5) / 2) ** n) // sqrt_5 - return ans % 1000000 - - -n = int(input()) -print(fibo(n)) - -#2^x 피보나치를 구해주는 함수 -def matrix_mul_self(x): - base = [[1, 1], [1, 0]] - result = [[1, 1], [1, 0]] - for _ in range(x): - result = [[0, 0], [0, 0]] - for i in range(2): - for j in range(2): - for k in range(2): - result[i][j] += (base[i][k] * base[k][j]) % 1000000 - base = result - - return result - -#2*2 두 행렬의 곱을 구해주는 함수 -def matrix_mul(a, b): - result = [[0 ,0], [0, 0]] - for i in range(2): - for j in range(2): - for k in range(2): - result[i][j] += (a[i][k] * b[k][j]) % 1000000 - - return result - -n = bin(int(input()))[2:] #2진법으로 변환 - -result = [[1, 0], [0, 1]] -for i in range(len(n)): - if n[-i-1] == '1': #2^x 피보나치들만 구해준 다음 곱해줌 - result = matrix_mul(result, matrix_mul_self(i)) - -print(result[0][1] % 1000000) - diff --git "a/\352\270\260\355\203\200/20210911_1.py" "b/\352\270\260\355\203\200/20210911_1.py" deleted file mode 100644 index 40c21e7..0000000 --- "a/\352\270\260\355\203\200/20210911_1.py" +++ /dev/null @@ -1,21 +0,0 @@ -# 브루스포스(n3)으로 풀림. -# 이전에 들고있던 sum값에 새로 들어오는 애들만 정리해주는 방식.(n2) -# 투포인터 2번 돌리는 방법. 합이 k이하인 연속 부분수열의 갯수를 k-1이하인 연속 부분수열의 갯수에서 빼면됨. - -from collections import deque - -def solution(student, k): - left = 0 - one_position = deque() - answer = 0 - student += [1] - for right in range(len(student)): - if student[right]: - one_position.append(right) - if len(one_position) > k: - answer += (one_position[0] - left + 1)*(right - one_position[-2]) - left = one_position.popleft() + 1 - return answer - - -print(solution([0,1,0,0],1)) diff --git "a/\352\270\260\355\203\200/20210911_2.py" "b/\352\270\260\355\203\200/20210911_2.py" deleted file mode 100644 index 4631939..0000000 --- "a/\352\270\260\355\203\200/20210911_2.py" +++ /dev/null @@ -1,41 +0,0 @@ -# 브루트 or 투포인터 - -from collections import deque - -def check_issue(counter,n,k): - for char in counter: - if counter[char] >= k: - n_cnt[char][0] += 1 - n_cnt[char][1].append(counter[char]) - if n_cnt[char][0] >= n: - if sum(n_cnt[char][1]) >= 2*n*k: - issue_word[char] += 1 - n_cnt[char][0] -= 1 - n_cnt[char][1].popleft() - else: - n_cnt[char][0] = 0 - n_cnt[char][1] = deque() - - -def solution(research, n, k): - global n_cnt, issue_word - n_cnt = {chr(i): [0,deque()] for i in range(97,97+26)} - issue_word = {chr(i): 0 for i in range(97,97+26)} - for search in research: - counter = {chr(i): 0 for i in range(97,97+26)} - for word in search: - counter[word] += 1 - check_issue(counter,n,k) - max_cnt = 0 - hot_issue_word = 0 - for word in issue_word: - if max_cnt < issue_word[word]: - hot_issue_word = word - max_cnt = issue_word[word] - if not hot_issue_word: - hot_issue_word = 'None' - return hot_issue_word - - - -print(solution(["abaaaa","aaa","abaaaaaa","fzfffffffa"],2,2)) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/20210911_3.py" "b/\352\270\260\355\203\200/20210911_3.py" deleted file mode 100644 index 51c042d..0000000 --- "a/\352\270\260\355\203\200/20210911_3.py" +++ /dev/null @@ -1,63 +0,0 @@ -from collections import deque - -def choose_job(q): - sum_priority = {i: [0,deque()] for i in range(1,101)} - max_priority_id = 0 - for job in q: - if check[job[4]]: - continue - sum_priority[job[2]][0] += job[3] - sum_priority[job[2]][1].append(job) - if max_priority_id < sum_priority[job[2]][0]: - max_priority_id = job[2] - - return sum_priority[max_priority_id][1] - -def solution(jobs): - global check - n = len(jobs) - for i in range(n): - jobs[i].append(i) - time = 0 - queue = [] - answer = [] - queue.append(jobs[0]) - idx = 0 - check = [False for i in range(n)] - while not all(check): - # 큐를체크해 할 작업을 골라냄. - to_do = choose_job(queue) - # 작업을 실시함. - now_doing = to_do[0][2] - while to_do: - call_time, cost, id_n, priority, cur_idx = to_do.popleft() - if time >= call_time: - time += cost - else: - time = call_time + cost - if not answer: - answer.append(id_n) - elif answer and answer[-1] != id_n: - answer.append(id_n) - check[cur_idx] = True - # 작업 종료 시간에따라 큐에 작업을 할당함 - flag = 0 - tmp = idx - for i in range(tmp+1,n): - if time >= jobs[i][0]: - if jobs[i][2]==now_doing: - to_do.append(jobs[i]) - idx = jobs[i][4] - else: - queue.append(jobs[i]) - idx = jobs[i][4] - flag = 1 - else: - break - if not flag and idx+1 < n: - queue.append(jobs[idx+1]) - - return answer - - -print(solution([[0, 2, 3, 1], [5, 3, 3, 1], [10, 2, 4, 1]])) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/20210911_4.py" "b/\352\270\260\355\203\200/20210911_4.py" deleted file mode 100644 index 45b5f71..0000000 --- "a/\352\270\260\355\203\200/20210911_4.py" +++ /dev/null @@ -1,31 +0,0 @@ - -def make_sieve(n): - primes = [True,True] + [False]*(n-1) - m = int(n**0.5)+1 - for i in range(2,m): - if not primes[i]: - for j in range(i+i, n+1, i): - primes[j] = True - return [num for num in range(n+1) if not primes[num]] - - -def divied_conquer(arr, size): - if size == 1: - return arr - for num in prime_nums: - if not size%num: - pivot = num - break - conquer = [] - for start in range(pivot): - conquer += divied_conquer([arr[i] for i in range(start,size,pivot)],size//pivot) - return conquer - - -def solution(n): - global prime_nums - arr = [i for i in range(1,n+1)] - prime_nums = make_sieve(n) - ans = divied_conquer(arr,n) - return ans -print(solution(1000000)) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/20210911_5.py" "b/\352\270\260\355\203\200/20210911_5.py" deleted file mode 100644 index 2be41c7..0000000 --- "a/\352\270\260\355\203\200/20210911_5.py" +++ /dev/null @@ -1 +0,0 @@ -# 못품. \ No newline at end of file diff --git "a/\352\270\260\355\203\200/20210911_6.py" "b/\352\270\260\355\203\200/20210911_6.py" deleted file mode 100644 index 6dabc86..0000000 --- "a/\352\270\260\355\203\200/20210911_6.py" +++ /dev/null @@ -1,21 +0,0 @@ -from collections import defaultdict -from bisect import bisect_left,bisect_right - -def solution(records, k, date): - parsed_recode = [] - for recode in records: - d = int(recode[0].replace('-','')) - parsed_recode.append((d,recode[1],recode[2])) - start = int(date.replace('-','')) - tmp = start + k - end = tmp if (tmp)%100 <= 30 else (tmp//1000)*1000 + (tmp//100 + 1)*100 + start%31 + 1 - start_idx = bisect_left(start) - end_idx = bisect_right(end) - count_buying = defaultdict(list) - re_buying_ration = defaultdict(list) - for i in range(start_idx,end_idx): - count_buying[parsed_recode[i][1]].append(parsed_recode[i][2]) - - - -print(solution(["2020-02-02 uid1 pid1", "2020-02-26 uid1 pid1", "2020-02-26 uid2 pid1", "2020-02-27 uid3 pid2", "2020-02-28 uid4 pid2", "2020-02-29 uid3 pid3", "2020-03-01 uid4 pid3", "2020-03-03 uid1 pid1", "2020-03-04 uid2 pid1", "2020-03-05 uid3 pid2", "2020-03-05 uid3 pid3", "2020-03-05 uid3 pid3", "2020-03-06 uid1 pid4"],10,"2020-03-05")) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/211007_1.py" "b/\352\270\260\355\203\200/211007_1.py" deleted file mode 100644 index b39a76f..0000000 --- "a/\352\270\260\355\203\200/211007_1.py" +++ /dev/null @@ -1,5 +0,0 @@ -def solution(n): - n -= 1 - for i in range(2, n + 1): - if not n % i: - return i \ No newline at end of file diff --git "a/\352\270\260\355\203\200/211007_2.py" "b/\352\270\260\355\203\200/211007_2.py" deleted file mode 100644 index 58acc35..0000000 --- "a/\352\270\260\355\203\200/211007_2.py" +++ /dev/null @@ -1,7 +0,0 @@ -def solution(n, left, right): - arr = [] - start_x, start_y, end_x = left // n, left % n, right // n - for i in range(start_x, end_x + 1): - arr += [i + 1] * (i + 1) + [j for j in range(i + 2, n + 1)] - return arr[start_y: start_y + right - left + 1] - diff --git "a/\352\270\260\355\203\200/211007_3.py" "b/\352\270\260\355\203\200/211007_3.py" deleted file mode 100644 index 6153c39..0000000 --- "a/\352\270\260\355\203\200/211007_3.py" +++ /dev/null @@ -1,16 +0,0 @@ -def solution(n, m, x, y, queries): - # 도착점부터 거꾸로 이행을 한다. left, right, up, down의 범위를 조정해감.(x1, y1), (x2, y2) - # 도착점과 command set을 가지고 시작할 수 있는 범위를 돌려주는 함수. - # 연속 부분 이차원 배열의 연산결과는 연속 부분 이차원 배열이 나옴. - # 그 여백의 넓이가 문제의 답. - - # 음수구간 고려해야함. - - # max_x, min_x ,y 이분탐색으로 구해서 범위를 구한다. -> 얘는 따로 x, y 따로해서 구할 수 있음.(축마다 따로) - answer = -1 - return answer - - - - -print(solution(2, 2, 0, 0)) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/211028kaenf_1\353\262\210.py" "b/\352\270\260\355\203\200/211028kaenf_1\353\262\210.py" deleted file mode 100644 index d3aad53..0000000 --- "a/\352\270\260\355\203\200/211028kaenf_1\353\262\210.py" +++ /dev/null @@ -1,29 +0,0 @@ - -from heapq import heappush, heappop - -def cardinalitySort(nums): - # Write your code here - answer = [] - heap = [] - for num in nums: - binary_cardinality = bin(int(num))[2:].count('1') - heappush(heap, (binary_cardinality, num)) - while heap: - answer.append(heappop(heap)[1]) - return answer - - -if __name__ == '__main__': - - - nums_count = int(input().strip()) - - nums = [] - - for _ in range(nums_count): - nums_item = int(input().strip()) - nums.append(nums_item) - - result = cardinalitySort(nums) - - print(result) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/211028kaenf_2\353\262\210.py" "b/\352\270\260\355\203\200/211028kaenf_2\353\262\210.py" deleted file mode 100644 index 9e9b16a..0000000 --- "a/\352\270\260\355\203\200/211028kaenf_2\353\262\210.py" +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/python3 - -import math -import os -import random -import re -import sys - - - -# -# Complete the 'validateAddresses' function below. -# -# The function is expected to return a STRING_ARRAY. -# The function accepts STRING_ARRAY addresses as parameter. -# - -def validateAddresses(addresses): - answer = [] - for address in addresses: - address.strip() - if ':' not in address and address.count('.') == 3: - if not address[0].isdigit() or not address[-1].isdigit(): - answer.append('Neither') - continue - arr = [] - tmp = address.split('.') - flag = 0 - for each in tmp: - if len(each) > 3 or int(each) < 0 or int(each) > 255: - flag = 1 - break - if each[0] == '0' and int(each) >= 8: - flag = 1 - break - if flag: - answer.append('Neither') - continue - answer.append('IPv4') - elif '.' not in address and ':' in address: - flag = 0 - if address[0] == ':' and address[1] != ':': - answer.append('Neither') - continue - if address[-1] == ':' and address[-2] != ':': - answer.append('Neither') - for char in address: - if char not in '0123456789abcdef:': - flag = 1 - break - if flag: - answer.append('Neither') - continue - arr = [] - tmp = list(address.split(':')) - for idx, each in enumerate(tmp): - if idx > 1 and not each: - if not tmp[idx - 1] and idx != len(tmp) - 1: - flag = 1 - break - if flag: - answer.append('Neither') - continue - for each in tmp: - if not each: - flag = 1 - break - if not flag and len(tmp) != 8: - answer.append('Neither') - continue - answer.append('IPv6') - else: - answer.append('Neither') - return answer - -# 000.012.234.23 - -if __name__ == '__main__': - addresses_count = int(input().strip()) - - addresses = [] - - for _ in range(addresses_count): - addresses_item = input() - addresses.append(addresses_item) - - result = validateAddresses(addresses) - - print(result) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/211028kaenf_3\353\262\210.py" "b/\352\270\260\355\203\200/211028kaenf_3\353\262\210.py" deleted file mode 100644 index 91ae1b3..0000000 --- "a/\352\270\260\355\203\200/211028kaenf_3\353\262\210.py" +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/python3 - -import math -import os -import random -import re -import sys - - - -# -# Complete the 'minOperations' function below. -# -# The function is expected to return a LONG_INTEGER. -# The function accepts LONG_INTEGER n as parameter. -# - -def minOperations(n): - bin_n = list(map(int, bin(n)[2:].lstrip('0'))) - return bin_n - -if __name__ == '__main__': - - n = int(input().strip()) - - result = minOperations(n) - - print(result) - diff --git "a/\352\270\260\355\203\200/211028kaenf_4\353\262\210.py" "b/\352\270\260\355\203\200/211028kaenf_4\353\262\210.py" deleted file mode 100644 index 3854e08..0000000 --- "a/\352\270\260\355\203\200/211028kaenf_4\353\262\210.py" +++ /dev/null @@ -1,53 +0,0 @@ -from collections import defaultdict - -def dfs(cur_node, graph, visited): - global answer - visited[cur_node] = True - answer += '(' + cur_node - for next_node in graph[cur_node]: - if visited[next_node]: - answer = 'E3' - for key in visited: - visited[key] = True - return - dfs(next_node, graph, visited) - answer += ')' - return answer - - -def sExpression(nodes): - global answer - graph = defaultdict(list) - visited = {} - for idx, char in enumerate(nodes): - if char == ',': - start, end = nodes[idx - 1], nodes[idx + 1] - visited[start], visited[end] = False, False - if start in graph and end in graph[start]: - return 'E2' - if end in graph and start in graph[end]: - return 'E2' - graph[start].append(end) - if len(graph[start]) > 2: - return 'E1' - for value in graph.values(): - value.sort() - - for start in visited: - visited = {node: False for node in visited} - answer = '' - dfs(start, graph, visited) - answer += ')' - if len(answer) == 3 * len(visited): - return answer - if answer[0] == 'E': - return 'E3' - return 'E4' - - -if __name__ == '__main__': - nodes = input() - - result = sExpression(nodes) - - print(result) diff --git "a/\352\270\260\355\203\200/25083 \354\203\210\354\213\271.py" "b/\352\270\260\355\203\200/25083 \354\203\210\354\213\271.py" deleted file mode 100644 index 5b8a9e3..0000000 --- "a/\352\270\260\355\203\200/25083 \354\203\210\354\213\271.py" +++ /dev/null @@ -1,6 +0,0 @@ -print(" ,r'\"7") -print("r`-_ ,' ,/") -print(" \\. \". L_r'") -print(" `~\\/") -print(" |") -print(" |") \ No newline at end of file diff --git "a/\352\270\260\355\203\200/codechallenge1.py" "b/\352\270\260\355\203\200/codechallenge1.py" deleted file mode 100644 index df06219..0000000 --- "a/\352\270\260\355\203\200/codechallenge1.py" +++ /dev/null @@ -1,11 +0,0 @@ -def solution(numbers): - check = {i: False for i in range(10)} - for number in numbers: - if not check[number]: - check[number] = True - answer = 0 - for nums in check: - if not check[nums]: - answer += nums - - return answer \ No newline at end of file diff --git "a/\352\270\260\355\203\200/codechallenge2.py" "b/\352\270\260\355\203\200/codechallenge2.py" deleted file mode 100644 index 697d60d..0000000 --- "a/\352\270\260\355\203\200/codechallenge2.py" +++ /dev/null @@ -1,35 +0,0 @@ - - - -def solution(grid): - d = ((1,0),(0,-1),(-1,0),(0,1)) - results = [] - rows = len(grid) - cols = len(grid[0]) - visited = {(i,j,d): False for i in range(rows) for j in range(cols) for d in range(4)} - for i in range(rows): - for j in range(cols): - for di in range(4): - if visited[(i,j,di)]: - continue - length = 1 - x, y, di = i, j, di - while True: - visited[(x,y,di)] = True - nx = (x + d[di][0])%rows - ny = (y + d[di][1])%cols - if grid[nx][ny] == 'S': - nd = di - elif grid[nx][ny] == 'L': - nd = (di-1)%4 - else: - nd = (di+1)%4 - if visited[(nx,ny,nd)]: - results.append(length) - break - length += 1 - x,y,di = nx,ny,nd - results.sort() - return results - -print(solution(["R","R"])) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/codechallenge3.py" "b/\352\270\260\355\203\200/codechallenge3.py" deleted file mode 100644 index a082745..0000000 --- "a/\352\270\260\355\203\200/codechallenge3.py" +++ /dev/null @@ -1,35 +0,0 @@ -import sys -input = sys.stdin.readline -from math import ceil - -def is_possible(target,gold,silver,g_list,s_list,w_list,t_list): - n = len(g_list) - need_to_move = gold + silver - for i in range(n): - # 편도 cnt번 왕복 가능. - cnt = target//t_list[i] - # 한번에 w_list[i] - total = w_list[i]*ceil(cnt/2) - if total > g_list[i] + s_list[i]: - total = g_list[i] + s_list[i] - need_to_move -= total - if need_to_move <= 0: - return True - return False - - - -def solution(a, b, g, s, w, t): - left = 0 - right = int(2e14) - answer = 0 - while left <= right: - mid = (left + right)//2 - if is_possible(mid, a, b, g, s, w, t): - right = mid-1 - answer = mid - else: - left = mid + 1 - return answer - -print(solution(10,10,[100],[100],[7],[10])) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/codechallenge4.py" "b/\352\270\260\355\203\200/codechallenge4.py" deleted file mode 100644 index 2a1d19f..0000000 --- "a/\352\270\260\355\203\200/codechallenge4.py" +++ /dev/null @@ -1,26 +0,0 @@ -def check(b,n): - c.add(tuple(b)) - for i in range(1,n): - if b[i] == b[i-1]: - tmp = b[:i-1] + [b[i]+b[i-1]] + b[i+1:] - check(tmp,n-1) - - -def solution(a, s): - results = [] - bs = [] - idx = 0 - s_cnt = len(s) - for n in s: - bs.append(a[idx:idx+n]) - idx = idx+n - for i in range(s_cnt): - global c - b = bs[i] - n = s[i] - c = set() - check(b,n) - results.append(len(c)) - return results - -print(solution([1,2,3,4,5,6,7,8,9],[2,3,4])) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/nefa_1.py" "b/\352\270\260\355\203\200/nefa_1.py" deleted file mode 100644 index 041b9a6..0000000 --- "a/\352\270\260\355\203\200/nefa_1.py" +++ /dev/null @@ -1,15 +0,0 @@ -from collections import defaultdict - -def solution(id_list, k): - total = defaultdict(int) - for day in id_list: - check = set() - for each in day.split(): - check.add(each) - for num in check: - if total[num] < k: - total[num] += 1 - answer = 0 - for each in total.values(): - answer += each - return answer \ No newline at end of file diff --git "a/\352\270\260\355\203\200/nefa_2.py" "b/\352\270\260\355\203\200/nefa_2.py" deleted file mode 100644 index 08ef885..0000000 --- "a/\352\270\260\355\203\200/nefa_2.py" +++ /dev/null @@ -1,34 +0,0 @@ -def solution(n, jump): - board = [[0] * n for _ in range(n)] - size = (n ** 2) - delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) - arr = [0] * size - arr[0] = 1 - num = 1 - cnt = 0 - while num < size: - for i in range(size): - if not arr[i]: - cnt += 1 - if cnt == jump: - num += 1 - arr[i] = num - cnt = 0 - target_cnt = arr.index(size) - q = [] - q.append((0, 0, 0, 0)) - while q: - x, y, d, cnt = q.pop() - board[x][y] = arr[cnt] - if cnt == target_cnt: - answer = [x + 1, y + 1] - break - for i in range(d, d + 4): - i %= 4 - nx, ny = x + delta[i][0], y + delta[i][1] - if 0 <= nx < n and 0 <= ny < n and not board[nx][ny]: - q.append((nx, ny, i, cnt + 1)) - break - return answer - -print(solution(5, 3)) \ No newline at end of file diff --git "a/\352\270\260\355\203\200/nefa_3.py" "b/\352\270\260\355\203\200/nefa_3.py" deleted file mode 100644 index 16e498e..0000000 --- "a/\352\270\260\355\203\200/nefa_3.py" +++ /dev/null @@ -1,28 +0,0 @@ -from collections import defaultdict - -def solution(logs): - answer = [] - dic = defaultdict(dict) - for each in logs: - man_id, problem_id, score = each.split() - dic[man_id][problem_id] = score - candidate = [man for man in dic if len(dic[man]) >= 5] - answer_set = set() - n = len(candidate) - for i in range(n - 1): - for j in range(i + 1, n): - for problem in dic[candidate[i]]: - if problem not in dic[candidate[j]]: - break - if dic[candidate[i]][problem] != dic[candidate[j]][problem]: - break - else: - answer_set.add(candidate[i]) - answer_set.add(candidate[j]) - if answer_set: - for each in answer_set: - answer.append(each) - else: - answer.append("None") - answer.sort() - return answer \ No newline at end of file diff --git "a/\352\270\260\355\203\200/nefa_4.py" "b/\352\270\260\355\203\200/nefa_4.py" deleted file mode 100644 index 7cc7bad..0000000 --- "a/\352\270\260\355\203\200/nefa_4.py" +++ /dev/null @@ -1,24 +0,0 @@ - - -def solution(board): - global answer - n = len(board) - delta = ((1, 0), (0, 1)) - answer = 0 - - def dfs(x, y, cnt): - global answer - if (x, y) == (n-1, n-1): - answer = max(answer, cnt) - return - for dx, dy in delta: - nx, ny = x + dx, y + dy - if 0 <= nx < n and 0 <= ny < n: - if board[nx][ny]: - dfs(nx, ny, cnt + board[nx][ny]) - else: - dfs(nx, ny, cnt) - dfs(nx, ny, -cnt) - - dfs(0, 0, board[0][0]) - return answer \ No newline at end of file diff --git "a/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274.py" "b/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274.py" deleted file mode 100644 index 4946a7b..0000000 --- "a/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\274.py" +++ /dev/null @@ -1,53 +0,0 @@ -# 인접 행렬로 구현한 다익스트라 코드 -import sys - - -def dijkstra(K, V, graph): - INF = sys.maxsize - # s는 해당 노드를 방문 했는지 여부를 저장하는 변수이다 - s = [False] * V - # d는 memoization을 위한 array이다. d[i]는 정점 K에서 i까지 가는 최소한의 거리가 저장되어 있다. - d = [INF] * V - d[K - 1] = 0 - - while True: - m = INF - N = -1 - - # 방문하지 않은 노드 중 d값이 가장 작은 값을 선택해 그 노드의 번호를 N에 저장한다. - # 즉, 방문하지 않은 노드 중 K 정점과 가장 가까운 노드를 선택한다. - for j in range(V): - if not s[j] and m > d[j]: - m = d[j] - N = j - - # 방문하지 않은 노드 중 현재 K 정점과 가장 가까운 노드와의 거리가 INF 라는 뜻은 - # 방문하지 않은 남아있는 모든 노드가 A에서 도달할 수 없는 노드라는 의미이므로 반복문을 빠져나간다. - if m == INF: - break - - # N번 노드를 '방문'한다. - # '방문'한다는 의미는 모든 노드를 탐색하며 N번 노드를 통해서 가면 더 빨리 갈 수 있는 노드가 있는지 확인하고, - # 더 빨리 갈 수 있다면 해당 노드(노드의 번호 j라고 하자)의 d[j]를 업데이트 해준다. - s[N] = True - - for j in range(V): - if s[j]: continue - via = d[N] + graph[N][j] - if d[j] > via: - d[j] = via - - return d - -if __name__ == "__main__": - V, E = map(int, input().split()) - K = int(input()) - INF = sys.maxsize - graph = [[INF]*V for _ in range(V)] - - for _ in range(E): - u, v, w = map(int, input().split()) - graph[u-1][v-1] = w - - for d in dijkstra(K, V, graph): - print(d if d != INF else "INF") \ No newline at end of file diff --git "a/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\2742.py" "b/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\2742.py" deleted file mode 100644 index 00cc1f8..0000000 --- "a/\353\213\244\354\235\265\354\212\244\355\212\270\353\235\2742.py" +++ /dev/null @@ -1,49 +0,0 @@ -import heapq -import sys -input = sys.stdin.readline() -INF = int(1e9) #무한을 의미하는 값으로 10억을 설정. - -#노드의 개수, 간선의 개수를 입력받기 -n, m = map(int, input().split()) -#시작 노드 번호를 입력받기 -start = int(input()) -#각 노드에 연결되어 있는 노드에 대한 정보를 담는 리스트를 만들기 -graph = [[] for i in range(n + 1)] -#최단 거리 테이블을 모두 무한으로 초기화 -distance = [INF] * (n + 1) - -#모든 간선 정보를 입력받기 -for _ in range(m): - a, b, c = map(int, input().split()) - #a번 노드에서 b번 노드로 가는 비용이 c라는 의미 - graph[a].append((b, c)) - -def dijkstra(start): - q = [] - #시작 노드로 가기 위한 최단 경로는 0으로 설정하여, 큐에 삽입 - heapq.heappush(q, (0, start)) - distance[start] = 0 - while q: #큐가 비어있지 않다면 - #가장 최단 거리가 짧은 노드에 대한 정보 꺼내기 - dist, now = heapq.heappop(q) - # 현재 노드가 이미 처리된 적이 있는 노드라면 무시 - if distance[now] < dist: - continue - # 현재 노드와 연결된 다른 인접한 노드들을 확인 - for i in graph[now]: - cost = dist + i[1] - #현재 노드를 거쳐서, 다른 노드로 이동하는 거리가 더 짧은 경우 - if cost < distance[i[0]]: - distance[i[0]] = cost - heapq.heappush(q, (cost, i[0])) - -dijkstra(start) - -#모든 노드로 가기 위한 최단 거리를 출력 -for i in range(1, n + 1): - #도달할 수 없는 경우, 무한이라고 출력 - if distance[i] == INF: - print("INFINITY") - #도달할 수 있는 경우 거리를 출력 - else: - print(distance[i]) \ No newline at end of file diff --git "a/\353\213\254\355\214\275\354\235\264.py" "b/\353\213\254\355\214\275\354\235\264.py" deleted file mode 100644 index e69de29..0000000 diff --git "a/\353\260\261\355\212\270\353\236\230\355\202\271.py" "b/\353\260\261\355\212\270\353\236\230\355\202\271.py" deleted file mode 100644 index 8fcbafe..0000000 --- "a/\353\260\261\355\212\270\353\236\230\355\202\271.py" +++ /dev/null @@ -1,34 +0,0 @@ -#부분집합 기본코드 -def printSet(n): - for i in range(n): - if A[i] == 1: - print(data[i], end = " ") - print() - -def powerset(k, n): # k는 A배열의 k인덱스의 포함 유무를 판별한다. - if n == k: - printSet(k) - else: - A[k] = 1 - powerset(k+1, n) # 배열 A에 체크하고 다음 인덱스로 넘어간다 - A[k] = 0 # 재귀로 되돌아와서 체크 했던걸 다시 원상복귀시킨다 - powerset(k+1, n) - -# data = 구하려는 리스트 -n = len(data) # 부분집합을 구하는 리스트의 수 -A = [0]* n # 포함 유무를 체크할 리스트 (0이 미포함, 1이 포함) - - -# 부분집합의 합 -def powerset(k, n, sum): - if sum > 10: # 부분집합의 합을 구하는 문제에서 구하고자하는 값인 10을 넘는다면 더이상 계산할 필요가 없으므로 return해버린다.(가지치기) - return - if n == k: - printSet(k, sum) - else: - A[k] = 1 - powerset(k+1, n, sum+data[k]) - A[k] = 0 - powerset(k+1, n, sum) - - # 백트래킹은 완전검색에서 가지치기를함 \ No newline at end of file diff --git "a/\353\263\200\354\210\230\353\252\205.PNG" "b/\353\263\200\354\210\230\353\252\205.PNG" new file mode 100644 index 0000000..0c94bc3 Binary files /dev/null and "b/\353\263\200\354\210\230\353\252\205.PNG" differ diff --git "a/\353\263\264\354\235\264\354\226\264\353\254\264\354\226\264 \355\214\250\355\204\264\353\247\244\354\271\255.py" "b/\353\263\264\354\235\264\354\226\264\353\254\264\354\226\264 \355\214\250\355\204\264\353\247\244\354\271\255.py" deleted file mode 100644 index 54780dc..0000000 --- "a/\353\263\264\354\235\264\354\226\264\353\254\264\354\226\264 \355\214\250\355\204\264\353\247\244\354\271\255.py" +++ /dev/null @@ -1,70 +0,0 @@ -# 본 코드는 text안에 찾는 pattern 이 있으면 1 없으면 0 을 출력해주는 코드이다 - -# 보이어무어 알고리즘을 적용했다. - - - -# 보이어무어 알고리즘이란 다음과 같다 - -# pattern의 오른쪽 끝 문자와 text의 현재 위치의 문자가 일치하는지 검사 -# 끝이 일치하면 pattern과 text를 다 검사한다. 마지막까지 일치하지 않으면 패턴길이만큼 skip -# 끝이 일치하지않으면 text의 현재위치 문자가 skip배열에 있는지 확인. 있으면 인덱스만큼 skip, 없으면 패턴길이만큼 skip -# 텍스트 끝 도달할 때까지 반복 - -text = 'a pattern matching algorithm' -pattern = 'rithm' -s = pattern[::-1] -skip = list(range((len(pattern)))) - -i = len(pattern)-1 -result = 0 - -while i < len(text): - nxt = len(s) - j = 0 - if s[j] == text[i]: - while j < len(s): - if s[j] != text[i-j]: - break - j += 1 - if j == len(s): - result = 1 - else: - while j < len(s): - if s[j] == text[i]: - nxt = min(j, nxt) - break - j += 1 - if result: - break - i += nxt - -print(result) - - -# 고지식한 패턴검색 알고리즘 = Brute Force. 텍스트의 모든 위치에서 패턴비교 O(MN) - -# KMP 알고리즘. 불일치 발생한 앞부분 대해 다시 비교하지 않고 매칭 수행 O(M+N)=O(N) -# next 배열을 생성해 불일치 발생하면 이동할 다음위치 저장. -# 패턴 왼쪽에서 오른쪽으로 비교 - -# 보이어 무어 알고리즘. 앞부분보다 끝부분가서 불일치 일어날 확률이 높다는 것 이용 -# 일반적으로는 O(N) 보다 적은 수행시간. 최악일땐 O(MN) -# skip 배열 생성해서 일치하는 칸으로 몇칸 이동해야하는지 저장 -# 패턴 오른쪽에서 왼쪽으로 비교. - -# 그러면 3가지 패턴매칭 알고리즘을 비교해보자. M은 패턴의 길이, N은 텍스트의 길이 -# Brute Force(=고지식한 패턴검색 알고리즘) -# 텍스트의 모든 위치에서 패턴 비교하고 한칸씩 이동한다. -# 시간복잡도 O(MN) -# KMP -# 불일치 발생한 앞부분에 대해 다시 비교하지 않고 매칭 수행 -# next배열을 생성해 불일치 발생하면 이동할 다음 위치 저장 -# 패턴의 왼쪽에서 오른쪽으로 비교 -# 시간복잡도 O(M+N) = O(N) -# 보이어무어 -# 앞부분보다 끝부분가서 불일치 일어날 확률이 높다는 것 이용 -# skip 배열 생성해서 일치하는 칸으로 몇 칸 이동해야하는지 저장 -# 패턴의 오른쪽에서 왼쪽으로 비교 -# 상용화된 제품이나 서비스에 가장 많이 적용됨 -# 시간복잡도 일반적으로 O(N) 이하. 최학일땐 O(MN) \ No newline at end of file diff --git "a/\354\202\254\353\260\251\355\203\220\354\203\211.py" "b/\354\202\254\353\260\251\355\203\220\354\203\211.py" deleted file mode 100644 index 3a413c2..0000000 --- "a/\354\202\254\353\260\251\355\203\220\354\203\211.py" +++ /dev/null @@ -1,38 +0,0 @@ -from collections import deque -import sys -def bfs(q, cnt = 0): - dx, dy = [0, 0, 1, -1], [1, -1, 0, 0] - while q: - cnt += 1 - for _ in range(len(q)): - x, y = q.popleft() - for i in range(4): - nx, ny = x + dx[i], y + dy[i] - if nx >= N or nx < 0 or ny >= M or ny < 0 or arr[nx][ny] != 0: - continue - arr[nx][ny] = 1 - q.append((nx,ny)) - if check(arr): - return cnt - 1 - else: - return -1 - -def check(arr): - for i in range(N): - for j in range(M): - if arr[i][j] == 0: - return False - break - return 1 - -if __name__ == "__main__": - input = sys.stdin.readline - M, N = map(int,input().split()) - q = deque([]) - arr = [] - for i in range(N): - arr.append(list(map(int,input().split()))) - for j in range(M): - if arr[i][j] == 1: - q.append((i,j)) - print(bfs(q)) \ No newline at end of file diff --git "a/\354\227\260\354\243\274\354\231\200\355\227\254\354\212\244\354\236\245_LV4.py" "b/\354\227\260\354\243\274\354\231\200\355\227\254\354\212\244\354\236\245_LV4.py" deleted file mode 100644 index 2c35c04..0000000 --- "a/\354\227\260\354\243\274\354\231\200\355\227\254\354\212\244\354\236\245_LV4.py" +++ /dev/null @@ -1,107 +0,0 @@ -# 연주와헬스장_LV4.py -""" -하루 운동에 대한 선택은 실시 할 때마다 해당 기구의 운동 효율이 줄어들기 때문에 dfs로 3세트의 운동 조합을 산출했습니다. -dfs의 결과 최대 무게 증량이 가능한 운동 조합값을 하루단위로 저장할 maxw_a_day, used_a_day 변수로 -하루의 증량과 사용한 기구를 전역으로 관리했습니다. - -각 세트가 지날 때마다 이용자의 위치는 하루동안 동일하기 때문에 change_locations_each_set 함수를 통해 -dfs전 미리 연산해 others, others_1, others_2로 전역관리했습니다. - -하루 운동이 끝나면 그 날 이용한 기구들에 대해 근육통 counter인 exhausted 딕셔너리에 갱신을 해준 후 -maxw_a_day를 cur_weight에 더해 최대 중량을 갱신합니다. -다음날 이용자들 위치 연산을 위해 change_locations 함수를 통해 다음날 위치를 산출 해 주었고 -근육통이 지속되는 날짜에 대해 exhausted를 순회하며 1씩 감산 해주었습니다. -근육통이 끝나면 근육통 배열에서 삭제했습니다. -""" - -# 하루 운동할 때 3세트 운동한다. -def exercise(chosen, total, machines, gym): - global exhausted, maxw_a_day, used_a_day, others, others_1, others_2 - n = len(gym) - k = len(chosen) - # 진행한 세트 수에 따라 사람들의 위치가 바뀌거나 최대값들이 갱신된다. - if k == 0: - tmp_others = others - elif k == 1: - tmp_others = others_1 - elif k == 2: - tmp_others = others_2 - elif k == 3: - if maxw_a_day < total: - maxw_a_day = total - used_a_day = chosen - return - for i in range(n): - for j in range(n): - # 다른 사람이 쓰고있는 운동 기구는 쓰지 않습니다. - if (i, j) not in tmp_others: - # 선택하면 효율성 반으로. - machine_id = gym[i][j] - earn_weight = machines[machine_id] - if machine_id in exhausted: - earn_weight //= 2 - for choose in chosen: - if machine_id == choose: - earn_weight //= 2 - exercise(chosen + [machine_id], total + earn_weight, machines, gym) - -# 하루 지날 때 헬스장 이용자들의 위치 변화 -def change_locations(others, n): - ret = {} - for other in others: - x, y = other - d = (others[other] + 1) % 4 - ret[(y, n - x - 1)] = d - return ret - -# 한 세트 지날 때 헬스장 이용자들의 위치 변화 -def change_locations_each_set(others, n): - delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) - ret = {} - for other in others: - x, y = other - d = others[other] - dx, dy = x + delta[d][0], y + delta[d][1] - if dx < 0 or dx >= n or dy < 0 or dy >= n: - d = (d + 2) % 4 - dx, dy = x + delta[d][0], y + delta[d][1] - ret[dx, dy] = d - return ret - - -def solution(cur_weight, gym, peoples, machines): - global maxw_a_day, exhausted, used_a_day, others, others_1, others_2 - days = 0 - exhausted = {} - # 다른 사람들 위치 dictionary에 저장. - others = {} - for x, y, d in peoples: - others[(x, y)] = d - while cur_weight < 500: - maxw_a_day, used_a_day = 0, [] - # 각 세트를 운동 한 후 헬스장 상태. - others_1 = change_locations_each_set(others, len(gym)) - others_2 = change_locations_each_set(others_1, len(gym)) - # 하루 운동해서 최댓값 증량 - exercise([], 0, machines, gym) - cur_weight += maxw_a_day - for each in used_a_day: - exhausted[each] = 3 - # 사람들 위치 변경 - others = change_locations(others_2, len(gym)) - # 날짜 변동 - days += 1 - # 날이 지나면 근육통 count - 1 - finish_exhausted = [] - for each_exercise in exhausted: - exhausted[each_exercise] -= 1 - if not exhausted[each_exercise]: - finish_exhausted.append(each_exercise) - for fin in finish_exhausted: - del exhausted[fin] - return days - - - -if __name__ == "__main__": - print(solution(3, [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], [[1, 2, 3], [3, 4, 2], [0, 4, 2]], [100, 2, 3, 4, 5])) \ No newline at end of file diff --git "a/\354\230\210\354\240\234\353\252\250\354\235\214.py" "b/\354\230\210\354\240\234\353\252\250\354\235\214.py" index 4da3122..1375b0e 100644 --- "a/\354\230\210\354\240\234\353\252\250\354\235\214.py" +++ "b/\354\230\210\354\240\234\353\252\250\354\235\214.py" @@ -1,16 +1,16 @@ -# 완주하지 못한 선수 - -def solution(participant, completion): hash ={} for i in participant: if i in hash: hash[i] += 1 else: hash[i] = 1 for i in completion: if hash[i] == 1: del hash[i] else: hash[i] -= 1 answer = list(hash.keys())[0] return answer - -# 전화번호 목록 - -def solution(phone_book): answer = True finish = False phone_book = sorted(phone_book, key=len) for i in range(0, len(phone_book)): if finish: break current = phone_book[i] for j in range(i+1, len(phone_book)): comp = phone_book[j] if len(current) dp[u][0]: - allies.append(u) - is_having = False - else: - is_having = True - for v in graph[u]: - if not visited[v]: - make_allies(v, is_having) - - -def solution(n, location, army_powers, edges): - global visited, dp, graph, visited, allies - graph = defaultdict(list) - for a, b in edges: - graph[a] += [b] - graph[b] += [a] - dp = {i: [0, 0] for i in range(n)} - visited = {i: False for i in range(n)} - merge_power(location, army_powers) - max_power = dp[location][1] - allies = [location] - visited = {i: False for i in range(n)} - visited[location] = True - for v in graph[location]: - make_allies(v, False) - allies.sort() - return max_power, allies - - -if __name__ == "__main__": - print(solution(4, 0, [70, 80, 100, 2000], [[0, 1], [1, 2], [2, 3]])) \ No newline at end of file diff --git "a/\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" "b/\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" index 70b8631..a5d9529 100644 --- "a/\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" +++ "b/\354\240\221\353\257\270\354\202\254\353\260\260\354\227\264.py" @@ -1,9 +1,9 @@ -S = "hanseungjoo" -S_list = [] - -for _ in S: - S_list.append(S) - S = S[1:] - -for i in sorted(S_list): +S = "hanseungjoo" +S_list = [] + +for _ in S: + S_list.append(S) + S = S[1:] + +for i in sorted(S_list): print(i) \ No newline at end of file diff --git "a/\354\240\234\352\263\261 \343\204\264\343\204\264\354\210\230.py" "b/\354\240\234\352\263\261 \343\204\264\343\204\264\354\210\230.py" deleted file mode 100644 index 0c5f8d2..0000000 --- "a/\354\240\234\352\263\261 \343\204\264\343\204\264\354\210\230.py" +++ /dev/null @@ -1,30 +0,0 @@ -# 에라토스테네스의 체 활용 -# 기존은 isPrime을 통해 소수 수집 후 소수의 배수들을 걸러주는 방법. -# 이번엔 n^2수들의 배수를 배제하는 방법. -# 1. 검사할 숫자들을 배제하기위한 False배열(최대검사수만큼) -# 2. 제곱들이 저장되는 배열(범위 내 제곱값까지.) -# 3. 제곱의 배수 갯수 저장할 cnt -# 4. 제곱수로 나누어 떻어지는 값들을 최대, 최소값 사이로 민다.(j를 늘려가며) -# 체를통해 중복체크하는 것만 없애면 시간복잡도는 n에 수렴한다. - -min_num,max_num = map(int,input()) -# 1 -eratos_filter = [False for _ in range(max_num-min_num+1)] -# 3 -cnt = max_num-min_num+1 -i = 2 -while i**2 <= max_num: - # i는2부터 i제곱의 으로 안나눠 떨어지면 s+1부터 min이랑 max사이로 들어옴. - s = min_num//(i**2) - if min_num % (i**2) != 0: - s +=1 - - while s*(i**2) <= max_num: - if not eratos_filter[s*(i**2)-min_num]: - eratos_filter[s*(i**2)-min_num] = True - # 카운트는 최대 값부터 배수하나 찾을때마다 -1씩해줌. - cnt -= 1 - s+=1 - i += 1 - -print(cnt) \ No newline at end of file diff --git "a/\354\240\234\354\236\221/\354\227\260\354\243\274\354\231\200 \355\227\254\354\212\244\354\236\245_LV4.md" "b/\354\240\234\354\236\221/\354\227\260\354\243\274\354\231\200 \355\227\254\354\212\244\354\236\245_LV4.md" deleted file mode 100644 index 1e7f8cc..0000000 --- "a/\354\240\234\354\236\221/\354\227\260\354\243\274\354\231\200 \355\227\254\354\212\244\354\236\245_LV4.md" +++ /dev/null @@ -1,45 +0,0 @@ -# 연주와 헬스장 - -연주는 올 여름 승주와 바캉스를 가기 위해 3대 운동 최대 중량의 합이 500이상이 되는 "3대 500"을 목표로 헬스장을 등록했다. - -한 변의 길이가 n인 정사각형 모양의 헬스장에는 각 격자마다 운동 기구가 배치되어 있다. - -연주는 다음과 같은 방법으로 운동을 한다. - -* 연주는 하루에 운동을 3세트 실시하며 그 날 중량을 최대한 늘릴 수 있는 조합으로 세트를 구성한다. - * 조합의 증량 무게가 같을 경우 0행 가깝고, 행이 같으면 0열에 가까운 운동기구를 먼저 사용한다. -* 다른 사람이 쓰고 있는 자리는 쓸 수 없으며 한 세트가 끝나면 모든 사람들이 각자 방향으로 한 칸씩 이동한다. - * 방향 0, 1, 2, 3은 각각 동, 서, 남, 북 방향이며 체육관의 0행쪽이 남쪽, 0열쪽이 서쪽이다. - * 이용자들끼리의 위치 중복은 신경쓰지 않는다. -* 당일 운동한 기구는 횟수당 증량 효율이 절반이 된다. (증량 무게는 정수이며 소수점은 버린다.) -* 운동한 기구는 운동 후 2일동안 근육통으로 증량 효율은 절반이 된다. - * 단 근육통은 운동 종료 후 날이 바뀔 때 생긴다. - * 근육통이 있는 기구로 운동했을 시 근육통 지속 기간은 그 날로부터 2일로 갱신된다. -* 하루가 지나면 전일 운동했던 다른 이용자들은 마지막 위치에서 시계방향으로 90도 회전한 위치에서 다음 날 운동을 시작한다. - * (0, 0)에서 (0, n)으로 회전하는 방향이 시계방향이다. - * 방향은 동 -> 북, 북 -> 서, 서 -> 남, 남 -> 동 방향으로 바뀐다. - * 다른 이용자들끼리의 위치 중복은 신경쓰지 않는다. - -현재 중량 cur_weight, 각 기구의 id가 담겨있는 정사각형의 2차원 배열 체육관 gym, 다른 이용자들의 x좌표, y좌표, 이동방향 d가 배열 형태로 담겨있는 2차원 배열 peoples, 각 기구 id의 index에 이용시 증량 무게가 담겨있는 배열 machines가 매개변수로 주어질 때 3대 500을 달성하기까지 걸리는 일 수를 return하도록 solution함수를 완성하라. - -#### 제한 사항 - -* gym의 한변의 길이인 n은 1이상 5 이하입니다. -* gym의 각 원소의 크기는 0이상 (machines배열의 길이 - 1)이하 입니다. -* peoples의 길이는 (gym의 한 변의 길이)^2 미만입니다. -* peoples의 각 요소는 [x좌표, y좌표, d이동방향]으로 이루어지며 d는 0, 1, 2, 3으로 이루어 집니다. - * 방향 0, 1, 2, 3은 각각 동, 서, 남, 북 방향이며 체육관의 0행쪽이 남쪽, 0열쪽이 서쪽이다. -* machines의 길이는 1이상 (gym의 한 변의 길이)^2 미만입니다. - -#### 입출력 예 - -| cur_weight | gym | peoples | machines | result | -| ---------- | ------------------------------------------------------------ | --------------------------------- | ----------------- | ------ | -| 3 | [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] | [[1, 2, 3], [3, 4, 2], [0, 4, 2]] | [100, 2, 3, 4, 5] | 5 | - -#### 입출력 예 설명 - -* 첫 날 사용할 수 있는 운동기구 조합 중 gym에서 가장 고 효율의 운동 조합은 증량 무게가 100인 0번 기구를 사용해 3번 운동하는 경우이며 각 운동마다 100, 50, 25의 증량을 얻어 운동 종료 후 현재 3대 무게는 178입니다. -* 첫날이 지난 후 peoples의 위치가 바뀌지만 최고 효율의 0번 기구는 근육통을 얻은 상태에서 이용해도 50, 25, 12의 중량을 얻어 265로 마무리 할 수 있습니다. -* 각 날마다 50, 25, 12로 87의 증량이 가능하며 5일 차 운동이 끝난 후 3대 526이 되어 목표를 달성합니다. - diff --git "a/\354\240\234\354\236\221/\354\227\260\354\243\274\354\231\200\355\227\254\354\212\244\354\236\245_LV4.py" "b/\354\240\234\354\236\221/\354\227\260\354\243\274\354\231\200\355\227\254\354\212\244\354\236\245_LV4.py" deleted file mode 100644 index 2c35c04..0000000 --- "a/\354\240\234\354\236\221/\354\227\260\354\243\274\354\231\200\355\227\254\354\212\244\354\236\245_LV4.py" +++ /dev/null @@ -1,107 +0,0 @@ -# 연주와헬스장_LV4.py -""" -하루 운동에 대한 선택은 실시 할 때마다 해당 기구의 운동 효율이 줄어들기 때문에 dfs로 3세트의 운동 조합을 산출했습니다. -dfs의 결과 최대 무게 증량이 가능한 운동 조합값을 하루단위로 저장할 maxw_a_day, used_a_day 변수로 -하루의 증량과 사용한 기구를 전역으로 관리했습니다. - -각 세트가 지날 때마다 이용자의 위치는 하루동안 동일하기 때문에 change_locations_each_set 함수를 통해 -dfs전 미리 연산해 others, others_1, others_2로 전역관리했습니다. - -하루 운동이 끝나면 그 날 이용한 기구들에 대해 근육통 counter인 exhausted 딕셔너리에 갱신을 해준 후 -maxw_a_day를 cur_weight에 더해 최대 중량을 갱신합니다. -다음날 이용자들 위치 연산을 위해 change_locations 함수를 통해 다음날 위치를 산출 해 주었고 -근육통이 지속되는 날짜에 대해 exhausted를 순회하며 1씩 감산 해주었습니다. -근육통이 끝나면 근육통 배열에서 삭제했습니다. -""" - -# 하루 운동할 때 3세트 운동한다. -def exercise(chosen, total, machines, gym): - global exhausted, maxw_a_day, used_a_day, others, others_1, others_2 - n = len(gym) - k = len(chosen) - # 진행한 세트 수에 따라 사람들의 위치가 바뀌거나 최대값들이 갱신된다. - if k == 0: - tmp_others = others - elif k == 1: - tmp_others = others_1 - elif k == 2: - tmp_others = others_2 - elif k == 3: - if maxw_a_day < total: - maxw_a_day = total - used_a_day = chosen - return - for i in range(n): - for j in range(n): - # 다른 사람이 쓰고있는 운동 기구는 쓰지 않습니다. - if (i, j) not in tmp_others: - # 선택하면 효율성 반으로. - machine_id = gym[i][j] - earn_weight = machines[machine_id] - if machine_id in exhausted: - earn_weight //= 2 - for choose in chosen: - if machine_id == choose: - earn_weight //= 2 - exercise(chosen + [machine_id], total + earn_weight, machines, gym) - -# 하루 지날 때 헬스장 이용자들의 위치 변화 -def change_locations(others, n): - ret = {} - for other in others: - x, y = other - d = (others[other] + 1) % 4 - ret[(y, n - x - 1)] = d - return ret - -# 한 세트 지날 때 헬스장 이용자들의 위치 변화 -def change_locations_each_set(others, n): - delta = ((0, 1), (1, 0), (0, -1), (-1, 0)) - ret = {} - for other in others: - x, y = other - d = others[other] - dx, dy = x + delta[d][0], y + delta[d][1] - if dx < 0 or dx >= n or dy < 0 or dy >= n: - d = (d + 2) % 4 - dx, dy = x + delta[d][0], y + delta[d][1] - ret[dx, dy] = d - return ret - - -def solution(cur_weight, gym, peoples, machines): - global maxw_a_day, exhausted, used_a_day, others, others_1, others_2 - days = 0 - exhausted = {} - # 다른 사람들 위치 dictionary에 저장. - others = {} - for x, y, d in peoples: - others[(x, y)] = d - while cur_weight < 500: - maxw_a_day, used_a_day = 0, [] - # 각 세트를 운동 한 후 헬스장 상태. - others_1 = change_locations_each_set(others, len(gym)) - others_2 = change_locations_each_set(others_1, len(gym)) - # 하루 운동해서 최댓값 증량 - exercise([], 0, machines, gym) - cur_weight += maxw_a_day - for each in used_a_day: - exhausted[each] = 3 - # 사람들 위치 변경 - others = change_locations(others_2, len(gym)) - # 날짜 변동 - days += 1 - # 날이 지나면 근육통 count - 1 - finish_exhausted = [] - for each_exercise in exhausted: - exhausted[each_exercise] -= 1 - if not exhausted[each_exercise]: - finish_exhausted.append(each_exercise) - for fin in finish_exhausted: - del exhausted[fin] - return days - - - -if __name__ == "__main__": - print(solution(3, [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], [[1, 2, 3], [3, 4, 2], [0, 4, 2]], [100, 2, 3, 4, 5])) \ No newline at end of file diff --git "a/\354\240\234\354\236\221/\354\233\220\352\265\220\352\267\274\352\263\265_LV3.md" "b/\354\240\234\354\236\221/\354\233\220\352\265\220\352\267\274\352\263\265_LV3.md" deleted file mode 100644 index 311eb67..0000000 --- "a/\354\240\234\354\236\221/\354\233\220\352\265\220\352\267\274\352\263\265_LV3.md" +++ /dev/null @@ -1,30 +0,0 @@ -# 원교근공 - -원교근공(遠交近攻)은 삼십육계의 계책 중 먼 곳과 사귀고 가까운 곳을 때리는 계책으로 먼 나라는 지리적인 차이로 굳이 싸울 필요 없다는 뜻입니다. - -연주나라의 승주왕은 전쟁 준비를 위해 원교근공에 따라 이웃하지 않은 나라들끼리 가장 강력한 동맹을 맺으려고 합니다. - -중복경유 없이 각 나라끼리 이동할 수 있는 경로는 반드시 하나만 존재합니다. - -예를 들어 승주왕의 나라를 0번이라 했을 때 각 나라의 군사력이 [70, 80, 100, 2000]이고 각 나라의 인접 상태가 [[0, 1], [1, 2], [2, 3]]일 때 승주 나라가 원교근공에 따라 최대 군사력 동맹을 맺는 경우는 [0, 3]이며 군사력 총 합은 2070이 됩니다. - -나라의 갯수 n, 승주왕의 나라의 번호 location, 각 나라의 군사력 배열 army_powers, 각 나라끼리 인접상태를 말하는 배열 edges가 매개변수로 주어질 때, 승주왕이 가장 강력한 동맹을 맺는 경우 동맹의 군사력 총 합과 동맹에 포함된 국가의 번호를 오름차순으로 정렬한 배열을 return하는 solution 함수를 완성해 주세요. - -#### 제한 사항 - -* location은 0이상 n미만입니다. -* edges의 길이는 n - 1입니다. -* edges는 방향이 없고 중복된 입력이 주어지지 않습니다. (ex. [a, b], [b, a]쌍은 주어지지 않음.) - -* 최대 군사력 동맹이 여러개일 경우 하나만 출력하면 됩니다. - -#### 입출력 예 - -| n | location | army_powers | edges | return | -| ---- | -------- | ------------------- | ------------------------ | -------------- | -| 4 | 0 | [70, 80, 100, 2000] | [[0, 1], [1, 2], [2, 3]] | (2070, [0, 3]) | - -#### 입출력 예 설명 - -* 승주왕의 나라인 0번 나라를 포함하고 인접한 1번 나라를 포함하지 않으며 나올 수 있는 조합은 [0, 2], [0, 3]입니다. -* 각 조합의 군사력 합은 170, 2070이며 최대 군사력인 2070을 만드는 [0, 3]조합이 최대 군사력 동맹입니다. \ No newline at end of file diff --git "a/\354\240\234\354\236\221/\354\233\220\352\265\220\352\267\274\352\263\265_LV3.py" "b/\354\240\234\354\236\221/\354\233\220\352\265\220\352\267\274\352\263\265_LV3.py" deleted file mode 100644 index d921e2d..0000000 --- "a/\354\240\234\354\236\221/\354\233\220\352\265\220\352\267\274\352\263\265_LV3.py" +++ /dev/null @@ -1,57 +0,0 @@ -# 원교근공_LV3 -""" -중복 경유없이 각 나라끼리 이동할 수 있는 경로가 반드시 하나만 존재하는 경우는 나라 간 연결이 tree의 형태를 이룰 때 입니다. -이에따라 location을 root로 하는 tree graph를 그립니다. -각 서브트리 루트까지의 최선의 결과는 상위 트리 결과를 연산할 때도 독립적으로 작용하기 때문에 -각 나라가 동맹에 속하는 경우와 속하지 않는 경우의 결과를 dynamic programming으로 구할 수 있습니다. -최종적으로 dp[location][1]에 location을 포함하는 최대의 연산 결과가 저장되며 같은 원리를 통해 -각 subtree의 root를 포함하는 경우와 포함하지 않는 경우를 역추적해 최종 동맹 allies에 포함 되는 지 여부를 판단할 수 있습니다. -""" -from collections import defaultdict - -def merge_power(u, army_powers): - global visited, dp, graph - visited[u] = True - dp[u][1] = army_powers[u] - dp[u][0] = 0 - for v in graph[u]: - if not visited[v]: - merge_power(v, army_powers) - dp[u][1] += dp[v][0] - dp[u][0] += max(dp[v][1], dp[v][0]) - - -def make_allies(u, is_having): - global graph, dp, visited, allies - visited[u] = True - if is_having and dp[u][1] > dp[u][0]: - allies.append(u) - is_having = False - else: - is_having = True - for v in graph[u]: - if not visited[v]: - make_allies(v, is_having) - - -def solution(n, location, army_powers, edges): - global visited, dp, graph, visited, allies - graph = defaultdict(list) - for a, b in edges: - graph[a] += [b] - graph[b] += [a] - dp = {i: [0, 0] for i in range(n)} - visited = {i: False for i in range(n)} - merge_power(location, army_powers) - max_power = dp[location][1] - allies = [location] - visited = {i: False for i in range(n)} - visited[location] = True - for v in graph[location]: - make_allies(v, False) - allies.sort() - return max_power, allies - - -if __name__ == "__main__": - print(solution(4, 0, [70, 80, 100, 2000], [[0, 1], [1, 2], [2, 3]])) \ No newline at end of file diff --git "a/\355\200\265\354\240\225\353\240\254.py" "b/\355\200\265\354\240\225\353\240\254.py" deleted file mode 100644 index e6277ca..0000000 --- "a/\355\200\265\354\240\225\353\240\254.py" +++ /dev/null @@ -1,42 +0,0 @@ -# 퀵정렬 - - -def quick_sort(arr): - if len(arr) <= 1: - return arr - pivot = arr[len(arr) // 2] - lesser_arr, equal_arr, greater_arr = [], [], [] - for num in arr: - if num < pivot: - lesser_arr.append(num) - elif num > pivot: - greater_arr.append(num) - else: - equal_arr.append(num) - return quick_sort(lesser_arr) + equal_arr + quick_sort(greater_arr) - - - -# 큇정렬 최적화(inplace)\ -def quick_sort(arr): - def sort(low, high): - if high <= low: - return - - mid = partition(low, high) - sort(low, mid - 1) - sort(mid, high) - - def partition(low, high): - pivot = arr[(low + high) // 2] - while low <= high: - while arr[low] < pivot: - low += 1 - while arr[high] > pivot: - high -= 1 - if low <= high: - arr[low], arr[high] = arr[high], arr[low] - low, high = low + 1, high - 1 - return low - - return sort(0, len(arr) - 1) \ No newline at end of file diff --git "a/\355\212\270\353\235\274\354\235\264.py" "b/\355\212\270\353\235\274\354\235\264.py" deleted file mode 100644 index c36555f..0000000 --- "a/\355\212\270\353\235\274\354\235\264.py" +++ /dev/null @@ -1,44 +0,0 @@ -class Node: - def __init__(self): - self.word = False - self.children = {} - -class Trie: - def __init__(self): - self.root = Node() - - def insert(self, word: str) -> None: - node = self.root - for char in word: - if char not in node.children: - node.children[char] = Node() - node = node.children[char] - node.word = True - - def search(self, word: str) -> bool: - node = self.root - for char in word: - if char not in node.children: - return False - node = node.children[char] - - return node.word - - def startsWith(self, prefix: str) -> bool: - node = self.root - for char in prefix: - if char not in node.children: - return False - node = node.children[char] - - return True - - def travel(self, level: int, node: Node) -> None: - if node.word: - return - - cur_children = sorted(node.children) - - for child in cur_children: - print("--"*level + child) - self.travel(level+1, node.children[child]) diff --git "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" "b/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" similarity index 97% rename from "programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" rename to "\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" index e1c41ed..567b5a6 100644 --- "a/programmers/\354\234\204\355\201\264\353\246\254 \354\261\214\353\246\260\354\247\200 \353\223\261 \352\270\260\355\203\200/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" +++ "b/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\230\244\355\224\210\354\261\204\355\214\205\353\260\251.py" @@ -1,20 +1,20 @@ -def solution(record): - answer = [] - userdict = {} - # mes : record의 message - # message를 받음과 동시에 유저 아이디 : 닉네임을 저장 - # Enter, Change가 들어온 경우 dictionary에 저장 - for mes in record: - if (mes.split(' ')[0] == 'Enter') | (mes.split(' ')[0] == 'Change'): - userdict[mes.split(' ')[1]] = mes.split(' ')[2] - - # for문을 돌면서, 하나씩 출력 - for mes in record: - if mes.split(' ')[0] == 'Enter': - # userdict[mes.split(' ')[1]] + '님이 들어왔습니다.' 이런식으로 해도 가능 - answer.append("{}님이 들어왔습니다.".format(userdict[mes.split(' ')[1]])) - elif mes.split(' ')[0] == 'Leave': - answer.append("{}님이 나갔습니다.".format(userdict[mes.split(' ')[1]])) - else: - pass +def solution(record): + answer = [] + userdict = {} + # mes : record의 message + # message를 받음과 동시에 유저 아이디 : 닉네임을 저장 + # Enter, Change가 들어온 경우 dictionary에 저장 + for mes in record: + if (mes.split(' ')[0] == 'Enter') | (mes.split(' ')[0] == 'Change'): + userdict[mes.split(' ')[1]] = mes.split(' ')[2] + + # for문을 돌면서, 하나씩 출력 + for mes in record: + if mes.split(' ')[0] == 'Enter': + # userdict[mes.split(' ')[1]] + '님이 들어왔습니다.' 이런식으로 해도 가능 + answer.append("{}님이 들어왔습니다.".format(userdict[mes.split(' ')[1]])) + elif mes.split(' ')[0] == 'Leave': + answer.append("{}님이 나갔습니다.".format(userdict[mes.split(' ')[1]])) + else: + pass return answer \ No newline at end of file