오늘도 그리디에 관한 문제를 풀었다. 익숙해진 느낌이지만 아직 확실한 포인트를 못잡는 문제들이 가끔 있다. (골드 등급의 문제들이 그렇다.) 이런 문제들은 머릿속에 계속 기억해두고 같은 일이 반복되지 않도록 하는 것이 중요하다고 생각한다.
또한 이번주 주말부터 코딩테스트 스터디를 진행하기로 했다. 주말 오전 10시부터 12시까지는 필수 참여이고 코딩테스트 책을 중심으로 학습할 것이기에 도움이 될 것이라고 생각한다. 실력이 늘면 알고리즘 대회도 참여해볼 계획이다.
백준 1541번 잃어버린 괄호
import sys
sic = sys.stdin.readline().split('-')
gwalho = list()
res = 0
for i in sic:
count = 0
sp_i = i.split('+')
for j in sp_i:
count += int(j)
gwalho.append(count)
res += gwalho[0]
for k in range(1,len(gwalho)):
res -= gwalho[k]
print(res)
백준 11501번 주식
'''시간초과
import sys
T = int(sys.stdin.readline())
for _ in range(T):
N = int(sys.stdin.readline())
price = list(map(int, sys.stdin.readline().split()))
total = 0
for i in range(len(price)-1):
count = price.pop(0)
if max(price)-count>0:
total+= max(price)-count
print(total)
'''
import sys
T = int(sys.stdin.readline())
for _ in range(T):
N = int(sys.stdin.readline())
price = list(map(int,sys.stdin.readline().split()))
total = 0
for i in range(N-2,-1,-1):
if price[i] > price[-1]: # 맨 뒤의 값이 작다면 update
price[-1] = price[i]
else:
total += price[-1]-price[i] # 맨 뒤의 값이 크다면 total에 추가 (이득값)
print(total)
백준 1744번 수 묶기
'''틀린 코드
짜다가 이 방식은 모든 경우의 수를 고려하기 힘들다고 생각해서 멈춤.
또한 직관적이지도 못함.
import sys
T = int(sys.stdin.readline())
N_lst = list()
for _ in range(T):
N_lst.append(int(sys.stdin.readline()))
N_lst.sort(reverse=True)
count = 0
while N_lst:
if N_lst[0]==1 and N_lst[1]==1:
count += N_lst[0] + N_lst[1]
del N_lst[0]
del N_lst[0]
elif N_lst[0]>0 and N_lst[1]>0:
count += N_lst[0]*N_lst[1]
del N_lst[0]
del N_lst[0]
elif N_lst[0]==0 and N_lst[1]<0:
del N_lst[0]
del N_lst[0]
else:
count += N_lst[0]
del N_lst[0]
print(count)
'''
# 수 묶기를 이용하는 것이 중요하다.
# 0,양수 = 덧셈
# 0,음수 = 곱셈
# 1,양수 = 덧셈
# 1,음수 = 덧셈 -> 따라서, 1 = 덧셈
# 양수,양수 = 곱셈
# 음수,음수 = 곱셈
# 양수,음수 = 덧셈
import sys
T = int(sys.stdin.readline())
pos = []
neg = []
count = 0
for _ in range(T): # 양수,음수를 나누어 저장한다.
N = int(sys.stdin.readline())
if N > 1:
pos.append(N)
elif N == 1:
count += 1
else:
neg.append(N)
pos.sort(reverse=True)
if len(pos) % 2 == 0: # 양수가 짝수개
for i in range(0,len(pos),2):
count += pos[i]*pos[i+1]
else: # 양수가 홀수개
for j in range(0,len(pos)-1,2):
count += pos[j]*pos[j+1]
count += pos[len(pos)-1]
neg.sort()
if len(neg) % 2 == 0: # 음수가 짝수개
for k in range(0, len(neg), 2):
count += neg[k]*neg[k+1]
else: # 음수가 홀수개
for l in range(0, len(neg)-1, 2):
count += neg[l]*neg[l+1]
count += neg[len(neg)-1]
print(count)