Problem:


				Max Score: 350 Points 

Problem Statement

					There are N buildings along the line. The i-th building from the left is colored in color i, and its height is currently a_i meters. 

					Chokudai is a mayor of the city, and he loves colorful thigs. And now he wants to see at least K buildings from the left. 

					You can increase height of buildings, but it costs 1 yens to increase 1 meters. It means you cannot make building that height is not integer. 

					You cannot decrease height of buildings. 

					Calculate the minimum cost of satisfying Chokudai's objective. 

					Note: "Building i can see from the left" means there are no j exists that (height of building j) ≥ (height of building i) and j < i. 

Input Format

N K
a_1 a_2 a_3 ... a_N

Output Format

						Print the minimum cost in one line. In the end put a line break.

Constraints

1 ≤ K ≤ N ≤ 15

1 ≤ a_i ≤ 10^9

Scoring

						Subtask 1 [120 points] 

N = K

						Subtask 2 [90 points] 

N ≤ 5

a_i ≤ 7

						Subtask 3 [140 points] 

There are no additional constraints.

Sample Input 1

5 5
3949 3774 3598 3469 3424

Sample Output 1

1541

					The optimal solution is (height of buildings from the left) = [3949, 3950, 3951, 3952, 3953].

Sample Input 2

5 3
7 4 2 6 4

Sample Output 2

7

					The optimal solution is (height of buildings from the left) = [7, 8, 2, 9, 4].



Sample input:
5 5
3949 3774 3598 3469 3424


Sample output:
1541

Submission status: Accepted

Solution code:
import copy

N, K = map(int, input().split())
a = list(map(int, input().split()))

ans = []
for i in range(2**N):
    s = a.copy()
    cnt = 0
    tmp = 1
    henkou = [False for _ in range(N)]
    for j in range(N):
        if((i >> j)&1):
            henkou[j] = True
    bill = s[0]
    for k in range(1, N):
        if(henkou[k]):
            if(bill >= s[k]):
                cnt += bill-s[k]+1
                s[k] = bill+1
                bill = s[k]
                tmp += 1
            else:
                bill = s[k]
                tmp += 1
        else:
            if(bill < s[k]):
                bill = s[k]
                tmp += 1
    if(tmp >= K):
        ans.append(cnt)
print(min(ans), end='\n')

Submission status: Accepted

Solution code:
n, k = map(int,input().split())
a = list(map(int, input().split()))
# print(a)
ans = 10**15
for i in range(2**n):
    
    maxheight = a[0]
    money = 0
    see = 1
    for j in range(1,n):
        if see >= k:
            break 
        if a[j]>maxheight:
            see += 1
            maxheight = a[j]
        elif a[j]<=maxheight and (i>>j)&1 ==1:
            # print(i,j)
            money += maxheight-a[j]+1
            
            maxheight += 1
            see +=1
    # print(bin(i), money, maxheight,see)
    if see >= k and money <= ans:
        ans = money
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
ans = float('inf')

for i in range(2**n):
    height = a[0]
    count = 1
    cost = 0
    for j in range(1,n):
        if (i>>j)&1:
            cost += max(0,(height-a[j]+1))
            height = max(height+1, a[j])
            count +=1
        else:
            if a[j] > height:
                count +=1
                height = a[j]
    if count >= k:
        ans = min(ans, cost)
print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np

sys.setrecursionlimit(10**7)

N, K = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]

LEN = 1 << N
H = np.zeros(LEN,dtype = np.int64)
cost = np.zeros(LEN,dtype = np.int64)
# print(N,K)
# print(A)
for i,a in enumerate(A):
    bit = 1 << i
    H[bit:2*bit] = np.maximum(H[:bit]+1,a)
    H[:bit] = np.maximum(H[:bit],a)
    cost[bit:2*bit] = (H[bit:2*bit] - a) + cost[:bit]

pop_count = np.zeros(LEN,dtype=np.int32)
for i in range(LEN):
    pop_count[i] = bin(i).count('1')


print(cost[pop_count >= K].min())

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

import numpy as np

N,K = map(int,input().split())
A = [int(x) for x in input().split()]

L = 1 << N
right = np.zeros(L,dtype=np.int64)
total = np.zeros(L,dtype=np.int64)

for i, v in enumerate(A):
    bit = 1 << i
    # print(bit)
    right[bit:2*bit] = np.maximum(right[:bit]+1,v)
    np.maximum(right[:bit], v, out=right[:bit])
    total[bit:2*bit] = (right[bit:2*bit] - v) + total[:bit]
    # print(right)
    # print(total)

# print(total)

popcount = np.zeros(L,dtype=np.int32)
rng = np.arange(L)

for _ in range(15):
    popcount += rng&1
    rng >>= 1

# print(popcount)

answer = total[popcount >= K].min()
print(answer)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

# 1 <= K <= N <= 15
# 1 <= a_i <= 10 ** 9

N, K = map(int, input().split())
heights = list(map(int, input().split()))
# print(N, K, heights)


def calc(i, heights):
    cost = 0
    for shift in range(1, N):
        if i & (1 << shift):
            max_h = max(heights[:shift])
            if max_h >= heights[shift]:
                cost += (max_h + 1) - heights[shift]
                heights[shift] = max_h + 1
    return cost


str_bin = ""
for _ in range(K):
    str_bin += "1"
min_i = int(str_bin, 2)
min_cost = float("inf")


def is_valid(i, K):
    count = 0
    for bit in range(N):
        if i & (1 << bit):
            count += 1
    if count == K:
        return True
    return False


for i in range(min_i, 2 ** N):
    if is_valid(i, K):
        heights_copy = heights[:]
        # print(f"i = {i} ({bin(i)})")
        cost = calc(i, heights_copy)
        # print(f"cost = {cost}")
        min_cost = min(min_cost, cost)

print(min_cost)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
a = list(map(int, input(). split()))

res = 1 << 60
for i in range(1<<n):
    if(i%2 == 0): continue
    
    use_idx = [0 for _ in range(n)]
    use_cnt = 0
    for j in range(n):
        if(i & (1<<j)):
            use_idx[j] = 1
            use_cnt += 1
    
    if(use_cnt != k): continue
    
    sm = 0
    mx = a[0]
    for j in range(1, n):
        
        if(use_idx[j]):
            if(a[j] <= mx):
                sm += mx+1 - a[j]
                mx += 1
        
        mx = max(mx, a[j])
    
    res = min(res, sm)

print(res)

Submission status: Accepted

Solution code:
import sys
import copy

readline = sys.stdin.readline

def main():
    N, K = map(int, readline().split())
    a = list(map(int, readline().split()))

    h = [max(a[:i]) for i in range(1, N+1)]
    #print(h)

    mincost = float('inf')
    for i in range(2**N):
        cost = 0
        htmp = copy.copy(h)
        tmp = []
        tmpappend = tmp.append
        for j in range(N):
            if (i>>j) & 1:
                tmpappend(j)
        if len(tmp) != K:
            continue
        #print(tmp)
        for k in tmp:
            if k >= 1 and htmp[k] <= htmp[k-1]:
                maxh = max(htmp[:k])
                cost += maxh - a[k] + 1
                htmp[k] = maxh + 1
        #print("h:{}, cost:{}".format(htmp, cost))
        mincost = min(mincost, cost)

    print(mincost)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys
import random

input = sys.stdin.readline
_NUMINT_ALL = list(range(10))
_START_TIME = time.time()


def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is not None:
        print(ans)


def solve():
    N, K = iip()
    A = iip()


    ans = 10**30
    for i in range(2**N):
        cn = 0
        mh = 0
        cost = 0
        m = 1
        for j in range(N):
            if (i % (m*2)) // m == 1:
                #print(1)
                cn += 1
                mh = max(mh+1, A[j])
                cost += mh-A[j]
            else:
                mh = max(mh, A[j])
            m *= 2
        if cn >= K:
            ans = min(cost, ans)

    print(ans)


#####################################################ライブラリ集ここから

def kiriage_warizan(a, b):
    return -(-a//b)


def iip(listed=True):  # 数字のinputをlistで受け取る
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1 and listed is False:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iipt(l, listed=True, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m

def time_debug_10percent():
    a = random.randint(0, 9)
    if a == 9:
        sys.exit()

def time_debug(t):
    time.sleep(_START_TIME + t - time.time())
    sys.exit()


def make_graph_edge_flat(N):  # グラフ作成のための辺をリストで返す
    ret = []
    for i in range(N-1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


def nibutan_func(func, target, left, right, side="left"): # 関数を二分探索
    l = left
    r = right
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if func(x) == target:
            return x
        elif func(x) > target:
            r = x
        else:
            l = x

    if side == "left" or func(x) == target:
        return l
    else:
        return r


def nibutan_list(list_, target, side="left"):  # リストを二分探索
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r


class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                #for i in path: # 経路圧縮
                #    self.parent[i] = cur
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys
import random

input = sys.stdin.readline
_NUMINT_ALL = list(range(10))
_START_TIME = time.time()


def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is not None:
        print(ans)


def solve():
    N, K = iip()
    A = iip()


    ans = 10**30
    for i in range(2**N):
        cn = 0
        mh = 0
        cost = 0
        for j in range(N):
            if (i % 2**(j+1)) // 2**j == 1:
                #print(1)
                cn += 1
                mh = max(mh+1, A[j])
                cost += mh-A[j]
            else:
                mh = max(mh, A[j])
        if cn >= K:
            ans = min(cost, ans)

    print(ans)


#####################################################ライブラリ集ここから

def kiriage_warizan(a, b):
    return -(-a//b)


def iip(listed=True):  # 数字のinputをlistで受け取る
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1 and listed is False:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iipt(l, listed=True, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m

def time_debug_10percent():
    a = random.randint(0, 9)
    if a == 9:
        sys.exit()

def time_debug(t):
    time.sleep(_START_TIME + t - time.time())
    sys.exit()


def make_graph_edge_flat(N):  # グラフ作成のための辺をリストで返す
    ret = []
    for i in range(N-1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


def nibutan_func(func, target, left, right, side="left"): # 関数を二分探索
    l = left
    r = right
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if func(x) == target:
            return x
        elif func(x) > target:
            r = x
        else:
            l = x

    if side == "left" or func(x) == target:
        return l
    else:
        return r


def nibutan_list(list_, target, side="left"):  # リストを二分探索
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r


class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                #for i in path: # 経路圧縮
                #    self.parent[i] = cur
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import product

def main():
    n, k = [int(i) for i in input().split()]
    a = [int(i) for i in input().split()]
    res = 10e10
    for t in product([0,1], repeat=n):
        if sum(t) < k:
            continue
        a_tmp = list(a)
        score = 0
        t_height = 0
        cnt = 0
        for i, h in enumerate(a_tmp):
            if t_height < h:
                t_height = h
                cnt += 1
            elif t[i]:
                t_height += 1
                score += t_height - h
            if cnt >= k:
                break
        res = min(res, score)
    print(res)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))
result = 1000000001*15
def j_cost(cost):
    c = 1
    for i in range(1,len(A)):
        if(max(cost[:i]) < cost[i]):
            c += 1
    #print(c,cost)
    if c >= k:
        return True
    else:
        return False

for i in range(2**n):
    cost = [0]*len(A)
    for j in range(1,n):
        if((i>>j)&1):
            total = [x + y for (x,y) in zip(A[:j],cost[:j])]
            if(max(total)>=A[j]):
                cost[j] = max(total)+1-A[j]
            else:
                cost[j] = 0
    #print(cost,[x + y for (x,y) in zip(A,cost)])
    if(sum(cost) < result and j_cost([x + y for (x,y) in zip(A,cost)])):
        result = sum(cost)
print(result)

Submission status: Accepted

Solution code:
# square869120Contest #4
# B - Buildings are Colorful!
# https://atcoder.jp/contests/s8pc-4/tasks/s8pc_4_b
N, K = map(int, input().split())
*A, = map(int, input().split())

ans = float('inf')
for bit in range(2**N):
    cnt = 0
    for i in range(N):
        if bit >> i & 1:
            cnt += 1
    if cnt < K:
        continue

    cost = 0
    maxh = 0
    for i, a in enumerate(A):
        if bit >> i & 1 and maxh >= a:
            cost += maxh - a + 1
            maxh += 1
        elif maxh < a:
            maxh = a


    if cost < ans:
        ans = cost


print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
aa = list(map(int, input().split()))

inf = 10 ** 9 * 15
ans = inf
for bits in range(2 ** n):
    selected = set()
    for shift in range(n):
        if bits & (1 << shift) > 0:
            selected.add(shift)

    if len(selected) < k:
        continue
    highest = aa[0]
    cost = 0

    for i in range(1, n):
        if highest < aa[i]:
            highest = aa[i]
        else:
            if i in selected:
                highest += 1
                cost += highest - aa[i]
    ans = min(ans, cost)
print(ans)

Submission status: Accepted

Solution code:
N,K=list(map(int,input().split()))
a=list(map(int,input().split()))

ans=10**12

for i in range(2**N):
    cnt=0
    cost=0
    h=0
    for j in range(N):
        if (i>>j)&1==1:
            cnt+=1
            if h>=a[j]:
                cost+=h+1-a[j]
                h+=1
            else:
                h=max(h,a[j])
        else:
            h=max(h,a[j])

    if cnt>=K:
        ans=min(ans,cost)

print(ans)

Submission status: Accepted

Solution code:
from itertools import combinations as comb

N, K = map(int, input().split())
a = list(map(int, input().split()))
ans = 10**17

for i in comb([n for n in range(1, N)], K-1):
    tmpa = a[:]
    tmp = 0
    for j in range(K-1):
        pre = max(tmpa[:i[j]])
        if tmpa[i[j]] <= pre:
            tmp += pre+1-tmpa[i[j]]
            tmpa[i[j]] = pre+1
    
    if tmp < ans:
        ans = tmp

print(ans)

Submission status: Accepted

Solution code:
import math
import copy
import sys
import fractions
# import numpy as np
# import statistics
import decimal
import heapq
import collections
import itertools


# from operator import mul

# sys.setrecursionlimit(100001)


# input = sys.stdin.readline
# sys.setrecursionlimit(10**6)

# ===FUNCTION===

def getInputIntList():
    outputDataList = []
    inputData = input().split()
    outputDataList = [int(n) for n in inputData]

    return outputDataList

def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList


def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList


# ===CODE===

n, k = map(int, input().split())
data = getInputIntList()

items = [n for n in range(1,n)]
comb = []
for v in itertools.combinations(items,k-1):
    comb.append(v)

ans = sys.maxsize
for com in comb:
    tmpans = 0
    highest = data[0]
    for i in range(1, n):
        if i in com:
            if highest < data[i]:
                highest = data[i]
                continue
            else:
                highest += 1
                tmpans += highest - data[i]
        else:
            if highest < data[i]:
                highest = data[i]
                continue
  

    ans = min(ans, tmpans)

if k == 1:
    print(0)
else:
    print(ans)

Submission status: Accepted

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


def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))

# mod=10**9+7
# rstrip().decode('utf-8')

#import numpy as np
from itertools import combinations

def main():
	n,k=MI()
	ans=10**18

	A=LI()
	A=[A[0]-1]+A

	for t in combinations(range(n),k):
		B=A.copy()
		tmp=0
		for i in t:
			i+=1
			B[i]=max(max(B[:i])+1,A[i])
			tmp+=B[i]-A[i]
		ans=min(ans,tmp)
	print(ans)

if __name__ == "__main__":
	main()

Submission status: Accepted

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


def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))

# mod=10**9+7
# rstrip().decode('utf-8')

import numpy as np
from itertools import combinations

def main():
	n,k=MI()
	ans=10**18

	A=LI()
	A=[A[0]-1]+A
	A=np.array(A)

	for t in combinations(range(n),k):
		B=A.copy()
		tmp=0
		for i in t:
			i+=1
			B[i]=max(B[:i].max()+1,A[i])
			tmp+=B[i]-A[i]
		ans=min(ans,tmp)
	print(ans)

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:


class BitSeacher:
    def __init__(self,bitcount):
        self.counter =0
        self.bitcount = bitcount
        self.mx = 2**bitcount-1
    
    def __next__(self):
        if self.counter > self.mx:
            raise StopIteration()
        ans =[]
        flg =1
        for i in range(self.bitcount):
            if flg & self.counter != 0:
                ans.append(i)
            flg = flg.__lshift__(1)
        self.counter+=1
        return ans

    def __iter__(self):
        return self

def checker(A,group,K):
    if len(group) < K:
        return 10**20

    tbl = [False for i in A]
    for i in group:
        tbl[i]=True
    mx = 0
    count = 0
    for i in range(len(A)):
        if not tbl[i]:
            mx = max(mx,A[i])
            continue
        
        if mx < A[i]:
            mx = A[i]
        else:
            count += mx - A[i] +1
            mx +=1
    return count






def resolve():
    N,K = map(int,input().split())
    A= list(map(int,input().split()))
    mn = 10**20
    for group in BitSeacher(N):
        group.sort()
        mn = min(mn,checker(A,group,K))

    print(mn)



if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))

min_cost = 1 << 50
for mask in range(1<<N):
    if bin(mask).count('1') < K:
        continue

    cost = 0
    prev_height = 0
    for i in range(N):
        # not chose this building
        if mask & (1<<i) == 0:
            prev_height = max(prev_height, A[i])
            continue

        # chose this building viewable
        if A[i] <= prev_height:
            cost += prev_height - A[i] + 1
            prev_height += 1
        else:
            prev_height = A[i]
    min_cost = min(min_cost, cost)

print(min_cost)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
A = list(map(int, input().split()))

ans = 10 ** 11
for b in range(1 << n):
    if bin(b).count("1") != k:
        continue

    max_ai = 0
    cost = 0
    for i in range(n):
        if (b & 1 << i):
            if A[i] > max_ai:
                max_ai = A[i]
            else:
                cost += (max_ai + 1) - A[i]
                max_ai += 1
        else:
            max_ai = max(max_ai, A[i])

    ans = min(ans, cost)

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
from itertools import combinations
N,K = [int(x) for x in stdin.readline().rstrip().split()]
A = [int(x) for x in stdin.readline().rstrip().split()]
ans = 10**18
for i in combinations(range(1,N),K-1):
    tallest = A[0]
    tmp = 0
    for j in range(1,N):
        if j in i:
            if tallest >= A[j]:
                tmp += (tallest - A[j] + 1)
                tallest = (tallest + 1)
            else:
                tallest = max(tallest,A[j])
        else:
            tallest = max(tallest,A[j])
    ans = min(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
#n = int(input())
#n,k = map(int,input().split())
#x = list(map(int,input().split()))


def main():
    N,K = map(int,input().split())
    A = list(map(int,input().split()))

    ans = 10**30
    for i in range(1<<N):
        hght = A[0]
        cst = 0
        cnt = 1
        for j in range(1,N):
            if (i>>j)&1:
                cnt += 1
                if A[j]<=hght: 
                    cst += hght-A[j]+1
                    hght += 1
                else:
                    hght = A[j]
            hght = max(hght,A[j])
        if cnt >= K:
            ans = min(ans,cst)
    
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/s8pc-4/tasks/s8pc_4_b

if __name__ == "__main__":
    N, K = map(int, input().split())
    A = list(map(int, input().split()))

    result = float('inf')
    for bit in range(1 << N):
        use = []
        for i in range(N):
            if bit & (1 << i):
                use.append(i)
        if len(use) != K:
            continue

        cost = 0
        eye_height = A[0]

        for i in range(1, N):
            a = A[i]
            if a > eye_height:
                eye_height = a
                continue
            elif i in use:
                eye_height = eye_height + 1
                cost += eye_height - a

        # print(bin(bit))
        # print(use)
        # print('cost {}'.format(cost))

        result = min(result, cost)

    print(result)