Problem:


Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
 :  :  :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.



Sample input:
3
1 2 300
3 3 600
1 4 800


Sample output:
2900
900
0
0

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
import sys
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LIR(n):
    return [LI() for i in range(n)]

def solve():
    n = I()
    p = LIR(n)
    p.sort()
    m = 1<<n
    s = 0
    for i,(x,y,num) in enumerate(p):
        d = min(abs(x),abs(y))
        s += num*d
        p[i].append(d)
    ans = [s]*(n+1)
    ans[-1] = 0
    pow = [1<<i for i in range(n)]
    dx = [[None]*m for i in range(n)]
    dy = [[None]*m for i in range(n)]
    for b in range(m):
        lx = []
        ly = []
        res = b
        for x,y,_,_ in p:
            j = res&1
            if j:
                lx.append(x)
                ly.append(y)
            res >>= 1
        ly.sort()
        for j,(x,y,num,d) in enumerate(p):
            i = bisect.bisect_right(lx,x)-1
            dxj = d
            dyj = d
            if i >= 0:
                nd = x-lx[i]
                if nd < dxj:
                    dxj = nd
            i += 1
            if i < len(lx):
                nd = lx[i]-x
                if nd < dxj:
                    dxj = nd
            i = bisect.bisect_right(ly,y)-1
            if i >= 0:
                nd = y-ly[i]
                if nd < dyj:
                    dyj = nd
            i += 1
            if i < len(ly):
                nd = ly[i]-y
                if nd < dyj:
                    dyj = nd
            dx[j][b] = dxj*num
            dy[j][b] = dyj*num
    m = 3**n
    for b in range(m-1):
        kx = ky = cnt = 0
        res = b
        for i in range(n):
            j = res%3
            if j:
                cnt += 1
                if j == 1:
                    kx |= pow[i]
                else:
                    ky |= pow[i]
            res //= 3
        s = 0
        ans_ = ans[cnt]
        for i in range(n):
            num = p[i][2]
            d = min(dx[i][kx],dy[i][ky])
            s += d
            if s >= ans_:
                break
        else:
            if s == 0:
                for i in range(cnt,n+1):
                    ans[i] = 0
                break
            ans[cnt] = s
    for i in ans:
        print(i)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    p = LIR(n)
    p.sort()
    m = 1<<n
    s = 0
    for i,(x,y,num) in enumerate(p):
        d = min(abs(x),abs(y))
        s += num*d
        p[i].append(d)
    ans = [s]*(n+1)
    ans[-1] = 0
    pow = [1<<i for i in range(n)]
    dx = [[None]*m for i in range(n)]
    dy = [[None]*m for i in range(n)]
    for b in range(m):
        lx = []
        ly = []
        res = b
        for x,y,_,_ in p:
            j = res&1
            if j:
                lx.append(x)
                ly.append(y)
            res >>= 1
        ly.sort()
        for j,(x,y,num,d) in enumerate(p):
            i = bisect.bisect_left(lx,x)-1
            dxj = d
            dyj = d
            if i >= 0:
                nd = x-lx[i]
                if nd < dxj:
                    dxj = nd
            i += 1
            if i < len(lx):
                nd = lx[i]-x
                if nd < dxj:
                    dxj = nd
            i = bisect.bisect_left(ly,y)-1
            if i >= 0:
                nd = y-ly[i]
                if nd < dyj:
                    dyj = nd
            i += 1
            if i < len(ly):
                nd = ly[i]-y
                if nd < dyj:
                    dyj = nd
            dx[j][b] = dxj*num
            dy[j][b] = dyj*num
    m = 3**n
    for b in range(m-1):
        kx = ky = cnt = 0
        res = b
        for i in range(n):
            j = res%3
            if j:
                cnt += 1
                if j == 1:
                    kx |= pow[i]
                else:
                    ky |= pow[i]
            res //= 3
        s = 0
        ans_ = ans[cnt]
        for i in range(n):
            num = p[i][2]
            d = min(dx[i][kx],dy[i][ky])
            s += d
            if s >= ans_:
                break
        else:
            if s == 0:
                for i in range(cnt,n+1):
                    ans[i] = 0
                break
            ans[cnt] = s
    for i in ans:
        print(i)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import sys
from itertools import combinations_with_replacement, product
import numpy as np
def input(): return sys.stdin.readline().rstrip()


def kyori(xlist, ylist, x, y):
    return min(np.min(np.abs(np.array(xlist)-x)), np.min(np.abs(np.array(ylist)-y)))


def main():
    n = int(input())
    li = []
    x = set()
    y = set()
    for _ in range(n):
        xi, yi, pi = map(int, input().split())
        li.append([xi, yi, pi])
    klist=[10**10]*(n+1)    
    for xyr in list(product([0, 1, 2], repeat=n)):
        nowx={0}
        nowy={0}
        for i in range(n):
            if xyr[i] == 1:
                nowx.add(li[i][0])
            elif xyr[i] == 2:
                nowy.add(li[i][1])
        nowx=list(nowx)
        nowy=list(nowy)
        cost=0
        k=len(nowx)+len(nowy)-2
        for lis in li:
            cost += kyori(nowx, nowy, lis[0], lis[1])*lis[2]
        klist[k]=min(klist[k], cost)

    for g in range(n+1):
        print(klist[g])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
readline=sys.stdin.readline

N=int(readline())
X = [None] * N
Y = [None] * N
P = [None] * N
for i in range(N):
  X[i],Y[i],P[i] = map(int,readline().split())

# 必ずいずれかの都市と重なるように作るのが合理的。
# 従い、縦15通り横15通りの最大30パターンを毎回試せばよい
# 縦、横ともに、どの筋に道路が通っているかのリスト（最大15）を持ち、
# 最も近い道路を検索できるようにする(小さいのでソートや二分探索不要)

xroad = [0]
yroad = [0]

def calc_S(xroad, yroad):
  S = 0
  for i in range(N):
    # 都市iに関して
    # X軸で最も近い道路を探す
    mindist = 10 ** 10
    for x in range(len(xroad)):
      if abs(X[i] - xroad[x]) < mindist:
        mindist = abs(X[i] - xroad[x])
    # Y軸で最も近い道路を探す
    for y in range(len(yroad)):
      if abs(Y[i] - yroad[y]) < mindist:
        mindist = abs(Y[i] - yroad[y])
    S += mindist * P[i]
  return S

# 道路を指定したときの各都市からの距離を返す
def calc_segment(road):
  R = [None] * N
  #print("road",road)
  for i in range(N):
    mindist = 10 ** 10
    for p in range(len(road)):
      if abs(X[i] - road[p]) < mindist:
        mindist = abs(X[i] - road[p])
    R[i] = mindist * P[i]
  #print("R",R)
  return R

# 初期状態
#print(calc_S(xroad, yroad))

# それぞれ算出しておく
# X軸方向に0～15本引いた場合の各i都市のX軸の値
# Y軸方向に0～15本引いた場合の各i都市のX軸の値

# ループ内で、本数の和がKになるように各組み合わせを試す

# X軸方向
x_pairs = [[] for i in range(N + 1)]
for i in range(2 ** N):
  xroad = [0]
  #print("bin(i)",bin(i))
  for j in range(N):
    if (i >> j) & 1:
      xroad.append(X[j])
    xr = calc_segment(xroad)
    num = bin(i).count("1")
    #print("xr",xr,"x_pairs",x_pairs)
    x_pairs[num] += [xr]

#print("x_pairs",x_pairs)

y_pairs = [[] * N for i in range(N + 1)]
for i in range(2 ** N):
  yroad = [0]
  for j in range(N):
    if (i >> j) & 1:
      yroad.append(X[j])
    yr = calc_segment(yroad)
    num = bin(i).count("1")
    y_pairs[num] += [yr]

for K in range(N + 1):
  # 和がKになるように、x_pairsとy_pairsから配列を取得する
  ans = 10 ** 10
  for x in range(K + 1):
    y = K - x
    x_list = x_pairs[x]
    y_list = y_pairs[y]
    dist = 0
    for xl in x_list:
      for yl in x_list:
        for i in range(N):
          dist += min(xl[i], yl[i])
    if ans > dist:
      ans = dist
  print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
xyp = []
XY = [(0, 0), (0, 1)]
for _ in range(n):
    x, y, p = map(int, input().split())
    xyp.append((x, y, p))
    XY.append((x, 0))
    XY.append((y, 1))

# 各XYに対して予め距離を計算しておく
dists = [[0]*len(XY) for _ in range(n)]
for i, (x, y, p) in enumerate(xyp):
    for j, (corr, r) in enumerate(XY):
        if r == 0:
            dists[i][j] = abs(corr - x) * p
        else:
            dists[i][j] = abs(corr - y) * p

anss = [10**9] * (n+1)
from itertools import combinations
jlist = list(range(2, len(XY)))
for nn in range(n):
    for js in combinations(jlist, nn):
        cost = 0
        for i, (x, y, p) in enumerate(xyp):
            x_dist = dists[i][0]
            y_dist = dists[i][1]
            for j in js:
                corr, r = XY[j]
                if r == 0:
                    x_dist = min(x_dist, dists[i][j])
                else:
                    y_dist = min(y_dist, dists[i][j])
            cost += min(x_dist, y_dist)
            if cost > anss[nn]:
                break
        anss[nn] = min(anss[nn], cost)

for ans in anss:
    if ans == 10**9:
        print(0)
    else:
        print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
xyp = []
XY = [(0, 0), (0, 1)]
for _ in range(n):
    x, y, p = map(int, input().split())
    xyp.append((x, y, p))
    XY.append((x, 0))
    XY.append((y, 1))

anss = [10**9] * (n+1)
from itertools import combinations
for nn in range(n):
    for xy in combinations(XY, nn):
        x_trains = [0]
        y_trains = [0]
        for corr, r in xy:
            if r == 0:
                x_trains.append(corr)
            else:
                y_trains.append(corr)

        cost = 0
        for x, y, p in xyp:
            x_dist = min(map(lambda xx: abs(xx-x), x_trains))
            y_dist = min(map(lambda yy: abs(yy-y), y_trains))
            cost += min(x_dist, y_dist)*p
            if anss[nn] < cost:
                break
        anss[nn] = min(anss[nn], cost)

for ans in anss:
    if ans == 10**9:
        print(0)
    else:
        print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
P=[list(map(int,input().split())) for _ in range(N)]
ans=0
for i in range(N):
  ans+=min(abs(P[i][0]),abs(P[i][1]))*P[i][2]
print(ans)
if N==1:
  exit()
x=[0]
y=[0]
z=[]
for l in range(N):
  cns=10**12
  for i in range(N):
    if i in z:
      continue
    for j in range(2):
      bns=0
      for k in range(N):
        if i==k:
          continue
        s=10**5
        for u in x:
          s=min(abs(u-P[k][0]),s)
        s=min(s,abs(P[k][j]-P[i][j]))
        for v in y:
          s=min(abs(v-P[k][1]),s)
        bns+=s*P[k][2]
      if bns<cns:
        cns=bns
        a=i
        b=j
  if b==0:
    x.append(P[a][b])
  else:
    y.append(P[a][b])
  z.append(a)
  print(cns)

Submission status: Wrong Answer

Solution code:
N=int(input())
P=[list(map(int,input().split())) for _ in range(N)]
ans=0
for i in range(N):
  ans+=min(abs(P[i][0]),abs(P[i][1]))*P[i][2]
print(ans)
if N==1:
  exit()
x=[0]
y=[0]
z=[]
for l in range(N):
  cns=10**12
  for i in range(N):
    if i in z:
      continue
    for j in range(2):
      bns=0
      for k in range(N):
        if i==k:
          continue
        s=10**5
        for u in x:
          s=min(abs(u-P[k][0]),s)
        s=min(s,abs(P[k][j]-P[i][j]))
        for v in y:
          s=min(abs(v-P[k][1]),s)
        bns+=s*P[k][2]
      if bns<cns:
        cns=bns
        a=i
  x.append(P[a][0])
  y.append(P[a][1])
  z.append(a)
  print(cns)

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n = int(readline())
lst1 = []
for i in range(n):
    x,y,p = map(int,readline().split())
    lst1.append([x,y,p])
made = [(0,0)] #(x=1に引いたならば(1,0)みたいな)

def funcx(i):
    res = made + [(lst1[i][0],0)]
    ret = 0
    for i in range(n):
        loss = 10**24
        for j in range(len(res)):
            x = min(abs(res[j][0]-lst1[i][0]),abs(lst1[i][0]-res[j][0]))
            y = min(abs(res[j][1]-lst1[i][1]),abs(lst1[i][1]-res[j][1]))
            loss = min(loss,lst1[i][2]*min(x,y))
        ret += loss
    return ret

def funcy(i):
    res = made + [(0,lst1[i][1])]
    ret = 0
    for i in range(n):
        loss = 10**24
        for j in range(len(res)):
            x = min(abs(res[j][0]-lst1[i][0]),abs(lst1[i][0]-res[j][0]))
            y = min(abs(res[j][1]-lst1[i][1]),abs(lst1[i][1]-res[j][1]))
            loss = min(loss,lst1[i][2]*min(x,y))
        ret += loss
    return ret

#初回手動
ret = 0
res = made
for i in range(n):
    loss = 10**24
    for j in range(len(res)):
        x = min(abs(res[j][0]-lst1[i][0]),abs(lst1[i][0]-res[j][0]))
        y = min(abs(res[j][1]-lst1[i][1]),abs(lst1[i][1]-res[j][1]))
        loss = min(loss,lst1[i][2]*min(x,y))
    ret += loss
print(ret)

mura = 0
for i in range(n): #各路線について
    minloss = 10**24
    kouho = (0,0)
    for j in range(n): #各村について
        #x軸アプローチ
        res1 = funcx(j)
        #y軸アプローチ
        res2 = funcy(j)
        if res1<res2:
            if res1 < minloss:
                minloss = res1
                kouho = (lst1[j][0],0)
        else:
            if res2 < minloss:
                minloss = res2
                kouho = (0,lst1[j][1])
    made.append(kouho)
    print(minloss)

Submission status: Wrong Answer

Solution code:
import itertools
#import bisect

def main():
  N = int(input())
  X = []
  Y = []
  P = []
  for _ in range(N):
    x, y, p = [int(x) for x in input().split()]
    X.append(x)
    Y.append(y)
    P.append(p)
  Ms = [15 * 10000] * (N + 1)
  Mm = [[10000] * N  for _ in range(N+1)]
  
  for selected in itertools.product([0, 1, 2], repeat=N):
    #print(selected)
    LX = sorted([0] + [X[i] for i, s in enumerate(selected) if s == 1])
    LY = sorted([0] + [Y[i] for i, s in enumerate(selected) if s == 2])
    # print(LX, LY)
    
    S = 0
    for i in range(N):
      if selected[i]:
        continue
      M = 10000
      for x in LX:
        M = min(M, abs(x - X[i]))
      for y in LY:
        M = min(M, abs(y - Y[i]))
      S += M * P[i]
    count = sum([ x > 0 for x in selected])
    Ms[count] = min(Ms[count], S)
      
  for m in Ms:
    print(m)
      
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# Fast IO (only use in integer input)

import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

N = int(input())
Resident = []
for i in range(N):
    x,y,p = map(int,input().split())
    Resident.append((x,y,p))

minCost = [-1] * (N+1)

preCalRange = 1 << N

horizontalLineDistance = []
verticalLineDistance = []

for i in range(preCalRange):
    railRoad = []
    tmp = i
    for j in range(N):
        railRoad.append(tmp % 2)
        tmp //= 2
    minDistance = [-1] * N
    for j in range(N):
        minDistance[j] = min(abs(Resident[j][0]),abs(Resident[j][1]))
        for k in range(N):
            if railRoad[k] == 1 and abs(Resident[j][0] - Resident[k][0]) < minDistance[j]:
                minDistance[j] = abs(Resident[j][0] - Resident[k][0])
    horizontalLineDistance.append(tuple(minDistance))
    minDistance = [-1] * N
    for j in range(N):
        minDistance[j] = min(abs(Resident[j][0]),abs(Resident[j][1]))
        for k in range(N):
            if railRoad[k] == 1 and abs(Resident[j][1] - Resident[k][1]) < minDistance[j]:
                minDistance[j] = abs(Resident[j][1] - Resident[k][1])
    verticalLineDistance.append(tuple(minDistance))

# totalCases = 3 ** N

# for i in range(totalCases):
#     railRoad = []
#     tmp = i
#     for j in range(N):
#         railRoad.append(tmp % 3)
#         tmp //= 3
#     horizontalCount = 0
#     verticalCount = 0
#     numNewRailroad = 0
#     for j in range(N):
#         if railRoad[j] == 1:
#             numNewRailroad += 1
#             horizontalCount += 1 << j
#         if railRoad[j] == 2:
#             verticalCount += 1 << j
#             numNewRailroad += 1
#     minDistance = []
#     for j in range(N):
#         minDistance.append(min(horizontalLineDistance[horizontalCount][j], verticalLineDistance[verticalCount][j]))

#     cost = 0
#     for j in range(N):
#         cost += Resident[j][2] * minDistance[j]
#     if minCost[numNewRailroad] == -1 or minCost[numNewRailroad] > cost:
#         minCost[numNewRailroad] = cost
# for elem in minCost:
#     print(elem)

Submission status: Wrong Answer

Solution code:
from itertools import product
import sys

input = sys.stdin.buffer.readline

n = int(input())
infi = 10 ** 10
kouho = []
for _ in range(n):
    x, y, p = map(int, input().split())
    cos = min(abs(x), abs(y)) * p
    kouho.append((cos, x, y, p))
kouho.sort(reverse=True)

kumiawase = list(product([0, 1, 2], repeat=n))

ans = [infi] * (n + 1)
for kumi in kumiawase:
    xroad = [0]
    yroad = [0]
    cnt = 0
    for i in range(n):
        _, x, y, p = kouho[i]
        if kumi[i] == 1:
            xroad.append(x)
            cnt += 1
        elif kumi[i] == 2:
            yroad.append(y)
            cnt += 1
    res1 = 0
    for i in range(n):
        temp = infi
        _, x, y, p = kouho[i]
        for xval in xroad:
            temp = min(temp, p * abs(xval - x))
        for yval in yroad:
            temp = min(temp, p * abs(y - yval))
        res1 += temp
    ans[cnt] = min(ans[cnt], res1)


print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
from itertools import product
import sys

input = sys.stdin.buffer.readline

n = int(input())
infi = 10 ** 10
kouho = []
for _ in range(n):
    x, y, p = map(int, input().split())
    cos = min(abs(x), abs(y)) * p
    kouho.append((cos, x, y, p))
kouho.sort(reverse=True)

kumiawase = list(product([0, 1, 2], repeat=n))

ans = [infi] * (n + 1)
for kumi in kumiawase:
    for kumi in kumiawase:
        xroad = [0]
        yroad = [0]
        cnt = 0
        for i in range(n):
            _, x, y, p = kouho[i]
            if kumi[i] == 1:
                xroad.append(x)
                cnt += 1
            elif kumi[i] == 2:
                yroad.append(y)
                cnt += 1
        res1 = 0
        for i in range(n):
            temp = infi
            _, x, y, p = kouho[i]
            for xval in xroad:
                temp = min(temp, p * abs(xval - x))
            for yval in yroad:
                temp = min(temp, p * abs(y - yval))
            res1 += temp
        ans[cnt] = min(ans[cnt], res1)


print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
n = int(input())
lst = []
for i in range(n):
  x,y,p = map(int,input().split())
  lst.append((x,y,p))

lst = sorted(lst, key=lambda k: k[2], reverse=True)
ans_lst = [10**18]*(n+1)
train_lst = [[(0, 0), (0, 1)]]
while len(train_lst) > 0:
  tmp = train_lst.pop()
  count = 0
  for i in range(n):
    min_ = 10**18
    town = lst[i]
    for j in range(len(tmp)):
      min_ = min(min_, town[2] * abs(town[tmp[j][1]]-tmp[j][0]))
    count += min_
  ans_lst[len(tmp)-2] = min(ans_lst[len(tmp)-2], count)
  if len(tmp) < n+2:
    train_lst.append(tmp+[(lst[len(tmp)-2][0], 0)])
    train_lst.append(tmp+[(lst[len(tmp)-2][1], 1)])

for i in range(n+1):
  print(ans_lst[i])

Submission status: Wrong Answer

Solution code:
# Fast IO (only use in integer input)

# import os,io
# input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

N = int(input())
Resident = []
for i in range(N):
    x,y,p = map(int,input().split())
    Resident.append((x,y,p))

minCost = [-1] * (N+1)

preCalRange = 1 << N

horizontalLineDistance = []
verticalLineDistance = []

for i in range(preCalRange):
    railRoad = []
    tmp = i
    for j in range(N):
        railRoad.append(tmp % 3)
        tmp //= 2
    minDistance = [-1] * N
    for j in range(N):
        minDistance[j] = min(abs(Resident[j][0]),abs(Resident[j][1]))
        for k in range(N):
            if railRoad[k] == 1 and abs(Resident[j][0] - Resident[k][0]) < minDistance[j]:
                minDistance[j] = abs(Resident[j][0] - Resident[k][0])
    horizontalLineDistance.append(tuple(minDistance))
    minDistance = [-1] * N
    for j in range(N):
        minDistance[j] = min(abs(Resident[j][0]),abs(Resident[j][1]))
        for k in range(N):
            if railRoad[k] == 1 and abs(Resident[j][1] - Resident[k][1]) < minDistance[j]:
                minDistance[j] = abs(Resident[j][1] - Resident[k][1])
    verticalLineDistance.append(tuple(minDistance))

totalCases = 3 ** N

for i in range(totalCases):
    railRoad = []
    tmp = i
    for j in range(N):
        railRoad.append(tmp % 3)
        tmp //= 3
    numNewRailroad = sum(map(lambda x: 1 if x != 0 else 0,railRoad))
    horizontalCount = 0
    verticalCount = 0
    for j in range(N):
        if railRoad[j] == 1:
            horizontalCount += 1 << j
        if railRoad[j] == 2:
            verticalCount += 1 << j
    minDistance = [-1] * N
    for j in range(N):
        minDistance[j] = min(horizontalLineDistance[horizontalCount][j], verticalLineDistance[verticalCount][j])

    cost = 0
    for j in range(N):
        cost += Resident[j][2] * minDistance[j]
    if minCost[numNewRailroad] == -1 or minCost[numNewRailroad] > cost:
        minCost[numNewRailroad] = cost
for elem in minCost:
    print(elem)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = []
Y = []
P = []
R = []
for i in range(N):
    x, y, p = map(int, input().split())
    if x == 0 or y == 0:
        continue
    X.append(x)
    Y.append(y)
    P.append(p)
    R.append(p*min(abs(x), abs(y)))

if len(X) == 0:
    for K in range(0,N+1):
        print(0)
else:
    def get_index(array):
        array_c = list(set(array))
        array_c = sorted(array_c)
        map_ = { a:i for i, a in enumerate(array_c) }
        return [ map_[a] for a in array ], array_c

    X_int, X_inverse = get_index(X)
    Y_int, Y_inverse = get_index(Y)

    x_int_max = max(X_int)
    y_int_max = max(Y_int)

    candidates = [ ('x', i) for i in range(x_int_max+1) ] + [ ('y', i) for i in range(y_int_max+1) ]
    M = len(candidates)

    import itertools

    def get_dist(x,y,c):
        if c[0] == 'x':
            x0 = X_inverse[c[1]]
            return abs(x0-x)
        if c[0] == 'y':
            y0 = Y_inverse[c[1]]
            return abs(y0-y)

    cost = []
    for x,y,p,r in zip(X,Y,P,R):
        cost.append({ c:min(r, get_dist(x,y,c)*p) for c in candidates })

    print(sum(R))
    for K in range(1,N+1):
        # if K <= M/2:
        if K < min(x_int_max, y_int_max):
            S_ref = None
            for cand in itertools.combinations(candidates, K):
                S = sum([ min([ C[c_] for c_ in cand ]) for C in cost ])
                if S_ref is None:
                    S_ref = S
                elif S_ref > S:
                    S_ref = S
            print(S_ref)
        #elif K < M:
        #     break
        else:
            print(0)

Submission status: Wrong Answer

Solution code:
import itertools

N = int(input())
X = []
Y = []
P = []
for i in range(N):
    x, y, p = map(int, input().split())
    X.append(x)
    Y.append(y)
    P.append(p)

# N = 3
# X = [1, 3, 1]
# Y = [2, 3, 4]
# P = [300, 600, 800]

# N = 5
# X = [3, 5, 5, 5, 7]
# Y = [5, 3, 5, 7, 5]
# P = [400, 700, 1000, 700, 400]


# 地下鉄は集落を通るようなものにすれば、どうにか歩数を最小化できる。
Xsubway = list(set(X)) 
Ysubway = list(set(Y)) 
for i in range(len(Ysubway)):
    Ysubway[i] += 50000 # 南北方向の地下鉄は、座標+50000 して処理する。もっといい方法あるかもしれない。

# 建設する地下鉄のリスト。40000～60000は南北のもの。
Xsubway.extend(Ysubway)

# S: 建設される地下鉄の数
for S in range(N+1):
    # S本の地下鉄の建設計画の組み合わせパターンを列挙
    plan_subway = list(itertools.combinations(Xsubway, S))
#     print(plan_subway)
    
    minwalk_plan = 15*10000*1000000
    # 地下鉄S本を仮に建設した場合の歩行距離を計算する。
    for elem in plan_subway:
        # elme にはタプル形式で地下鉄一覧が入ってる。
        # N個の集落それぞれについて、どの地下鉄との距離が最短化を算出しつつ、
        # 全市民の歩行距離の和を算出
        walk = 0
        for i in range(N):
            minwalk_elem = min(abs(X[i]), abs(Y[i]))
            for j in list(elem):
                if j >= 40000: # この場合、y=j-50000の直線の東西方向の地下鉄。
                    minwalk_elem = min(minwalk_elem, abs(Y[i]-(j-50000)))
                else: # この場合、x=jの南北方向の地下鉄。
                    minwalk_elem = min(minwalk_elem, abs(X[i]-j))
            
            walk += minwalk_elem*P[i]
        
        if walk < minwalk_plan:
            minwalk_plan = walk
                                       
    print(minwalk_plan)

Submission status: Wrong Answer

Solution code:
import sys
from itertools import combinations

def solve():
      input = sys.stdin.readline
      N = int(input())
      Ans = [10 ** 10] * (N + 1)
      Res = [None] * N
      for i in range(N):
            Res[i] = [int(j) for j in input().split()]
      
      for i in range(3 ** N):
            Bit = i
            count = N
            NS = [0]
            EW = [0]
            for j in range(N):
                  if Bit % 3 == 0: NS.append(Res[j][0])
                  elif Bit % 3 == 1: EW.append(Res[j][1])
                  else: count -= 1
                  Bit //= 3

            cost = 0
            for j in range(N):
                  d = 10 ** 10
                  for n in NS: d = min(d, abs(n - Res[j][0]))
                  for n in EW: d = min(d, abs(n - Res[j][1]))
                  cost += d * Res[j][2]
            Ans[count] = min(Ans[count], cost)
                  

      print(*Ans, sep="\n")

      return 0

if __name__ == "__main__":
      solve()

Submission status: Wrong Answer

Solution code:
import sys
from itertools import combinations

def solve():
      input = sys.stdin.readline
      N = int(input())
      Ans = [10 ** 10] * (N + 1)
      Res = [None] * N
      for i in range(N):
            Res[i] = [int(j) for j in input().split()]
      
      for i in range(3 ** N):
            Bit = i
            count = N
            NS = [0]
            EW = [0]
            for j in range(N):
                  if Bit % 3 == 0: NS.append(Res[j][0])
                  elif Bit % 3 == 1: NS.append(Res[j][1])
                  else: count -= 1
                  Bit //= 3

            cost = 0
            for j in range(N):
                  d = 10 ** 10
                  for n in NS: d = min(d, abs(n - Res[j][0]))
                  for n in EW: d = min(d, abs(n - Res[j][1]))
                  cost += d * Res[j][2]
            Ans[count] = min(Ans[count], cost)
                  

      print(*Ans, sep="\n")

      return 0

if __name__ == "__main__":
      solve()