[BOJ] 2831

nerry·2022년 2월 8일
0

알고리즘

목록 보기
36/86

문제

me

import sys
input = sys.stdin.readline

N=int(input())
men = list(map(int,input().split()))
women = list(map(int,input().split()))

men.sort(key=lambda x:(abs(x),x))
women.sort(key=lambda x:(abs(x),x))

front,back=-1,N
cnt=0

res=[]
for man in men:
    if man<0:
        while front<N:
            front+=1
            if women[front]>0 :
                if -man > women[front]:
                    women[front]=0
                    cnt+=1
                break

    else:
        while back>-1:
            back -= 1
            if women[back] < 0:
                if man < -women[back]:
                    print('in')
                    women[back]=0
                    cnt += 1
                break
print(cnt)

변수 두 개를 써서 조건에 맞는지 확인을 했다.
테스트 케이스도, 내가 생각한 케이스도 잘 나와서 왜 틀렸습니다 가 나오는지 잘 모르겠다..
반례를 찾지 못했다..

solution

import sys
def conditionalCounter(boysOrGirlsPostive,girlsOrBoysnegative):
    postive=boysOrGirlsPostive
    negative=girlsOrBoysnegative
    def counter():
        count=0
        while postive and negative:
            if postive[-1]+negative[-1]<0:
                count+=1
                postive.pop()
                negative.pop()
            else:
                postive.pop()
        return count
    return counter
    
if __name__ == "__main__":
    input()

    boys=list(map(int,sys.stdin.readline().rstrip().split()))
    girls=list(map(int,sys.stdin.readline().rstrip().split()))

    boysPostive=sorted([i for i in boys if i>0])
    boysNegative=sorted([i for i in boys if i<0],reverse=True)
    girlsPostive=sorted([i for i in girls if i>0])
    girlsNegative=sorted([i for i in girls if i<0],reverse=True)

    bpgn=conditionalCounter(boysPostive,girlsNegative)
    gpbn=conditionalCounter(girlsPostive,boysNegative)

    print(bpgn()+gpbn())

배열을 각각 양수, 음수 기준으로 둘로 나누어 총 4개의 배열로 만들고, 서로 반대되는 부호를 갖는 남녀 배열을 비교해서 합이 음수이면 count를 해주는 방식.. 맨 앞 칸을 기준으로 하기에 매번 pop을 해줘야 한다. 합이 양수면 양수 쪽을 pop 시켜야 한다. (왜? 양수의 값이 음수보다 크니깐이라는데 이해가 안간다.

출처

profile
터벅터벅 개발(은좋은)자 로그

0개의 댓글