백준 2143 두 배열의 합 풀이 ( 파이썬 )
2143번: 두 배열의 합
첫째 줄에 T(-1,000,000,000 ≤ T ≤ 1,000,000,000)가 주어진다. 다음 줄에는 n(1 ≤ n ≤ 1,000)이 주어지고, 그 다음 줄에 n개의 정수로 A[1], …, A[n]이 주어진다. 다음 줄에는 m(1≤m≤1,000)이 주어지고, 그 다
www.acmicpc.net
부분합을 담아 놓고 배열 하나는 오름차순 정렬 하나는 내림차순 정렬로 바꾸어 합이 t 보다 작을 때는 오름차순 한 리스트의 인덱스를 1 증가시키고 합이 t보다 클 때는 내림차순 한 리스트의 인덱스를 1 증가시킨다.
만약 합이 t와 같다면 바로 answer를 1 증가 시키지 않고 각 리스트에 같은 값이 있는지 검사해줘야 한다.
t=int(input())
n=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
lenA=len(a)
lenB=len(b)
for i in range(lenA):
add=a[i]
for j in range(i+1,lenA):
add+=(a[j])
a.append(add)
for i in range(lenB):
add=b[i]
for j in range(i+1,lenB):
add+=(b[j])
b.append(add)
a.sort()
b.sort(reverse=True)
indexA=0
indexB=0
answer=0
lenA=len(a)
lenB=len(b)
while (indexA<lenA and indexB<lenB):
# 합이 t와 같을 때
if (a[indexA]+b[indexB])==t:
cntA=0
cntB=0
subsumA=a[indexA]
subsumB=b[indexB]
# 합이 같을 때 각 리스트에 같은 값이 있는지 확인
while indexA<lenA:
if subsumA == a[indexA]:
cntA+=1
indexA+=1
else:
break
while indexB<lenB:
if subsumB == b[indexB]:
cntB+=1
indexB+=1
else:
break
answer+=(cntA*cntB)
# 합이 t보다 작을 때
elif (a[indexA]+b[indexB])<t:
indexA+=1
# 합이 t보다 클 때
else:
indexB+=1
print(answer)
[ baekjoon ] 트리의 지름 1967번 ( python ) (0) | 2021.05.08 |
---|---|
[ baekjoon ] 트리의 부모 찾기 11725번 ( python ) (0) | 2021.05.07 |
[ baekjoon ] 신기한 소수 2023번 ( python ) (0) | 2021.04.14 |
[ baekjoon ] 비숍 1799번 ( python, java ) (0) | 2021.04.14 |
[ baekjoon ] 폰 호석만 ( python ) (0) | 2021.04.11 |