Algorithm/Python

Algorithm/Python

[백준] 11725 트리의 부모 찾기

https://www.acmicpc.net/problem/11725 1 - 6 => 1을 통해서 둘 중 부모가 1이란 것을 알 수 있음1. 입력받은 연결을 가지고 인접 행렬 만듦 2. 1부터 차례대로 트리 연결하며, 배열에 부모 저장 3. 저장한 배열 출력1 - 6 - 3 - 5 - 4 - 2 - 7 이렇게 자식이 하나 이상인 경우가 있기 때문에, 인접 행렬에서 부모를 뺀 후 iter의 형태로 자식들을 모두 스택에 넣어야 한다.import sysfrom collections import defaultdictinput=sys.stdin.readlineadj = defaultdict(list)n = int(input())parent = [0 for _ in range(n+1)]for _ in..

Algorithm/Python

[백준] 1987 알파벳

https://www.acmicpc.net/problem/1987BFS 로 처리 어려움➡️왜냐하면 지금까지 지나왔던 알파벳을 누적 저장해야 함따라서 Backtracking으로 처리하되, 길을 더 갈 수 없다면 지금까지 경로 길이를 이전에 저장해둔 최장의 길이와 비교하여 더 길 경우 갱신알파벳의 경우 갯수가 정해져 있으므로 boolean 타입의 길이 26인 배열 사용하여 지금까지 지나 온 알파벳 체크 그러나 dfs로 모든 루트 검사할 경우, 반복적으로 같은 지점 들릴 수 있음 => DP 사용하여 반복 계산 줄이기import sysfrom collections import dequeinput = sys.stdin.readliner, c = map(int, input().split())board = [inpu..

Algorithm/Python

[백준] 2161 카드 1

https://www.acmicpc.net/problem/2161deque를 사용해 맨 앞과 뒤에서 pop, push 일어나는 것 사용!from collections import dequeimport sysn = int(sys.stdin.readline())cards = deque(i for i in range(1, n+1))while cards: print(cards.popleft(), end=" ") if cards : cards.append(cards.popleft())

Algorithm/Python

[백준] 15649 N과 M (1)

https://www.acmicpc.net/problem/15649백트래킹 기법을 통해 출력import sysinput = sys.stdin.readlinen, m = map(int, input().split())check = [False] * (n+1)num = []def dfs(left): # 남은 개수가 0이면 지금까지 쌓은 조합/순열을 출력 if left == 0: print(*num) return for i in range(1, n+1): if not check[i]: check[i] = True # i를 선택했으니 표시 num.append(i) # 경로에 추가 ..

Algorithm/Python

[백준] 3085 사탕 게임

https://www.acmicpc.net/problem/3085문제에 제대로 나와 있지 않아 처음에 조금 고민했는데,알고 보니 딱 하나를 옆의 것과 바꿨을 때를 고려하는 것이다.즉, 현재 사탕과 다른 바로 옆/아래의 사탕을 바꿨을 때의 연속된 같은 사탕 개수 중 최대 값을 구하면 된다.그냥 브루트포스 문제이다.import sysinput = sys.stdin.readlinemaxcnt=0n = int(input())board=[]for _ in range(n): board.append(list(input().rstrip()))def checkarr(board, x): global maxcnt secnt=1 for j in range(1,n): if board[j-1][..

Algorithm/Python

[백준] 14501 퇴사

https://www.acmicpc.net/problem/14501import sysinput= sys.stdin.readlinen = int(input())dp=[[0,0] for _ in range(n+1)]for i in range(1,n+1): dp[i] = list(map(int,input().split())) # t, p maxsum= max((x[1] for x in dp[:i] if x[0] 해당 문제는 DP 문제로,현재 시점에서 상담을 채택한다고 했을 때, 현재 상담이 가능케 하는 상담 기록 중 누적 합이 가장 큰 값을 골라서, 현재 상담의 값을 더해 저장하고, 이 상담을 채택했을 때 다음 상담은 언제 가능한지 기록한다.즉,다음 상담 가능 날짜 / 누적값이런 형태로 저장하면 된..

Algorithm/Python

[백준] 25206 너의 평점은

https://www.acmicpc.net/problem/25206자릿수 제한 없이 오차 10^-4 이하면 정답으로 인정되기 때문에, 딱히 자릿수를 건드리거나 할 필요 없이 계산하면 된다.import sysinput= sys.stdin.readlinesum=0cnt=0degdict = { 'A+': 4.5, 'A0': 4.0, 'B+': 3.5, 'B0': 3.0, 'C+': 2.5, 'C0': 2.0, 'D+': 1.5, 'D0': 1.0, 'F': 0.0}for _ in range(20): arr = list(input().split()) if arr[2]=='P': continue sum+=degdict[arr[2]]*float(a..

Algorithm/Python

[백준] 1918 후위 표기식

import sysfrom collections import dequearr = sys.stdin.readline().rstrip()stack =[]answer=""prior = { '+' : 1, '-':1, '*' : 2, '/': 2 }for x in arr: if x.isalpha(): answer+=x elif x in "+-*/": while stack and stack[-1] !='(' and prior[stack[-1]] >= prior[x]: answer+=stack.pop() stack.append(x) elif x=='(': stack.append(x) elif x=='..

Algorithm/Python

[백준] 10866

https://www.acmicpc.net/problem/10866문제에서 시킨 대로 구현하면 된다.import sysinput = sys.stdin.readlinewrite = sys.stdout.writen = int(input())deque = list()for _ in range(n): inst = list(input().split()) if inst[0]== "push_front": deque.insert(0,inst[1]) elif inst[0]=="push_back": deque.append(inst[1]) elif inst[0]=="pop_front": if len(deque)>0: write(str(deque.pop(0))+"\n..

Algorithm/Python

[백준] 13701 중복 제거

https://www.acmicpc.net/problem/13701틀린 답안import sysinput = sys.stdin.readlinenums = set()for x in map(int, input().split()): if x not in nums: sys.stdout.write(str(x) + ' ') nums.add(x) 비트마스킹으로 풀어야 한다!! 메모리가 작아서 set도 못 쓴다..물론 한 줄로 입력 받아버려도 메모리가 안 돼서 한 글자씩 처리해야 한다!아래는 통과한 코드이다...import sysvisited = bytearray(1 > 3 bit_offset = num & 7 mask = 1

yoursin
'Algorithm/Python' 카테고리의 글 목록 (6 Page)