Binary Search

Introduction

https://www.acmicpc.net/step/29

랜선 자르기

import sys
input = sys.stdin.readline

K, N = map(int,input().split())
lan = []
for _ in range(K):
    lan.append(int(input()))
lan.sort()

def binary_search(in_arr, answer, start, end, target):
    # 연산 부분
    # 어떤 값 x 범위 (0,max(in_arr))
    # 조건: sum([length//x for length in in_arr]) == target
    if start > end:
        return answer
    x = (start+end)//2
    # Zero Division Error 처리.
    # start와 end가 0이라는 것은 선의 길이가 1인 것과 같음
    if x == 0:
        return 1
    # 그 외
    else:
        val = sum([length//x for length in in_arr])
        if val >= target:
            answer = x
            return binary_search(in_arr, answer, x+1, end, target)
        else:
            return binary_search(in_arr, answer, start, x-1, target)

print(binary_search(lan,0,0,lan[-1],N))

나무 자르기

python3로 실행하면 시간 초과가 발생한다.

pypy3로 실행해야 한다.

import sys
input = sys.stdin.readline

N, M = map(int,input().split())
tree = list(map(int,input().split()))
tree.sort()

def binary_search(in_arr, answer, start, end, target):
    # 연산 부분
    # 어떤 값 x 범위 (0,max(in_arr))
    # 조건: sum([max(0,length-x) for length in in_arr]) == target
    if start > end:
        return answer
    x = (start+end)//2
    # 탐색 부분
    val = sum([max(0,length-x) for length in in_arr])
    if val >= target:
        answer = x
        return binary_search(in_arr, answer, x+1, end, target)
    else:
        return binary_search(in_arr, answer, start, x-1, target)

print(binary_search(tree,0,0,tree[-1],M))

공유기 설치

K번째 수

2022

Stack

1 minute read

Introduction

Stack

less than 1 minute read

Introduction

Download-only-one-directory

less than 1 minute read

Git 명령어를 사용한 하위 디렉토리 다운로드 Clone 할 로컬 저장소 생성

Sort

3 minute read

Introduction

Tree

less than 1 minute read

Introduction

Mutex library on C++

less than 1 minute read

#include <iostream> #include <thread> #include <chrono> #include <mutex> #include <atomic> #include <string.h>

TODO

less than 1 minute read

how to costom github blog using jekyll

Welcome to Jekyll!

less than 1 minute read

You’ll find this post in your _posts directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different wa...

Back to top ↑