백준 10828/1920

chi·2023년 3월 23일

백준

목록 보기
1/20
import sys
input=sys.stdin.readline
num=int(input())
stack=[]
while num>0:
    fs=str(input())
    fs=fs.split()
    s=fs[0]
    if s=="push":
        stack.append(fs[1])
    elif s=="pop":
        if len(stack)==0:
            print(-1)
        else:
            print(stack[-1])
            del stack[-1]
    elif s=="size":
        print(len(stack))
    elif s=="empty":
        if len(stack)==0:
            print(1)
        else:
            print(0)
    elif s=="top":
        if len(stack)==0:
            print(-1)
        else:
            print(stack[-1])
    num-=1
import sys
input=sys.stdin.readline

이거 추가해야 시간초과안남

Q input=sys.stdin.readline 이거 하면 이 뒤로 input쓰면 다 저거로 대체되는 거임? 뭐야
아무때나 사용하셔도 됩니다.

주의할 점은 숫자가 아닌 문자열로 입력을 받는 경우엔 줄바꿈(\n)까지 입력으로 받으니 input().strip() 을 사용하거나 input().strip().split() 을 사용하시는게 좋습니다.

n = int(input())

stack = []
point = -1

#command = ["push","pop","size","empty","top"]

for i in range(n):
    c = list(input().split())
    
    if c[0] == "push":
        c[1] = int(c[1])
        stack.append(c[1])
        point += 1
    elif c[0] == "pop":
        if point >= 0:
            print(stack[point])
            del stack[point]
            point -= 1
        else :
            print(-1)
    elif c[0] == "size":
        print((point+1))
    elif c[0] == "empty":
        if point == -1 :
            print(1)
        else :
            print(0)
    elif c[0] == "top":
        if point >= 0:
            print(stack[point])
        else :
            print(-1)

이렇게 포인터 변수를 써야하나? 내 코드랑 비교
아니 내 코드에서 sys.stdin.readline 이거 써서 다시 해봐

sys.stdin.readline()

반복으로 여러줄 입력받을 때는 input()으로하면 시간초과 걸림
근데 sys.stdin.readline() 이거로 받으면 한 줄 단위로 입력받기에 /n까지 같이 받음. 따로 개행문자 제거하려면 뒤에 rstrip() 붙여야 됨.
sys.stdin.readline().rstrip()
그리고 문자열형으로 저장돼서 형 변환을 해줘야 됨. 이때도 개행문자 제거돼서 굳이 rstip() 안 붙여도 됨
int(sys.stdin.readline())
근데 str(sys.stdin.readline())은 안 통하네 문자열로 이미 저장된 거라 문자열형으로 바꿔도 개행문자는 안 없어짐
sys.stdin.readline().split()해야 문자열 리스트로 저장됨

https://mgyo.tistory.com/166

https://velog.io/@yeseolee/Python-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%9E%85%EB%A0%A5-%EC%A0%95%EB%A6%ACsys.stdin.readline

https://enjoyso.tistory.com/71

map()

>>> a = [1.2, 2.5, 3.7, 4.6]
>>> a = list(map(int, a))
>>> a
[1, 2, 3, 4]

리스트 안에 있는 모든 요소에 저 함수를 적용시키는 거
!원래 리스트 안의 요소들 다 int로 바꾸려면 반복문 써서 a[i]=int(a[i]) 이런 식으로 하는데 시간 엄청 걸림

한 줄에 여러개 입력받을 때

import sys
a,b,c=map(int,sys.stdin.readline().split())
Q sys.stdin.readline()가 문자열형태로 저장되니까 일단 문자열 split해주고 (근데 이렇게하면 /n까지 되나?
ㄴ ㄴㄴ/n은 포함 안 됨

list(map( ))


map 하고 꼭 list해줘야 리스트로 저장되는군,..
그냥 list(map(어쩌고)) 세트로 외워야될 듯

n번 입력받아 2차원 리스트에 저장하는 경우

import sys
n=int(sys.stdin.readline())
what=[]
for i in range(n):
	what.append(list(map(int,sys.stdin.readline().split())))

1920번

내 코드(시간 초과)

import sys
input=sys.stdin.readline
num= int(input())
nums= str(input())
nums=nums.split() 
num1= int(input())
nums1= str(input())
nums1=nums1.split() 
i=0
while num1>0:
    if nums1[i] in nums:
        print(1)
    else:
        print(0)
    i+=1
    num1-=1

set와 list 시간복잡도

https://velog.io/@ready2start/Python-%EC%84%B8%ED%8A%B8set%EC%9D%98-%EC%8B%9C%EA%B0%84-%EB%B3%B5%EC%9E%A1%EB%8F%84

리스트를 세트로 변환?이랑 그냥 애초에 세트로 저장...
nums 가 그럼 키 값이 따로 없는데 어떻게 해시함수로 짧게 찾는 거임?

내 코드(성공...했지만)

import sys
sys.stdin.readline()
nums=set(map(int,sys.stdin.readline().split()))
for i in range(int(sys.stdin.readline())):
    for n in list(map(int,sys.stdin.readline().split())):
        if n in nums:
            print(1)
        else:
            print(0)


시간 뭐임

남의 코드1

import sys
from bisect import bisect_left, bisect_right
n1 = int(input())
arr1 = list(map(int,sys.stdin.readline().rstrip().split()))
arr1.sort()
n2 = int(input())
arr2 = list(map(int,sys.stdin.readline().rstrip().split()))
for i in arr2:
  a = bisect_left(arr1,i)
  b = bisect_right(arr1,i)
  if(b-a >0):
    print(1)
  else:
    print(0)

남의 코드2(시간 적게 걸리고 간결함)

N = int(input())
A = list(input().split())
A = set(A)
M = int(input())
B = list(input().split())

for b in B:
    if b in A:
        print(1)
    else:
        print(0)

for b in B 처럼 내가 한 d[i] 가 아니더라도 이렇게 쓸 수 있군
이번 문제는 입력받는 것보다 찾는 ㄴ거에서 시간을 단축시키는 게 나은가? sys가 생각보다 시간을 많이 잡아먹나?? 뭐지
남의 코드3

import sys
input = sys.stdin.readline
N = int(input())
l = list((map(int, input().split())))
d = dict(zip(l, l))

M = int(input())
list_M = list(map(int, input().split()))
for num in list_M:
  if d.get(num) == None: print(0)
  else: print(1)

남의 코드4 (??!!!!!!)

a, b = open(0).readlines()[1::2]
a = set(map(int, a.split()))
print('\n'.join(map(str, [1 if int(x) in a else 0 for x in b.split()])))

남의 코드5

a = int(input())
exist = set(map(int, input().split()))
b = int(input())
find = list(map(int, input().split()))

for i in find:
    if i in exist:
        print(1)
    else:
        print(0)

1920 재도전 (성공)

import sys
input=sys.stdin.readline
a=input()
b=set(input().split())
c=int(input())
d=input().split()
for i in range(c):
    if d[i] in b:
        print(1)
    else:
        print(0)

0개의 댓글