본문 바로가기
알고리즘/[python] 백준 BOJ

[python] 백준 2141 우체국

by Alan_Kim 2023. 4. 9.
728x90
반응형

https://www.acmicpc.net/problem/2141

 

2141번: 우체국

첫째 줄에 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 X[1], A[1], X[2], A[2], …, X[N], A[N]이 주어진다. 범위는 |X[i]| ≤ 1,000,000,000, 1 ≤ A[i] ≤ 1,000,000,000 이며 모든 입력은 정수이다.

www.acmicpc.net

 

문제 해결

$ L_{1} $ 공간에서 $ \sum_{i=1}^{n} |x_{i}-a| \times b $ 의 최솟값은 표본의 중앙값이 위치한 값이라는 것을 이용하는 문제이다.

https://math.stackexchange.com/questions/4410205/minimum-value-of-sum-of-absolute-diferences

 

minimum value of sum of absolute diferences

i was thinking about finding a $x$ that minimize the function $f(x)=\sum_{i=0}^{n}|x-a_i|$. I plot this function in geogebra (here is the url) and i saw that the function have an x that minimize it...

math.stackexchange.com

 

 

CODE

import sys
INF = sys.maxsize
n = int(input())
location = []
p = 0
for i in range(1,n+1):
    a, b = map(int, input().split())
    location.append([a,b])
    p += b
location.sort(key= lambda x : x[0])

cnt = 0
for i in range(n):
    cnt += location[i][1]
    if cnt >= p/2:
        print(location[i][0])
        break
728x90
반응형

댓글