RUBY

[백준] 부분합 본문

PS/BOJ

[백준] 부분합

RUBY_루비 2020. 9. 21. 23:59

출처:: www.acmicpc.net/problem/1806

분류:: 구간 합(prefix sum) , 투포인터 

 

1. 문제 이해 및 해결과정

5 10
1 2 3 4 5
# 3,4,5(12) => 3
10 10
1 1 1 1 1 1 1 1 1 10
# 10 -> 1

 

2. 풀이방법

 1. python 투포인터 

#부분합
#https://www.acmicpc.net/problem/1806
import sys
sys.stdin = open("input.txt","r")
n,m=map(int,input().split()) #n,목표
arr=list(map(int,input().split()))

s,e=0,0
sum=0
sol=1e9
tmp=0
for s in range(n):
    while e<n and sum<m:
        sum+=arr[e]
        e+=1
    if sum>=m: #부분합이 m이상일때
        tmp=e-s #길이
        sol=min(sol,tmp) #가장짧은 것의 길이 
        sum-=arr[s]
if sol==1e9:
    print(0)
else:
    print(sol)

 2. 구간합(prefix sum) , 투포인터

#부분합
#https://www.acmicpc.net/problem/1806
import sys
sys.stdin = open("input.txt","r")
n,m=map(int,input().split()) #n,목표
arr=list(map(int,input().split()))
prefix=[0] #prefixsum
tmp=0
for x in arr:
    tmp+=x
    prefix.append(tmp)

s,e=0,0
sol=1e9

while s!=n:
    if prefix[e]-prefix[s]>=m: #부분합의 차이가 m이상이라면
        sol=min(sol,e-s)
        s+=1
    else: #부분합의 차이가 m미만 이면
        if e!=n:
            e+=1
        else:
            s+=1
if sol==1e9:
    print(0)
else:
    print(sol)

 

 

3. 오답원인

 

4. 알게된 점

 

'PS > BOJ' 카테고리의 다른 글

[백준] 최단 경로  (0) 2020.09.24
[백준] 빗물  (0) 2020.09.23
[백준] 로봇 청소기 | 삼성  (0) 2020.09.20
[백준] 부등호  (0) 2020.09.18
[백준] 소수의 연속합  (0) 2020.09.18
Comments