๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/๋ฐฑ์ค€

[๋ฐฑ์ค€] #15922 ์•„์šฐ์œผ ์šฐ์•„์œผ์ด์•ผ!! (Python)

์•„์šฐ์œผ ์šฐ์•„์œผ์ด์•ผ!!

๋ฌธ์ œ

์ฒซ์งธ ์ค„์— ์ˆ˜์ง์„  ์œ„์— ๊ทธ๋ฆด ์„ ๋ถ„์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค
๋‘˜์งธ ์ค„ ๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ์ขŒํ‘œ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ •์ˆ˜์Œ (x, y)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค
N๊ฐœ์˜ ์„ ๋ถ„์„ ๋ชจ๋‘ ๊ทธ๋ ธ์„ ๋•Œ, ์ˆ˜์ง์„  ์œ„์— ๊ทธ์–ด์ง„ ์„ ๋ถ„ ๊ธธ์ด์˜ ์ดํ•ฉ์„ ์ถœ๋ ฅ
๊ฒน์น˜๋Š” ๋ถ€๋ถ„์ด ์žˆ์„ ์ˆ˜ ์žˆ์Œ์„ ๊ณ ๋ คํ•˜์—ฌ ์„ ๋ถ„์˜ ๊ธธ์ด์˜ ์ดํ•ฉ์„ ์ถœ๋ ฅํ•ด์•ผํ•œ๋‹ค.

์˜ˆ์ œ

์ž…๋ ฅ
5
-5 -2
-3 0
2 5
6 10
8 12

์ถœ๋ ฅ
14
์ž…๋ ฅ
2
-1000000000 1000000000
-1 1

์ถœ๋ ฅ
2000000000

๋ฌธ์ œ ํ’€์ด ์ „๋žต

[[-5, -2], [-3, 0], [2, 5], [6, 10], [8, 12]]
[[-1000000000, 1000000000], [-1, 1]]

  • ํ˜„์žฌ๊ฐ’๊ณผ ์ด์ „๊ฐ’์ด ๊ฒน์น˜๋Š” ์ƒํƒœ์ธ์ง€, ์•„๋‹Œ์ง€๋ฅผ ๊ณ ๋ คํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ‘ผ๋‹ค.
    1) ๊ฒน์น˜๋Š” ๋ถ€๋ถ„์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ

-> [-5, -2], [-3, 0] : ๊ธธ์ด = 0-(-5) = 5

-> [-1000000000, 1000000000], [-1, 1] : ๊ธธ์ด = 2000000000

2) ๊ฒน์น˜๋Š” ๋ถ€๋ถ„์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ
[2, 5], [6, 10] : ๊ธธ์ด= 10-6 = 4

์ „์ฒด ๊ธธ์ด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ณ€์ˆ˜์— ๊ณ„์†ํ•ด์„œ ์—…๋ฐ์ดํŠธ

Results

Version Memory Time(ms) info
solution1.py 48500KB 4048ms Baseline

Solution 1

N = int(input())#N๊ฐœ์˜ ์„ ๋ถ„
lines = []
for _ in range(N):
    lines.append(list(map(int,input().split())))

pre_s, pre_e = lines[0][0],lines[0][1]
length = pre_e-pre_s

for i in range(1,N):
    cur_s,cur_e = lines[i][0],lines[i][1]
    if cur_s < pre_e: #ํ˜„์žฌ_s <์ด์ „_e -> ๋‘˜์ด ๊ฒน์น˜๋Š” ๋ถ€๋ถ„ ์กด์žฌ
        if cur_e < pre_e:#๋‘๋ฒˆ์งธ์ผ€์ด์Šค -> ์•„์˜ˆ ํ˜„์žฌ๊ฐ’์ด ์ด์ „๊ฐ’ ์•ˆ์— ์žˆ๋Š” ๊ฒฝ์šฐ
            continue
        else: #ํ•œ์ชฝ๋งŒ ๊ฒน์น˜๋Š” ๊ฒฝ์šฐ 
            length +=  cur_e - pre_e #ํ˜„์žฌ_e - ์ด์ „_e ๊ธธ์ด ๋”ํ•ด์คŒ
    else: #๊ฒน์น˜๋Š” ๋ถ€๋ถ„์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด
        length += cur_e - cur_s #ํ˜„์žฌ์„ ๋ถ„๊ธธ์ด๋งŒ ๋”ํ•ด์คŒ
    pre_s,pre_e = cur_s,cur_e #ํ˜„์žฌ๊ฐ’์„ ์ „๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธ ํ•ด์คŒ
print(length)