[BOJ] #1027 ๊ณ ์ธต ๊ฑด๋ฌผ(Bruteforce, Python)

    ๋ฐ˜์‘ํ˜•

    ๐ŸŒฑ ๋ฌธ์ œ

     

    1027๋ฒˆ: ๊ณ ์ธต ๊ฑด๋ฌผ

    ์„ธ์ค€์‹œ์—๋Š” ๊ณ ์ธต ๋นŒ๋”ฉ์ด ๋งŽ๋‹ค. ์„ธ์ค€์‹œ์˜ ์„œ๋ฏผ ๊น€์ง€๋ฏผ์€ ๊ฐ€์žฅ ๋งŽ์€ ๊ณ ์ธต ๋นŒ๋”ฉ์ด ๋ณด์ด๋Š” ๊ณ ์ธต ๋นŒ๋”ฉ์„ ์ฐพ์œผ๋ ค๊ณ  ํ•œ๋‹ค. ๋นŒ๋”ฉ์€ ์ด N๊ฐœ๊ฐ€ ์žˆ๋Š”๋ฐ, ๋นŒ๋”ฉ์€ ์„ ๋ถ„์œผ๋กœ ๋‚˜ํƒ€๋‚ธ๋‹ค. i๋ฒˆ์งธ ๋นŒ๋”ฉ (1๋ถ€ํ„ฐ ์‹œ์ž‘)

    www.acmicpc.net

     

    ๐ŸŒฑ ํ’€์ด

    1. ๊ธฐ์šธ๊ธฐ ๊ณ„์‚ฐ

    def calc_gradient(x1, y1, x2, y2):
        if x1 == x2:
            return 0
        gradient = (y2 - y1) / (x2 - x1)
        return gradient

    ๊ฑด๋ฌผ์ด ๋ณด์ด๋Š”์ง€ ์—ฌ๋ถ€๋Š” ๊ธฐ์šธ๊ธฐ์— ๋”ฐ๋ผ ๊ฒฐ์ •๋˜๋ฏ€๋กœ ๊ธฐ์šธ๊ธฐ๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.

     

    1. ์™„์ „ํƒ์ƒ‰ (Bruteforce)

    results = []
    for idx in range(len(buildings)):
        cnt = 0
    
        min_gradient = INF
        for i in range(idx - 1, -1, -1):
            gradient = calc_gradient(i, buildings[i], idx, buildings[idx])
            if gradient < min_gradient:
                cnt += 1
                min_gradient = gradient
    
        max_gradient = -INF
        for i in range(idx + 1, len(buildings)):
            gradient = calc_gradient(i, buildings[i], idx, buildings[idx])
            if gradient > max_gradient:
                cnt += 1
                max_gradient = gradient
    
        results.append(cnt)
    • ์™„์ „ํƒ์ƒ‰์œผ๋กœ ๋ชจ๋“  ๊ฑด๋ฌผ๋“ค์˜ ๊ธฐ์šธ๊ธฐ๋ฅผ ๋น„๊ตํ•˜์—ฌ ๋ณด์ด๋Š” ๊ฑด๋ฌผ์˜ ๊ฐœ์ˆ˜(cnt)๋ฅผ ์นด์šดํŠธํ•ฉ๋‹ˆ๋‹ค.
    • ์™ผ์ชฝ ๊ฑด๋ฌผ๋“ค์€ ํ˜„์žฌ๊นŒ์ง€ ์ธก์ •ํ•œ ์ตœ์†Œ ๊ธฐ์šธ๊ธฐ(min_gradient)๋ณด๋‹ค ๊ธฐ์šธ๊ธฐ๊ฐ€ ํฌ๋ฉด ๋ณด์ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
    • ์˜ค๋ฅธ์ชฝ ๊ฑด๋ฌผ๋“ค์€ ํ˜„์žฌ๊นŒ์ง€ ์ธก์ •ํ•œ ์ตœ๋Œ€ ๊ธฐ์šธ๊ธฐ(max_gradient)๋ณด๋‹ค ๊ธฐ์šธ๊ธฐ๊ฐ€ ์ž‘์œผ๋ฉด ๋ณด์ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

     

    ๐ŸŒฑ ์ฝ”๋“œ

    # !usr/bin/env python
    # -*- coding: utf-8 -*-
    # boj 1027 ๊ณ ์ธต๊ฑด๋ฌผ
    
    import sys
    INF = sys.maxsize
    
    n = int(input())
    buildings = list(map(int, input().split()))
    
    def calc_gradient(x1, y1, x2, y2):
        if x1 == x2:
            return 0
        gradient = (y2 - y1) / (x2 - x1)
        return gradient
    
    results = []
    for idx in range(len(buildings)):
        cnt = 0
    
        min_gradient = INF
        for i in range(idx - 1, -1, -1):
            gradient = calc_gradient(i, buildings[i], idx, buildings[idx])
            if gradient < min_gradient:
                cnt += 1
                min_gradient = gradient
    
        max_gradient = -INF
        for i in range(idx + 1, len(buildings)):
            gradient = calc_gradient(i, buildings[i], idx, buildings[idx])
            if gradient > max_gradient:
                cnt += 1
                max_gradient = gradient
    
        results.append(cnt)
    
    print(max(results))

     

    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€