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: Time Limit Exceeded

Solution code:
import sys

N = int(input())
XYP = [list(map(int, input().split())) for _ in range(N)]

bits = 1 << N

xmemo = [[sys.maxsize]*N for _ in range(bits)]
ymemo = [[sys.maxsize]*N for _ in range(bits)]

for b in range(bits):
  for i in range(N):
    xmemo[b][i] = min(XYP[i][2]*abs(XYP[i][0]), xmemo[b][i])
    ymemo[b][i] = min(XYP[i][2]*abs(XYP[i][1]), ymemo[b][i])
    if not (b & (1<<i)):
      continue
    for j in range(N):
      xmemo[b][j] = min(XYP[j][2]*abs(XYP[i][0]-XYP[j][0]), xmemo[b][j])
      ymemo[b][j] = min(XYP[j][2]*abs(XYP[i][1]-XYP[j][1]), ymemo[b][j])
      
ans = [sys.maxsize]*(N+1)

for b in range(bits):
  b_ = b
  cnt = bin(b_).count('1')
  while b_ >= 0:
    b_ &= b
    yi = b - b_
    tmp = 0
    for i in range(N):
      tmp += min(xmemo[b_][i], ymemo[yi][i])
    ans[cnt] = min(ans[cnt], tmp)
    b_ -= 1
  
for i in range(N+1):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import sys, queue, math, copy, itertools, bisect, collections, heapq


def main():
    INF = 10 ** 15
    LI = lambda: [int(x) for x in sys.stdin.readline().split()]
    NI = lambda: int(sys.stdin.readline())

    N = NI()
    X = []
    Y = []
    P = []

    for _ in range(N):
        a, b, c = LI()
        X.append(a)
        Y.append(b)
        P.append(c)

    r = []
    for a, b, c in zip(X, Y, P):
        r.append(min(abs(a), abs(b)) * c)

    hor = [copy.copy(r) for _ in range(2 ** N)]
    ver = [copy.copy(r) for _ in range(2 ** N)]

    for i in range(2 ** N):
        k = i
        for b in range(N):
            if k % 2 == 1:
                for j in range(N):
                    hor[i][j] = min(hor[i][j], abs(X[j] - X[b]) * P[j])
                    ver[i][j] = min(ver[i][j], abs(Y[j] - Y[b]) * P[j])
            k //= 2

    ans = [INF] * (N + 1)
    for i in range(3 ** N):
        cnt:int = 0
        bx:int = 0
        by:int = 0
        bit:int = 1
        for b in range(N):
            if i % 3 == 1:
                bx += bit
                cnt += 1
            elif i % 3 == 2:
                by += bit
                cnt += 1
            bit *= 2
            i //= 3
        s:int = 0
        if ans[cnt] == 0: continue 
        for b in range(N):
            s += min(hor[bx][b], ver[by][b])
        ans[cnt] = min(ans[cnt], s)

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
XYP = [list(map(int, input().split())) for _ in range(N)]

bits = 1 << N

xmemo = [[float('inf')]*N for _ in range(bits)]
ymemo = [[float('inf')]*N for _ in range(bits)]

for b in range(bits):
  for i in range(N):
    xmemo[b][i] = min(XYP[i][2]*abs(XYP[i][0]), xmemo[b][i])
    ymemo[b][i] = min(XYP[i][2]*abs(XYP[i][1]), ymemo[b][i])
    if not (b & (1<<i)):
      continue
    for j in range(N):
      xmemo[b][j] = min(XYP[j][2]*abs(XYP[i][0]-XYP[j][0]), xmemo[b][j])
      ymemo[b][j] = min(XYP[j][2]*abs(XYP[i][1]-XYP[j][1]), ymemo[b][j])
      
ans = [float('inf')]*(N+1)

for b in range(bits):
  b_ = b
  cnt = bin(b_).count('1')
  while b_ >= 0:
    b_ &= b
    yi = b - b_
    tmp = 0
    for i in range(N):
      tmp += min(xmemo[b_][i], ymemo[yi][i])
    ans[cnt] = min(ans[cnt], tmp)
    b_ -= 1
  
for i in range(N+1):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = []; Y = []; P = []
INF = float("inf")
for i in range(N):
  x,y,p = list(map(int,input().split()))
  X.append(x);Y.append(y);P.append(p)
ans = [INF for _ in range(N+1)] #0本置いた時からN本置いた時までN+1個
def calc(A):
  n = len(A) #Aにはいくつ入っているか。つまり、xoryで選ばれたものはいくつあるか。
  A.sort()
  res = [INF for _ in range(n+1)] #道が0本からn本
  for s in range(1<<n): #選ばれたものを全探索
    p = [] #最初の大通り
    for i in range(n):
      if (s>>i)&1 == 1: #bitが立っている位置は道があるので追加
        p.append(A[i][0])
    #p.sort()
    now = 0 #現在の移動距離
    pi = 0 #i個目の町の位置よりも小さい位置
    for i in range(n): #i個目の町に注目
      #m = INF
      x = A[i][0] #xoryとして選ばれた町のi番目の位置。
      while pi+1 < len(p) and p[pi+1] < x:
        pi += 1
      m = abs(x)
      if pi < len(p):
        m = min(m,abs(x-p[pi]))
      if pi+1 < len(p):
        m = min(m,abs(x-p[pi+1]))
      #for j in range(len(p)): #すべての道に対して愚直に最短距離を求める。
      #  m = min(m,abs(p[j]-A[i][0]))
      now += m*A[i][1] #最短距離×人数
    b = len(p) #道を何本追加したか。1を引くのは最初の大通り。
    res[b] = min(res[b],now)
  return res
    

for s in range(1<<N): #x軸にするかをbitで全探索
  AX = [];AY = [] #Aは選ばれた村を追加していく。2**N回これは更新される。
  for i in range(N):
    if (s>>i)&1 == 1: #x軸で見る
      AX.append((X[i],P[i]))
    else:
      AY.append((Y[i],P[i]))
    
  dx = calc(AX)
  dy = calc(AY)
  for i in range(len(dx)):
    for j in range(len(dy)):
      ans[i+j] = min(ans[i+j],dx[i]+dy[j])
for t in ans:
  print(t)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
XYP = [tuple(map(int,input().split())) for i in range(N)]

xset = set()
yset = set()
ycands = []
for x,y,_ in XYP:
    if x!=0: xset.add(x)
    if y!=0: yset.add(y)

xl = list(xset)
yl = list(yset)

xcost = [[0]*(1<<len(xl)) for _ in range(N)]
ycost = [[0]*(1<<len(yl)) for _ in range(N)]
for i,(x,y,p) in enumerate(XYP):
    for b in range(1<<len(xl)):
        d = abs(x)
        for k in range(len(xl)):
            if b&(1<<k):
                d = min(d, abs(x - xl[k]))
        xcost[i][b] = d*p
    for b in range(1<<len(yl)):
        d = abs(y)
        for k in range(len(yl)):
            if b&(1<<k):
                d = min(d, abs(y - yl[k]))
        ycost[i][b] = d*p

xk = [[] for _ in range(N+1)]
yk = [[] for _ in range(N+1)]
for b in range(1<<len(xl)):
    c = bin(b).count('1')
    if c > N: continue
    xk[c].append(b)
for b in range(1<<len(yl)):
    c = bin(b).count('1')
    if c > N: continue
    yk[c].append(b)

for k in range(N+1):
    if k >= len(xl) or k >= len(yl):
        print(0)
        continue
    ans = 10**20
    for xc in range(k+1):
        yc = k-xc
        for xb in xk[xc]:
            for yb in yk[yc]:
                cost = 0
                for i in range(N):
                    cost += min(xcost[i][xb], ycost[i][yb])
                ans = min(ans, cost)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
XYP = [tuple(map(int,input().split())) for i in range(N)]

xset = set()
yset = set()
ycands = []
for x,y,_ in XYP:
    if x!=0: xset.add(x)
    if y!=0: yset.add(y)

xl = sorted(list(xset))
yl = sorted(list(yset))

xcost = [[0]*(1<<len(xl)) for _ in range(N)]
ycost = [[0]*(1<<len(yl)) for _ in range(N)]
for i,(x,y,p) in enumerate(XYP):
    for b in range(1<<len(xl)):
        d = abs(x)
        for k in range(len(xl)):
            if b&(1<<k):
                d = min(d, abs(x - xl[k]))
        xcost[i][b] = d*p
    for b in range(1<<len(yl)):
        d = abs(y)
        for k in range(len(yl)):
            if b&(1<<k):
                d = min(d, abs(y - yl[k]))
        ycost[i][b] = d*p

xk = [[] for _ in range(N+1)]
yk = [[] for _ in range(N+1)]
for b in range(1<<len(xl)):
    c = bin(b).count('1')
    if c > N: continue
    xk[c].append(b)
for b in range(1<<len(yl)):
    c = bin(b).count('1')
    if c > N: continue
    yk[c].append(b)

for k in range(N+1):
    if k >= len(xl) or k >= len(yl):
        print(0)
        continue
    ans = 10**20
    for xc in range(k+1):
        yc = k-xc
        for xb in xk[xc]:
            for yb in yk[yc]:
                cost = 0
                for i in range(N):
                    cost += min(xcost[i][xb], ycost[i][yb])
                ans = min(ans, cost)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = []; Y = []; P = []
INF = float("inf")
for i in range(N):
  x,y,p = list(map(int,input().split()))
  X.append(x);Y.append(y);P.append(p)
ans = [INF for _ in range(N+1)] #0本置いた時からN本置いた時までN+1個
def calc(A):
  n = len(A) #Aにはいくつ入っているか。つまり、xoryで選ばれたものはいくつあるか。
  A.sort()
  res = [INF for _ in range(n+1)] #道が0本からn本
  for s in range(1<<n): #選ばれたものを全探索
    p = [0] #最初の大通り
    for i in range(n):
      if (s>>i)&1 == 1: #bitが立っている位置は道があるので追加
        p.append(A[i][0])
    p.sort()
    now = 0 #現在の移動距離
    pi = 0 #i個目の町の位置よりも小さい位置
    for i in range(n): #i個目の町に注目
      #m = INF
      x = A[i][0] #xoryとして選ばれた町のi番目の位置。
      while pi+1 < len(p) and p[pi+1] < x:
        pi += 1
      m = abs(x-p[pi])
      if pi+1 < len(p):
        m = min(m,abs(x-p[pi+1]))
      #for j in range(len(p)): #すべての道に対して愚直に最短距離を求める。
      #  m = min(m,abs(p[j]-A[i][0]))
      now += m*A[i][1] #最短距離×人数
    b = len(p) -1 #道を何本追加したか。1を引くのは最初の大通り。
    res[b] = min(res[b],now)
  return res
    

for s in range(1<<N): #x軸にするかをbitで全探索
  AX = [];AY = [] #Aは選ばれた村を追加していく。2**N回これは更新される。
  for i in range(N):
    if (s>>i)&1 == 1: #x軸で見る
      AX.append((X[i],P[i]))
    else:
      AY.append((Y[i],P[i]))
    
  dx = calc(AX)
  dy = calc(AY)
  for i in range(len(dx)):
    for j in range(len(dy)):
      ans[i+j] = min(ans[i+j],dx[i]+dy[j])
for t in ans:
  print(t)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
XYP = [list(map(int, input().split())) for _ in range(N)]

bits = 1 << N

xmemo = [[float('inf')]*N for _ in range(bits)]
ymemo = [[float('inf')]*N for _ in range(bits)]

for b in range(bits):
  for i in range(N):
    xmemo[b][i] = min(XYP[i][2]*abs(XYP[i][0]), xmemo[b][i])
    ymemo[b][i] = min(XYP[i][2]*abs(XYP[i][1]), ymemo[b][i])
    if not (b & (1<<i)):
      continue
    for j in range(N):
      xmemo[b][j] = min(XYP[j][2]*abs(XYP[i][0]-XYP[j][0]), xmemo[b][j])
      ymemo[b][j] = min(XYP[j][2]*abs(XYP[i][1]-XYP[j][1]), ymemo[b][j])
      
ans = [float('inf')]*(N+1)

pos = 3**N
for t in range(pos):
  l = []
  for _ in range(N):
    l.append(t%3)
    t //= 3
  xi = 0
  yi = 0
  cnt = 0
  for i in range(N):
    if l[i] == 0:
      xi += 1 << i
      cnt += 1
    elif l[i] == 1:
      yi += 1 << i
      cnt += 1
  tmp = 0
  for i in range(N):
    tmp += min(xmemo[xi][i], ymemo[yi][i])
  ans[cnt] = min(ans[cnt], tmp)
  
for i in range(N+1):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import sys

INF = 1 << 62


def solve(N, X, Y, P):

    xsel = [[None] * N for x in range(2**N)]
    ysel = [[None] * N for x in range(2**N)]

    for i in range(2**N):
        for j in range(N):
            xsel[i][j] = abs(X[j])
            ysel[i][j] = abs(Y[j])
            for k in range(N):
                if ((i >> k) & 1):
                    xsel[i][j] = min(xsel[i][j], abs(X[j] - X[k]))
                    ysel[i][j] = min(ysel[i][j], abs(Y[j] - Y[k]))

    ans = [INF] * (N + 1)
    for i in range(1 << N):
        cnt = 0
        for j in range(N):
            if (i >> j) & 1:
                cnt += 1
        for j in range(i, -1, -1):
            j &= i
            cost = 0
            for k in range(N):
                if (not ((i >> k) & 1)):
                    cost += min(xsel[j][k], ysel[i - j][k]) * P[k]

            ans[cnt] = min(ans[cnt], cost)

    return ans


def main():

    # 入力
    N = int(sys.stdin.readline().rstrip())
    X, Y, P = [], [], []
    for i in range(N):
        x, y, p = map(int, sys.stdin.readline().rstrip().split())
        X.append(x)
        Y.append(y)
        P.append(p)

    ans = solve(N, X, Y, P)

    for i in range(N+1):
        print(ans[i])
    return


main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = []; Y = []; P = []
INF = float("inf")
for i in range(N):
  x,y,p = list(map(int,input().split()))
  X.append(x);Y.append(y);P.append(p)
ans = [INF for _ in range(N+1)] #0本置いた時からN本置いた時までN+1個
def calc(A):
  n = len(A) #Aにはいくつ入っているか。つまり、xoryで選ばれたものはいくつあるか。
  res = [INF for _ in range(n+1)] #道が0本からn本
  for s in range(1<<n): #選ばれたものを全探索
    p = [0] #最初の大通り
    for i in range(n):
      if (s>>i)&1 == 1: #bitが立っている位置は道があるので追加
        p.append(A[i][0])
    now = 0 #現在の移動距離
    for i in range(n): #i個目の町に注目
      m = INF
      for j in range(len(p)): #すべての道に対して愚直に最短距離を求める。
        m = min(m,abs(p[j]-A[i][0]))
      now += m*A[i][1] #最短距離×人数
    b = len(p) -1 #道を何本追加したか。1を引くのは最初の大通り。
    res[b] = min(res[b],now)
  return res
    

for s in range(1<<N): #x軸にするかをbitで全探索
  AX = [];AY = [] #Aは選ばれた村を追加していく。2**N回これは更新される。
  for i in range(N):
    if (s>>i)&1 == 1: #x軸で見る
      AX.append((X[i],P[i]))
    else:
      AY.append((Y[i],P[i]))
    
  dx = calc(AX)
  dy = calc(AY)
  for i in range(len(dx)):
    for j in range(len(dy)):
      ans[i+j] = min(ans[i+j],dx[i]+dy[j])
for t in ans:
  print(t)

Submission status: Time Limit Exceeded

Solution code:
#解法１

#入力
N = int(input())
town = [list(map(int,input().split())) for i in range(N)]

#縦と横のリストを作る
vert = [town[i][0] for i in range(N)]
hori = [town[i][1] for i in range(N)]

#bit全探索
dX = []
for i in range(2**N):
    vertsel = []
    dXconst = [abs(town[l][0])*town[l][2] for l in range(N)]
    for j in range(N):
        if ((i >> j) & 1):
            vertsel.append(town[j][0])
    for k in vertsel:
        dXconst = [min(dXconst[l],abs(town[l][0]-k)*town[l][2]) for l in range(N)]
    dX.append(dXconst)

dY = []
for i in range(2**N):
    horisel = []
    dYconst = [abs(town[l][1])*town[l][2] for l in range(N)]
    for j in range(N):
        if ((i >> j) & 1):
            horisel.append(town[j][1])
    for k in horisel:
        dYconst = [min(dYconst[l],abs(town[l][1]-k)*town[l][2]) for l in range(N)]
    dY.append(dYconst)

#print('len(dX) ==',len(dX))
#print('len(dY) ==',len(dY))
#print(dX)
#print(dY)

#歩行距離を3進数を使って求める
ans = [float('inf') for K in range(N+1)]
for i in range(2**N):
    #print(i)
    K = 0
    #print('i ==',i)
    for j in range(N):
        if ((i >> j) & 1):
            K += 1
    for j in reversed(range(i+1)):
        j = (j&i)
        cost = 0
        for k in range(N):
            if not ((i >> k) & 1):
                cost += min(dX[j][k], dY[i-j][k])
        ans[K] = min(cost,ans[K])

#出力
[print(ans[K]) for K in range(N+1)]

Submission status: Time Limit Exceeded

Solution code:
#解法１

#入力
N = int(input())
town = [list(map(int,input().split())) for i in range(N)]

#縦と横のリストを作る
vert = [town[i][0] for i in range(N)]
hori = [town[i][1] for i in range(N)]

#bit全探索
dX = []
for i in range(2**N):
    vertsel = []
    dXconst = [abs(town[l][0])*town[l][2] for l in range(N)]
    for j in range(N):
        if ((i >> j) & 1):
            vertsel.append(town[j][0])
    for k in vertsel:
        dXconst = [min(dXconst[l],abs(town[l][0]-k)*town[l][2]) for l in range(N)]
    dX.append(dXconst)

dY = []
for i in range(2**N):
    horisel = []
    dYconst = [abs(town[l][1])*town[l][2] for l in range(N)]
    for j in range(N):
        if ((i >> j) & 1):
            horisel.append(town[j][1])
    for k in horisel:
        dYconst = [min(dYconst[l],abs(town[l][1]-k)*town[l][2]) for l in range(N)]
    dY.append(dYconst)

#print('len(dX) ==',len(dX))
#print('len(dY) ==',len(dY))
#print(dX)
#print(dY)

#歩行距離を3進数を使って求める
ans = [float('inf') for K in range(N+1)]
for i in range(2**N):
    #print(i)
    K = 0
    #print('i ==',i)
    for j in range(N):
        if ((i >> j) & 1):
            K += 1
    for j in reversed(range(i+1)):
        j = (j&i)
        ans[K] = min(sum([min(dX[j][l],dY[i-j][l]) for l in range(N)]),ans[K])

#出力
[print(ans[K]) for K in range(N+1)]

Submission status: Time Limit Exceeded

Solution code:
#解法１

#入力
N = int(input())
town = [list(map(int,input().split())) for i in range(N)]

#縦と横のリストを作る
vert = [town[i][0] for i in range(N)]
hori = [town[i][1] for i in range(N)]

#bit全探索
dX = []
for i in range(2**N):
    vertsel = []
    dXconst = [abs(town[l][0])*town[l][2] for l in range(N)]
    for j in range(N):
        if ((i >> j) & 1):
            vertsel.append(town[j][0])
    for k in vertsel:
        dXconst = [min(dXconst[l],abs(town[l][0]-k)*town[l][2]) for l in range(N)]
    dX.append(dXconst)

dY = []
for i in range(2**N):
    horisel = []
    dYconst = [abs(town[l][1])*town[l][2] for l in range(N)]
    for j in range(N):
        if ((i >> j) & 1):
            horisel.append(town[j][1])
    for k in horisel:
        dYconst = [min(dYconst[l],abs(town[l][1]-k)*town[l][2]) for l in range(N)]
    dY.append(dYconst)

#print('len(dX) ==',len(dX))
#print('len(dY) ==',len(dY))
#print(dX)
#print(dY)

#歩行距離を3進数を使って求める
ans = [float('inf') for K in range(N+1)]
for i in range(3**N):
    #print(i)
    Xvalue = 0
    Yvalue = 0
    K = 0
    #print('i ==',i)
    for j in range(N):
        p = i%3
        i = i//3
        if p == 1:
            Xvalue += 2**j
            K += 1
        if p == 2:
            Yvalue += 2**j
            K += 1
    
    ans[K] = min(sum([min(dX[Xvalue][l],dY[Yvalue][l]) for l in range(N)]),ans[K])

#出力
[print(ans[K]) for K in range(N+1)]

Submission status: Time Limit Exceeded

Solution code:
#解法１

#入力
N = int(input())
town = [list(map(int,input().split())) for j in range(N)]

#縦と横のリストを作る
X = [town[j][0] for j in range(N)]
Y = [town[j][1] for j in range(N)]

#bit全列挙
xsel = [[abs(X[j]) for j in range(N)] for i in range(2**N)]
ysel = [[abs(Y[j]) for j in range(N)] for i in range(2**N)]
for i in range(2**N):
    for j in range(N):
        for k in range(N):
            if ((i >> k) & 1):
                xsel[i][j] = min(xsel[i][j], abs(X[j] - X[k]))
                ysel[i][j] = min(ysel[i][j], abs(Y[j] - Y[k]))

#歩行距離を求める
ans = [float('inf') for cnt in range(N+1)]
for i in range(2**N):
    cnt = 0
    for j in range(N):
        if ((i >> j) & 1):
            cnt += 1
    for j in reversed(range(i+1)):
        j = (j&i)
        cost = 0
        for k in range(N):
            if not ((i >> k) & 1):
                cost += min(xsel[j][k], ysel[i-j][k])*town[k][2]
        ans[cnt] = min(ans[cnt],cost)

#出力
[print(ans[cnt]) for cnt in range(N+1)]

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys

n = int(input())
inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
xxx = inp[0::3]
yyy = inp[1::3]
ppp = inp[2::3]

ans = [10 ** 18]*(n+1)

default_dist = np.minimum(np.abs(xxx), np.abs(yyy))

# どの点に線を引くか全探索
for bit in range(1 << n):
    k = (bit & 0x5555) + (bit >> 1 & 0x5555)
    k = (k & 0x3333) + (k >> 2 & 0x3333)
    k = (k & 0x0f0f) + (k >> 4 & 0x0f0f)
    k = (k & 0x00ff) + (k >> 8 & 0x00ff)

    i = 0
    cur = 0
    t = bit
    # selected: 選択する点のidを格納
    selected = np.zeros(k, dtype=np.int)
    # is_selected: bit
    is_selected = np.zeros(n, dtype=np.int)
    while t:
        if t & 1:
            selected[cur] = i
            is_selected[i] = 1
            cur += 1
        t >>= 1
        i += 1

    # 引くと決めた座標にタテヨコどちらを引くか全探索
    for bit2 in range(1 << k):
        cost = 0
        for i in range(n):
            if is_selected[i]:
                continue
            town_dist = default_dist[i]
            t = bit2
            for j in range(k):
                if t & 1:
                    town_dist = min(town_dist, abs(yyy[selected[j]] - yyy[i]))
                else:
                    town_dist = min(town_dist, abs(xxx[selected[j]] - xxx[i]))
                t >>= 1
            cost += town_dist * ppp[i]
        ans[k] = min(ans[k], cost)


print('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys

n = int(input())
inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
xxx = inp[0::3]
yyy = inp[1::3]
ppp = inp[2::3]

ans = [10 ** 18]*(n+1)

default_dist = [0] * n
for i in range(n):
    default_dist[i] = min(abs(xxx[i]), abs(yyy[i]))

# どの点に線を引くか全探索
for bit in range(1 << n):
    k = (bit & 0x5555) + (bit >> 1 & 0x5555)
    k = (k & 0x3333) + (k >> 2 & 0x3333)
    k = (k & 0x0f0f) + (k >> 4 & 0x0f0f)
    k = (k & 0x00ff) + (k >> 8 & 0x00ff)

    i = 0
    cur = 0
    t = bit
    # selected: 選択する点のidを格納
    selected = [0] * k
    # is_selected: bit
    is_selected = [0] * n
    while t:
        if t & 1:
            selected[cur] = i
            is_selected[i] = 1
            cur += 1
        t >>= 1
        i += 1

    # 引くと決めた座標にタテヨコどちらを引くか全探索
    for bit2 in range(1 << k):
        cost = 0
        for i in range(n):
            if is_selected[i]:
                continue
            town_dist = default_dist[i]
            t = bit2
            for j in range(k):
                if t & 1:
                    town_dist = min(town_dist, abs(yyy[selected[j]] - yyy[i]))
                else:
                    town_dist = min(town_dist, abs(xxx[selected[j]] - xxx[i]))
                t >>= 1
            cost += town_dist * ppp[i]
        ans[k] = min(ans[k], cost)


print('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

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

ans = [10 ** 18]*(n+1)

default_dist = [0] * n
for i in range(n):
    default_dist[i] = min(abs(xxx[i]), abs(yyy[i]))

# どの点に線を引くか全探索
for bit in range(1 << n):
    k = (bit & 0x5555) + (bit >> 1 & 0x5555)
    k = (k & 0x3333) + (k >> 2 & 0x3333)
    k = (k & 0x0f0f) + (k >> 4 & 0x0f0f)
    k = (k & 0x00ff) + (k >> 8 & 0x00ff)

    i = 0
    cur = 0
    t = bit
    # selected: 選択する点のidを格納
    selected = [0] * k
    # is_selected: bit
    is_selected = [0] * n
    while t:
        if t & 1:
            selected[cur] = i
            is_selected[i] = 1
            cur += 1
        t >>= 1
        i += 1

    # 引くと決めた座標にタテヨコどちらを引くか全探索
    for bit2 in range(1 << k):
        cost = 0
        for i in range(n):
            if is_selected[i]:
                continue
            town_dist = default_dist[i]
            t = bit2
            for j in range(k):
                if t & 1:
                    town_dist = min(town_dist, abs(yyy[selected[j]] - yyy[i]))
                else:
                    town_dist = min(town_dist, abs(xxx[selected[j]] - xxx[i]))
                t >>= 1
            cost += town_dist * ppp[i]
        ans[k] = min(ans[k], cost)


print('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
import os
import sys

import numpy as np


n = int(input())
xxx, yyy, ppp = [],[],[]
for i in range(n):
    x, y, p = map(int, input().split())
    xxx.append(x)
    yyy.append(y)
    ppp.append(p)

ans = [10 ** 18]*(n+1)

default_dist = [0] * n
for i in range(n):
    default_dist[i] = min(abs(xxx[i]), abs(yyy[i]))

# どの点に線を引くか全探索
for bit in range(1 << n):
    k = (bit & 0x5555) + (bit >> 1 & 0x5555)
    k = (k & 0x3333) + (k >> 2 & 0x3333)
    k = (k & 0x0f0f) + (k >> 4 & 0x0f0f)
    k = (k & 0x00ff) + (k >> 8 & 0x00ff)

    i = 0
    cur = 0
    t = bit
    # selected: 選択する点のidを格納
    selected = [0] * k
    # is_selected: bit
    is_selected = [0] * n
    while t:
        if t & 1:
            selected[cur] = i
            is_selected[i] = 1
            cur += 1
        t >>= 1
        i += 1

    # 引くと決めた座標にタテヨコどちらを引くか全探索
    for bit2 in range(1 << k):
        cost = 0
        for i in range(n):
            if is_selected[i]:
                continue
            town_dist = default_dist[i]
            t = bit2
            for j in range(k):
                if t & 1:
                    town_dist = min(town_dist, abs(yyy[selected[j]] - yyy[i]))
                else:
                    town_dist = min(town_dist, abs(xxx[selected[j]] - xxx[i]))
                t >>= 1
            cost += town_dist * ppp[i]
        ans[k] = min(ans[k], cost)


print('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools, bisect
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def S(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]

alphabets = "abcdefghijklmnopqrstuvwxyz"

sys.setrecursionlimit(1000000)
dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
MOD = 1000000007
INF = float('inf')

def main():
    N = I()
    XYP = LIR(N)

    anss = [INF] * (N+1)

    preX, preY = [None for _ in range(1 << N)], [None for _ in range(1 << N)]
    for pattern in itertools.product([0, 1], repeat=N):
        X, Y = [0], [0]
        keyX, keyY = 0, 0
        tmpX, tmpY = [], []
        for i, bit in enumerate(pattern):
            keyX |= bit << i
            keyY |= bit << i
            if bit:
                X.append(XYP[i][0])
                Y.append(XYP[i][1])
        for x, y, p in XYP:
            min_distX = abs(y)
            min_distY = abs(x)
            for rx in X:
                if min_distX > abs(x - rx):
                    min_distX = abs(x - rx)
            for ry in Y:
                if min_distY > abs(y - ry):
                    min_distY = abs(y - ry)
            tmpX.append(min_distX * p)
            tmpY.append(min_distY * p)
        preX[keyX] = tmpX
        preY[keyY] = tmpY

    for pattern in itertools.product([0, 1, 2], repeat=N):
        keyX, keyY = 0, 0
        root = 0
        for i, which in enumerate(pattern):
            if which == 1:
                keyX |= which << i
                root += 1
            elif which == 2:
                keyY |= int(bool(which)) << i
                root += 1

        tmp = 0
        for vx, vy in zip(preX[keyX], preY[keyY]):
            tmp += min(vx, vy)

        if anss[root] > tmp:
            anss[root] = tmp

    for ans in anss:
        print(ans)

if __name__ == '__main__':
    main()