← Home
package main

import (
	"bufio"
	"fmt"
	"os"
)

const INF int = 1000000000000000000

type Edge struct {
	to, rev, cap, flow, cost int
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var n, k int
	if _, err := fmt.Fscan(in, &n, &k); err != nil {
		return
	}

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a[i])
	}

	c := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &c[i])
	}

	var baseCost int
	last := make([]int, n+1)
	supply := make([]int, n+1)

	graph := make([][]Edge, n+1)

	addEdge := func(u, v, cap, cost int) {
		graph[u] = append(graph[u], Edge{v, len(graph[v]), cap, 0, cost})
		graph[v] = append(graph[v], Edge{u, len(graph[u]) - 1, 0, 0, -cost})
	}

	for i := 1; i <= n; i++ {
		b := a[i-1]
		baseCost += c[b-1]
		prev := last[b]
		if prev != 0 {
			if prev+1 == i {
				baseCost -= c[b-1]
			} else {
				baseCost -= c[b-1]
				supply[prev] += 1
				supply[i-1] -= 1
				addEdge(prev, i-1, 1, c[b-1])
			}
		}
		last[b] = i
	}

	S := 0
	T := n

	for x := 1; x <= n-1; x++ {
		if supply[x] > 0 {
			addEdge(S, x, supply[x], 0)
		} else if supply[x] < 0 {
			addEdge(x, T, -supply[x], 0)
		}
	}

	for x := 1; x <= n-2; x++ {
		if k-1 > 0 {
			addEdge(x, x+1, k-1, 0)
		}
	}

	minCost := 0
	numNodes := n + 1

	for {
		dist := make([]int, numNodes)
		for i := range dist {
			dist[i] = INF
		}
		parentEdge := make([]int, numNodes)
		parentNode := make([]int, numNodes)
		inQueue := make([]bool, numNodes)

		dist[S] = 0
		queue := []int{S}
		inQueue[S] = true

		for len(queue) > 0 {
			u := queue[0]
			queue = queue[1:]
			inQueue[u] = false

			for i, e := range graph[u] {
				if e.cap > e.flow && dist[e.to] > dist[u]+e.cost {
					dist[e.to] = dist[u] + e.cost
					parentNode[e.to] = u
					parentEdge[e.to] = i
					if !inQueue[e.to] {
						queue = append(queue, e.to)
						inQueue[e.to] = true
					}
				}
			}
		}

		if dist[T] == INF {
			break
		}

		push := INF
		curr := T
		for curr != S {
			p := parentNode[curr]
			idx := parentEdge[curr]
			avail := graph[p][idx].cap - graph[p][idx].flow
			if avail < push {
				push = avail
			}
			curr = p
		}

		curr = T
		for curr != S {
			p := parentNode[curr]
			idx := parentEdge[curr]
			revIdx := graph[p][idx].rev

			graph[p][idx].flow += push
			graph[curr][revIdx].flow -= push
			minCost += push * graph[p][idx].cost

			curr = p
		}
	}

	fmt.Println(baseCost + minCost)
}