Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are n people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and n-th people to refer the last one in the queue.There will be k gondolas, and the way we allocate gondolas looks like this:  When the first gondolas come, the q1 people in head of the queue go into the gondolas.  Then when the second gondolas come, the q2 people in head of the remain queue go into the gondolas.    ... The remain qk people go into the last (k-th) gondolas. Note that q1, q2, ..., qk must be positive. You can get from the statement that  and qi > 0.You know, people don't want to stay with strangers in the gondolas, so your task is to find an optimal allocation way (that is find an optimal sequence q) to make people happy. For every pair of people i and j, there exists a value uij denotes a level of unfamiliar. You can assume uij = uji for all i, j (1 ≤ i, j ≤ n) and uii = 0 for all i (1 ≤ i ≤ n). Then an unfamiliar value of a gondolas is the sum of the levels of unfamiliar between any pair of people that is into the gondolas.A total unfamiliar value is the sum of unfamiliar values for all gondolas. Help Fox Ciel to find the minimal possible total unfamiliar value for some optimal allocation.

The first line contains two integers n and k (1 ≤ n ≤ 4000 and 1 ≤ k ≤ min(n, 800)) — the number of people in the queue and the number of gondolas. Each of the following n lines contains n integers — matrix u, (0 ≤ uij ≤ 9, uij = uji and uii = 0). Please, use fast input methods (for example, please use BufferedReader instead of Scanner for Java).

Print an integer — the minimal possible total unfamiliar value.

NoteIn the first example, we can allocate people like this: {1, 2} goes into a gondolas, {3, 4, 5} goes into another gondolas.In the second example, an optimal solution is : {1, 2, 3} | {4, 5, 6} | {7, 8}.

package main

import (
	"os"
	"strconv"
)

// M ...
const M = 4010

var (
	n, m int
	a, w [M][M]int
	f, g [M][M]int
)

func readnumbers() (nums []int) {
	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num, neg := 0, 1
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]-'0')
		} else if p[i] == '-' {
			neg = -1
		} else if p[i] != '\r' {
			nums = append(nums, neg*num)
			num, neg = 0, 1
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, neg*num)
	}

	return
}

func main() {
	nums := readnumbers()
	idx := 0

	n, m = nums[idx], nums[idx+1]
	idx += 2
	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			a[i][j] = nums[idx]
			idx++
			a[i][j] += a[i-1][j] + a[i][j-1] - a[i-1][j-1]
		}
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			w[i][j] = a[j][j] - a[i-1][j] - a[j][i-1] + a[i-1][i-1]
		}
	}

	for j := 1; j <= n; j++ {
		f[1][j] = w[1][j]
		g[1][j] = 1
	}

	for i := 2; i <= m; i++ {
		g[i][n+1] = n
		for j := n; j >= i; j-- {
			f[i][j] = int(1e9)
			for k := g[i-1][j]; k <= g[i][j+1] && k <= j; k++ {
				if f[i-1][k-1]+w[k][j] < f[i][j] {
					f[i][j] = f[i-1][k-1] + w[k][j]
					g[i][j] = k
				}
			}
		}
	}

	os.Stdout.Write([]byte(strconv.Itoa(f[m][n] / 2)))
}

package main

import (
	"os"
	"strconv"
)

// M ...
const M = 4010

var (
	a, w [M][M]int
	f, g [M][M]int
)

func readnumbers() (nums []int) {
	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num := 0
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]-'0')
		} else if p[i] != '\r' {
			nums = append(nums, num)
			num = 0
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, num)
	}

	return
}

func main() {
	fileInfo, _ := os.Stdin.Stat()
	p, idx := make([]byte, fileInfo.Size()), 0
	os.Stdin.Read(p)

	n, m := 0, 0
	for ; p[idx] >= '0'; idx++ {
		n *= 10
		n += int(p[idx] - '0')
	}
	idx++
	for ; p[idx] >= '0'; idx++ {
		m *= 10
		m += int(p[idx] - '0')
	}
	idx += 2

	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			a[i][j] = int(p[idx] - '0')
			idx += 2
			a[i][j] += a[i-1][j] + a[i][j-1] - a[i-1][j-1]
		}
		idx++
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			w[i][j] = a[j][j] - a[i-1][j] - a[j][i-1] + a[i-1][i-1]
		}
	}

	for j := 1; j <= n; j++ {
		f[1][j] = w[1][j]
		g[1][j] = 1
	}

	for i := 2; i <= m; i++ {
		g[i][n+1] = n
		for j := n; j >= i; j-- {
			f[i][j] = int(1e9)
			for k := g[i-1][j]; k <= g[i][j+1] && k <= j; k++ {
				if f[i-1][k-1]+w[k][j] < f[i][j] {
					f[i][j] = f[i-1][k-1] + w[k][j]
					g[i][j] = k
				}
			}
		}
	}

	os.Stdout.Write([]byte(strconv.Itoa(f[m][n] / 2)))
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.NextInt(), io.NextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.NextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.Println(dp[k][n])
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
}

func NewFastIO(r io.Reader, w io.Writer) FastIO {
	return FastIO{bufio.NewReader(r), bufio.NewWriter(w)}
}

func (f *FastIO) NextInt() int {
	p := make([]byte, 1)
	f.Read(p)
	for !('0' <= p[0] && p[0] <= '9') {
		f.Read(p)
	}
	n := 0
	for '0' <= p[0] && p[0] <= '9' {
		n = n*10 + int(p[0]) - '0'
		f.Read(p)
	}
	return n
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.nextInt(), io.nextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.nextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.println(dp[k][n])
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReaderSize(r, 16<<10), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.nextInt(), io.nextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.nextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.println(dp[k][n])
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) fastIO {
	return fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.nextInt(), io.nextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.nextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.println(dp[k][n])
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.nextInt(), io.nextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.nextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.println(dp[k][n])
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
	q *byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	f := fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
	f.q = &f.p[0]
	return &f
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= *f.q && *f.q <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= *f.q && *f.q <= '9' {
		n = n*10 + int(*f.q) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for *f.q <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for *f.q > ' ' {
		s = append(s, *f.q)
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

package main

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

// Testing I/O from https://codeforces.com/contest/1380/submission/87050098

const inf = int(1e9)

func main() {
	fin := MakeFastIn()

	n, k := fin.ReadInt(), fin.ReadInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = fin.ReadInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	fmt.Println(dp[k][n])
}

type FastIn struct {
	scanner *bufio.Scanner
}

func MakeFastIn() (obj FastIn) {
	obj = FastIn{}
	obj.scanner = bufio.NewScanner(os.Stdin)
	obj.scanner.Split(bufio.ScanWords)
	return
}

func (fi *FastIn) ReadText() string {
	fi.scanner.Scan()
	return fi.scanner.Text()
}

func (fi *FastIn) ReadInt() int {
	ret, err := strconv.Atoi(fi.ReadText())
	if err != nil {
		panic(err)
	}
	return ret
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.nextInt(), io.nextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.nextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.println(dp[k][n])
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p []byte
}

func newFastIO(r io.Reader, w io.Writer) fastIO {
	return fastIO{bufio.NewReader(r), bufio.NewWriter(w), make([]byte, 1)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p)
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p)
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p)
	}
	return n
}

func (f *fastIO) next() string {
	f.Read(f.p)
	for f.p[0] <= ' ' {
		f.Read(f.p)
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p)
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.NextInt(), io.NextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.NextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.Println(dp[k][n])
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
}

func NewFastIO(r io.Reader, w io.Writer) FastIO {
	return FastIO{bufio.NewReader(r), bufio.NewWriter(w)}
}

func (f *FastIO) NextInt() int {
	p := make([]byte, 1)
	for {
		f.Read(p)
		if '0' <= p[0] && p[0] <= '9' {
			break
		}
	}
	n := 0
	for '0' <= p[0] && p[0] <= '9' {
		n = n*10 + int(p[0]) - '0'
		f.Read(p)
	}
	return n
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.NextInt(), io.NextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.NextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.Println(dp[k][n])
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(' ', x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.NextInt(), io.NextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.NextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.Println(dp[k][n])
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	p []byte
}

func NewFastIO(r io.Reader, w io.Writer) FastIO {
	return FastIO{bufio.NewReader(r), bufio.NewWriter(w), make([]byte, 1)}
}

func (f *FastIO) NextInt() int {
	f.Read(f.p)
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p)
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p)
	}
	return n
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

package main

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

// 321E. Ciel and Gondolas
// Using opt[i - 1][j] <= opt[i][j] <= opt[i][j + 1]
// O(n^2)

const inf = int(1e9)

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	n, k := io.nextInt(), io.nextInt()
	u := make([][]int, n+1)
	u[0] = make([]int, n+1)
	for i := 1; i <= n; i++ {
		u[i] = make([]int, n+1)
		for j := 1; j <= n; j++ {
			u[i][j] = io.nextInt()
			if i > j {
				u[i][j] = 0
			}
			u[i][j] += u[i-1][j] + u[i][j-1] - u[i-1][j-1]
		}
	}

	sum := func(l, r int) int { return u[r][r] - u[r][l-1] - u[l-1][r] + u[l-1][l-1] }

	dp := make([][]int, k+1)
	opt := make([][]int, k+1)
	for i := 0; i <= k; i++ {
		dp[i] = make([]int, n+1)
		opt[i] = make([]int, n+1)
	}

	for j := 1; j <= n; j++ {
		dp[1][j] = sum(1, j)
	}

	for i := 2; i <= k; i++ {
		lim := n - 1
		for j := n; j > 0; j-- {
			dp[i][j] = inf
			for x := opt[i-1][j]; x <= lim && x < j; x++ {
				if dp[i][j] > dp[i-1][x]+sum(x+1, j) {
					dp[i][j] = dp[i-1][x] + sum(x+1, j)
					opt[i][j] = x
				}
			}
			lim = opt[i][j]
		}
	}

	io.println(dp[k][n])
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReaderSize(r, 1<<20), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

package main

import (
	"fmt"
	"os"
	"strconv"
)

// M ...
const M = 4010

var (
	a, w [M][M]int
	f, g [M][M]int
)

func readnumbers() (nums []int) {
	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num := 0
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]-'0')
		} else if p[i] != '\r' {
			nums = append(nums, num)
			num = 0
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, num)
	}

	return
}

func main() {
	fileInfo, _ := os.Stdin.Stat()
	p, idx := make([]byte, fileInfo.Size()), 0
	os.Stdin.Read(p)

	n, m := 0, 0
	for ; p[idx] >= '0'; idx++ {
		n *= 10
		n += int(p[idx] - '0')
	}
	idx++
	for ; p[idx] >= '0'; idx++ {
		m *= 10
		m += int(p[idx] - '0')
	}
	idx += 2

	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			a[i][j] = int(p[idx] - '0')
			fmt.Println(a[i][j])
			idx += 2
			a[i][j] += a[i-1][j] + a[i][j-1] - a[i-1][j-1]
		}
		idx++
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			w[i][j] = a[j][j] - a[i-1][j] - a[j][i-1] + a[i-1][i-1]
		}
	}

	for j := 1; j <= n; j++ {
		f[1][j] = w[1][j]
		g[1][j] = 1
	}

	for i := 2; i <= m; i++ {
		g[i][n+1] = n
		for j := n; j >= i; j-- {
			f[i][j] = int(1e9)
			for k := g[i-1][j]; k <= g[i][j+1] && k <= j; k++ {
				if f[i-1][k-1]+w[k][j] < f[i][j] {
					f[i][j] = f[i-1][k-1] + w[k][j]
					g[i][j] = k
				}
			}
		}
	}

	os.Stdout.Write([]byte(strconv.Itoa(f[m][n] / 2)))
}

package main

import (
	"os"
	"strconv"
)

// M ...
const M = 4010

var (
	n, m int
	a, w [M][M]int
	f, g [M][M]int
)

func readnumbers() (nums []int) {
	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num := 0
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]-'0')
		} else if p[i] != '\r' {
			nums = append(nums, num)
			num = 0
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, num)
	}

	return
}

func main() {
	fileInfo, _ := os.Stdin.Stat()
	p, idx := make([]byte, fileInfo.Size()), 0
	os.Stdin.Read(p)

	n, k := 0, 0
	for ; p[idx] >= '0'; idx++ {
		n *= 10
		n += int(p[idx] - '0')
	}
	for ; p[idx] >= '0'; idx++ {
		k *= 10
		k += int(p[idx] - '0')
	}
	idx += 2

	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			a[i][j] = int(p[idx])
			idx++
			a[i][j] += a[i-1][j] + a[i][j-1] - a[i-1][j-1]
		}
		idx += 2
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			w[i][j] = a[j][j] - a[i-1][j] - a[j][i-1] + a[i-1][i-1]
		}
	}

	for j := 1; j <= n; j++ {
		f[1][j] = w[1][j]
		g[1][j] = 1
	}

	for i := 2; i <= m; i++ {
		g[i][n+1] = n
		for j := n; j >= i; j-- {
			f[i][j] = int(1e9)
			for k := g[i-1][j]; k <= g[i][j+1] && k <= j; k++ {
				if f[i-1][k-1]+w[k][j] < f[i][j] {
					f[i][j] = f[i-1][k-1] + w[k][j]
					g[i][j] = k
				}
			}
		}
	}

	os.Stdout.Write([]byte(strconv.Itoa(f[m][n] / 2)))
}


Ela needs to send a large package from machine $$$1$$$ to machine $$$n$$$ through a network of machines. Currently, with the network condition, she complains that the network is too slow and the package can't arrive in time. Luckily, a Wiring Wizard offered her a helping hand.The network can be represented as an undirected connected graph with $$$n$$$ nodes, each node representing a machine. $$$m$$$ wires are used to connect them. Wire $$$i$$$ is used to connect machines $$$u_i$$$ and $$$v_i$$$, and has a weight $$$w_i$$$. The aforementioned large package, if going through wire $$$i$$$, will move from machine $$$u_i$$$ to machine $$$v_i$$$ (or vice versa) in exactly $$$w_i$$$ microseconds. The Wiring Wizard can use his spell an arbitrary number of times. For each spell, he will choose the wire of index $$$i$$$, connecting machine $$$u_i$$$ and $$$v_i$$$, and rewire it following these steps:  Choose one machine that is connected by this wire. Without loss of generality, let's choose $$$v_i$$$.  Choose a machine that is currently connecting to $$$v_i$$$ (including $$$u_i$$$), call it $$$t_i$$$. Disconnect the wire indexed $$$i$$$ from $$$v_i$$$, then using it to connect $$$u_i$$$ and $$$t_i$$$. The rewiring of wire $$$i$$$ will takes $$$w_i$$$ microseconds, and the weight of the wire will not change after this operation. After a rewiring, a machine might have some wire connect it with itself. Also, the Wiring Wizard has warned Ela that rewiring might cause temporary disconnections between some machines, but Ela just ignores it anyway. Her mission is to send the large package from machine $$$1$$$ to machine $$$n$$$ as fast as possible. Note that the Wizard can use his spell on a wire zero, one, or many times. To make sure the network works seamlessly while transferring the large package, once the package starts transferring from machine $$$1$$$, the Wiring Wizard cannot use his spell to move wires around anymore.Ela wonders, with the help of the Wiring Wizard, what is the least amount of time needed to transfer the large package from machine $$$1$$$ to $$$n$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The description of the test cases follows. The first line contains $$$n$$$ and $$$m$$$ ($$$2 \le n \le 500$$$, $$$n - 1 \le m \le 250 000$$$), the number of nodes and number of wires, respectively. For the next $$$m$$$ lines, $$$i$$$-th line will contains $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$1 \le w_i \le 10^9$$$) - the indices 2 machines that are connected by the $$$i$$$-th edge and the weight of it. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$250 000$$$. The graph in each test case is guaranteed to be connected, no self-loops, but it can contain multiple edges.

For each test case, output one integer denotes the least amount of time needed to transfer the large package from machine $$$1$$$ to $$$n$$$.

NoteHere is the graph in the first test case in the sample input:  Ela can ask the Wiring Wizard to use his spell on wire with the index of $$$7$$$, which is connecting machines $$$2$$$ and $$$3$$$. Then, since the machine $$$8$$$ is connected to machine $$$3$$$, the Wiring Wizard can disconnect wire $$$7$$$ from machine $$$3$$$ and connect it to machine $$$8$$$ in $$$3$$$ microseconds (weight of wire $$$3$$$).After that, the package can be sent from machine $$$1$$$ to machine $$$8$$$ in $$$6$$$ microseconds. Therefore, the answer is $$$3 + 6 = 9$$$ microseconds.Here is the graph in the third test case in the sample input:

package main

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

func min(a, b int) int {
	if a < b { return a }
	return b
}

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m int
		fmt.Fscan(r, &n, &m)

		adj := make([][]int, 504)
		dist := make([][]int, 504)
		for i := range adj {
			adj[i] = make([]int, 504)
			dist[i] = make([]int, 504)
			for j := range adj[i] {
				adj[i][j] = 1e14 + 7
				dist[i][j] = 1e9 + 7
			}
			dist[i][i] = 0
		}

		var u, v, wt int
		for i := 0; i < m; i++ {
			fmt.Fscan(r, &u, &v, &wt)
			adj[u][v] = min(wt, adj[u][v])
			adj[v][u] = min(wt, adj[v][u])
			dist[u][v] = 1
			dist[v][u] = 1
		}

		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				for k := j+1; k <= n; k++ {
					dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k])
					dist[k][j] = dist[j][k]
				}
			}
		}

		cost := int(1e17)
		for i := 1; i <= n; i++ {
			for j := i+1; j <= n; j++ {
				cost = min(cost, (dist[1][i] + dist[j][n] + 1) * adj[i][j])
				cost = min(cost, (dist[1][j] + dist[i][n] + 1) * adj[i][j])

				for k := 1; k <= n; k++ {
					cost = min(cost, (dist[1][k] + dist[n][k] + dist[i][k] + 2) * adj[i][j])
					cost = min(cost, (dist[1][k] + dist[n][k] + dist[j][k] + 2) * adj[i][j])
				}
			}
		}

		fmt.Fprintln(w, cost)

	}

}

package main

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

func min(a, b int) int {
	if a < b { return a }
	return b
}

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m int
		fmt.Fscan(r, &n, &m)

		adj := make([][]int, 504)
		dist := make([][]int, 504)
		for i := range adj {
			adj[i] = make([]int, 504)
			dist[i] = make([]int, 504)
			for j := range adj[i] {
				adj[i][j] = 1e9 + 7
				dist[i][j] = 1e9 + 7
			}
			dist[i][i] = 0
		}

		var u, v, wt int
		for i := 0; i < m; i++ {
			fmt.Fscan(r, &u, &v, &wt)
			adj[u][v] = min(wt, adj[u][v])
			adj[v][u] = min(wt, adj[v][u])
			dist[u][v] = 1
			dist[v][u] = 1
		}

		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				for k := j+1; k <= n; k++ {
					dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k])
					dist[k][j] = dist[j][k]
				}
			}
		}

		cost := int(1e17)
		for i := 1; i <= n; i++ {
			for j := i+1; j <= n; j++ {
				cost = min(cost, (dist[1][i] + dist[j][n] + 1) * adj[i][j])
				cost = min(cost, (dist[1][j] + dist[i][n] + 1) * adj[i][j])

				for k := 1; k <= n; k++ {
					cost = min(cost, (dist[1][k] + dist[n][k] + dist[i][k] + 2) * adj[i][j])
					cost = min(cost, (dist[1][k] + dist[n][k] + dist[j][k] + 2) * adj[i][j])
				}
			}
		}

		fmt.Fprintln(w, cost)

	}

}

package main

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

func min(a, b int) int {
	if a < b { return a }
	return b
}

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m int
		fmt.Fscan(r, &n, &m)

		adj := make([][]int, 504)
		dist := make([][]int, 504)
		for i := range adj {
			adj[i] = make([]int, 504)
			dist[i] = make([]int, 504)
			for j := range adj[i] {
				adj[i][j] = 1e9 + 7
				dist[i][j] = 1e9 + 7
			}
			dist[i][i] = 0
		}

		var u, v, wt int
		for i := 0; i < m; i++ {
			fmt.Fscan(r, &u, &v, &wt)
			adj[u][v] = wt
			adj[v][u] = wt
			dist[u][v] = 1
			dist[v][u] = 1
		}

		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				for k := 1; k <= n; k++ {
					dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k])
					dist[k][j] = dist[j][k]
				}
			}
		}

		cost := int(1e17)
		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				cost = min(cost, (dist[1][i] + dist[j][n] + 1) * adj[i][j])
				cost = min(cost, (dist[1][j] + dist[i][n] + 1) * adj[i][j])

				for k := 1; k <= n; k++ {
					cost = min(cost, (dist[1][k] + dist[n][k] + dist[i][k] + 2) * adj[i][j])
					cost = min(cost, (dist[1][k] + dist[n][k] + dist[j][k] + 2) * adj[i][j])
				}
			}
		}

		fmt.Fprintln(w, cost)

	}

}

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m int
		fmt.Fscan(r, &n, &m)

		adj := make([][]int, 504)
		dist := make([][]int, 504)
		for i := range adj {
			adj[i] = make([]int, 504)
			dist[i] = make([]int, 504)
			for j := range adj[i] {
				adj[i][j] = 1e9 + 7
				dist[i][j] = 1e9 + 7
			}
			dist[i][i] = 0
		}

		var u, v, wt int
		for i := 0; i < m; i++ {
			fmt.Fscan(r, &u, &v, &wt)
			adj[u][v] = wt
			adj[v][u] = wt
			dist[u][v] = 1
			dist[v][u] = 1
		}

		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				for k := 1; k <= n; k++ {
					new_dist := dist[j][i] + dist[i][k]
					if new_dist < dist[j][k] {
						dist[j][k] = new_dist
						dist[k][j] = new_dist
					}
				}
			}
		}

		// fmt.Fprintln(w, " &&&&&&&&&&&&&&&&&&&&&&&&& ")
		/*
		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				fmt.Fprintln(w, "i, j dist ", i, j, dist[i][j])
			}
		}
		*/

		cost := int(1e17)
		var new_cost1, new_cost2 int
		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				new_cost1 = (dist[1][i] + dist[j][n] + 1) * adj[i][j]
				new_cost2 = (dist[1][j] + dist[i][n] + 1) * adj[i][j]
				if new_cost1 < cost {
					cost = new_cost1
				}
				if new_cost2 < cost {
					cost = new_cost2
				}

				for k := 1; k <= n; k++ {
					// fmt.Fprintln(w, " %%%%%%%%%%%%%%%%%%%%%%%%% ")
					// fmt.Fprintln(w, " i, j, k ", i, j, k)
					// fmt.Fprintf(w, "dist[1][i]: %d dist[n][i]: %d dist[j][i]: %d adj[j][k]: %d\n", dist[1][i], dist[n][i], dist[j][i], adj[j][k])
					// fmt.Fprintf(w, "dist[1][i]: %d dist[n][i]: %d dist[k][i]: %d adj[j][k]: %d\n", dist[1][i], dist[n][i], dist[k][i], adj[j][k])
					new_cost1 = (dist[1][k] + dist[n][k] + dist[i][k] + 2) * adj[i][j]
					new_cost2 = (dist[1][k] + dist[n][k] + dist[j][k] + 2) * adj[i][j]
					// fmt.Fprintf(w, "nc1: %d nc2: %d\n", new_cost1, new_cost2)
					if new_cost1 < cost {
						cost = new_cost1
					}
					if new_cost2 < cost {
						cost = new_cost2
					}
				}
			}
		}

		fmt.Fprintln(w, cost)

	}

}

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m int
		fmt.Fscan(r, &n, &m)

		adj := make([][]int, 504)
		dist := make([][]int, 504)
		for i := range adj {
			adj[i] = make([]int, 504)
			dist[i] = make([]int, 504)
			for j := range adj[i] {
				adj[i][j] = 1e9 + 7
				dist[i][j] = 1e9 + 7
			}
			dist[i][i] = 0
		}

		var u, v, wt int
		for i := 0; i < m; i++ {
			fmt.Fscan(r, &u, &v, &wt)
			adj[u][v] = wt
			adj[v][u] = wt
			dist[u][v] = 1
			dist[v][u] = 1
		}

		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				for k := j+1; k <= n; k++ {
					new_dist := dist[j][i] + dist[i][k]
					if new_dist < dist[j][k] {
						dist[j][k] = new_dist
						dist[k][j] = new_dist
					}
				}
			}
		}

		// fmt.Fprintln(w, " &&&&&&&&&&&&&&&&&&&&&&&&& ")
		/*
		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				fmt.Fprintln(w, "i, j dist ", i, j, dist[i][j])
			}
		}
		*/

		cost := int(1e17)
		var new_cost1, new_cost2 int
		for i := 1; i <= n; i++ {
			for j := i; j <= n; j++ {
				new_cost1 = (dist[1][i] + dist[j][n] + 1) * adj[i][j]
				new_cost2 = (dist[1][j] + dist[i][n] + 1) * adj[i][j]
				if new_cost1 < cost {
					cost = new_cost1
				}
				if new_cost2 < cost {
					cost = new_cost2
				}

				for k := 1; k <= n; k++ {
					// fmt.Fprintln(w, " %%%%%%%%%%%%%%%%%%%%%%%%% ")
					// fmt.Fprintln(w, " i, j, k ", i, j, k)
					// fmt.Fprintf(w, "dist[1][i]: %d dist[n][i]: %d dist[j][i]: %d adj[j][k]: %d\n", dist[1][i], dist[n][i], dist[j][i], adj[j][k])
					// fmt.Fprintf(w, "dist[1][i]: %d dist[n][i]: %d dist[k][i]: %d adj[j][k]: %d\n", dist[1][i], dist[n][i], dist[k][i], adj[j][k])
					new_cost1 = (dist[1][k] + dist[n][k] + dist[i][k] + 2) * adj[i][j]
					new_cost2 = (dist[1][k] + dist[n][k] + dist[j][k] + 2) * adj[i][j]
					// fmt.Fprintf(w, "nc1: %d nc2: %d\n", new_cost1, new_cost2)
					if new_cost1 < cost {
						cost = new_cost1
					}
					if new_cost2 < cost {
						cost = new_cost2
					}
				}
			}
		}

		fmt.Fprintln(w, cost)

	}

}


Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.  There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ..., an and p1, ..., pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

The first line of input contains integer n (1 ≤ n ≤ 105), the number of days. In the next n lines, i-th line contains two integers ai and pi (1 ≤ ai, pi ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

Print the minimum money needed to keep Duff happy for n days, in one line.

NoteIn the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

package main

import (
	"bufio"
	"os"
	"strconv"
	"math"
	"fmt"
)

var in *bufio.Scanner = bufio.NewScanner(os.Stdin)
var out *bufio.Writer = bufio.NewWriter(os.Stdout)

func main() {
	defer out.Flush()
	in.Split(bufio.ScanWords)

	sum, cost := 0, math.MaxInt32
	for i := nextInt(); i > 0; i-- {
		a := nextInt()
		cost = min(cost, nextInt())
		sum += a * cost
	}
	fmt.Println(sum)
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func nextInt() int {
	in.Scan()
	res, _ := strconv.Atoi(in.Text())
	return res
}

package main

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

var (
	reader  = bufio.NewReader(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	a, p := 0, 0
	totalMoney, minPrice := 0, 1<<31-1

	for n := nextInt(); n > 0; n-- {
		a, p = nextInt(), nextInt()
		if p < minPrice {
			minPrice = p
		}

		totalMoney += minPrice * a
	}

	println(totalMoney)
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

func next() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	var n, minp, a, p int
	fmt.Scanf("%d \n", &n)
	result := 0
	minp = 100
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		line, _ := reader.ReadString('\n')
		list := strings.Split(strings.TrimRight(line, "\r\n"), " ")
		temp, _ := strconv.ParseInt(list[0], 10, 64)
		a = int(temp)
		temp, _ = strconv.ParseInt(list[1], 10, 64)
		p = int(temp)

		if p < minp {
			minp = p
		}
		result += a * minp
	}
	fmt.Print(result)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	var n, minp, a, p int
	fmt.Scanf("%d \n", &n)
	result := 0
	minp = 100

	scanner := bufio.NewScanner(os.Stdin)

	for i := 0; i < n; i++ {
		scanner.Scan()
		line := scanner.Text()
		list := strings.Split(line, " ")
		temp, _ := strconv.ParseInt(list[0], 10, 64)
		a = int(temp)
		temp, _ = strconv.ParseInt(list[1], 10, 64)
		p = int(temp)

		if p < minp {
			minp = p
		}
		result += a * minp
	}
	fmt.Print(result)
}

package main

import "bufio"
import "os"
import "fmt"

func Read(s *bufio.Reader) string {
    line, _ := s.ReadString('\n')
    return line
}

func Write(s *bufio.Writer, a ...interface{}) {
    fmt.Fprintln(s, a...)
    s.Flush()
}

func main() {
    reader := bufio.NewReader(os.Stdin)

    var n int
    fmt.Sscanln(Read(reader), &n)

    a := make([][2]int, n)

    for i := 0; i < n; i++ {
        line, _ := reader.ReadString(' ')
        fmt.Sscanln(line, &a[i][0])
        fmt.Sscanln(Read(reader), &a[i][1])
    }

    var result int = 0
    var min int = 200
    for i := range a {
        if a[i][1] < min {
            min = a[i][1]
        }

        result += min * a[i][0]
    }

    writer := bufio.NewWriter(os.Stdout)
    Write(writer, result)
}

package main

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

/**
3
1 3
2 2
3 1
*/

type DuffMeat struct {
	Eat   int
	Price int
}

var Meats []DuffMeat

func main() {
	var n int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanln(reader, &n)
	Meats = make([]DuffMeat, n)
	for i := 0; i < n; i++ {
		fmt.Fscanln(reader, &Meats[i].Eat, &Meats[i].Price)
	}
	//fmt.Println(Meats)

	retMoney := 0
	x := 0
	y := len(Meats)
	for {
		if y == x {
			break
		}
		var tempMoney int
		y, tempMoney = eatMin(x, y)
		retMoney += tempMoney
	}
	fmt.Println(retMoney)
}

// 最小的index, money
func eatMin(x, y int) (int, int) {
	//fmt.Println(x, y)
	minIndex := x
	for i := x; i < y; i++ {
		if Meats[i].Price < Meats[minIndex].Price {
			minIndex = i
		}
	}
	count := 0
	for i := minIndex; i < y; i++ {
		count += Meats[i].Eat
	}
	return minIndex, count * Meats[minIndex].Price
}

package main

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func ReadInt32() int {
	scanner.Scan()
	return toInt(scanner.Bytes())
}

func toInt(buf []byte) (n int) {
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return n
}

func main() {
	scanner.Split(bufio.ScanWords)
	var n int
	n = ReadInt32()

	minPrice := math.MaxInt32
	totalCost := 0
	for i := 0; i < n; i++ {
		var ai, pi int
		ai = ReadInt32()
		pi = ReadInt32()
		if minPrice > pi {
			minPrice = pi

		}
		totalCost = totalCost + ai*minPrice

	}
	fmt.Print(totalCost)

}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin);
    var n int
    minVal := 101
    ans := 0

    fmt.Fscanln(reader, &n)

    for i:=0; i<n; i++ {
        var a, b int
        fmt.Fscanln(reader, &a, &b)
        if(minVal > b) {
            minVal = b
        }
        ans += minVal * a
    }
    fmt.Println(ans)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var count, prePrice, sumPrice int
	fmt.Fscanln(reader, &count)
	for i := 0; i < count; i++ {
		var a, p int
		fmt.Fscanln(reader, &a, &p)
		if prePrice == 0 {
			prePrice = p
		}
		if prePrice < p {
			sumPrice += a * prePrice
		} else {
			sumPrice += a * p
			prePrice = p
		}
	}
	fmt.Println(sumPrice)
}

package main

import (
	"fmt"
	"os"
	"bufio"
	"strconv"
)
var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func ReadInt32() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	var n,b int
	fmt.Scan(&n)
	c := 100
	for i:=0;i<n;i++ {
		a,p := ReadInt32(),ReadInt32()
		if p < c {
			c = p
		}
		b += c*a
	}

	fmt.Println(b)
}

package main

import (
	"fmt"
	"math"
)

func main() {

	var n int
	fmt.Scanf("%d\n",&n)
	minPrice := math.MaxInt32
	totalCost := 0
	for i := 0; i < n; i++ {
		var ai, pi int
		fmt.Scan("%d %d\n",&ai, &pi)
		if minPrice > pi {
			minPrice = pi

		}
		totalCost = totalCost + ai*minPrice

	}
	fmt.Print(totalCost)

}

package main

import (
	"fmt"
	"math"
)

func main() {

	var n int
	fmt.Scan(&n)
	minPrice := math.MaxInt32
	totalCost := 0
	for i := 0; i < n; i++ {
		var ai, pi int
		fmt.Scan(&ai, &pi)
		fmt.Print(ai, pi, "\n")
		if minPrice > pi {
			minPrice = pi

		}
		totalCost = totalCost + ai*minPrice

	}
	fmt.Print(totalCost)

}

package main

import (
	"fmt"
)

func main() {
	var count, prePrice, sumA, sumPrice int
	fmt.Scanf("%d", &count)
	for i := 0; i < count; i++ {
		var a, p int
		fmt.Scanf("%d %d", &a, &p)
		sumA += a
		if prePrice == 0 {
			prePrice = p
		}
		if prePrice < p {
			sumPrice += a * prePrice
		} else {
			sumPrice += a * p
		}
		prePrice = p
	}
	fmt.Println(sumPrice)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var count, prePrice, sumA, sumPrice int
	fmt.Fscanln(reader, &count)
	for i := 0; i < count; i++ {
		var a, p int
		fmt.Fscanln(reader, &a, &p)
		sumA += a
		if prePrice == 0 {
			prePrice = p
		}
		if prePrice < p {
			sumPrice += a * prePrice
		} else {
			sumPrice += a * p
		}
		prePrice = p
	}
	fmt.Println(sumPrice)
}


VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.

The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.

Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.

NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.

package main

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

// AVLTree structure. Public methods are Add, Remove, Update, Search, DisplayTreeInOrder.
type AVLTree struct {
	root *AVLNode
}

func (t *AVLTree) Add(key int, value int) {
	t.root = t.root.add(key, value)
}

func (t *AVLTree) Remove(key int) {
	t.root = t.root.remove(key)
}

func (t *AVLTree) Big() int {
	s := t.root.findBig()
	return s.Value
}

// AVLNode structure
type AVLNode struct {
	key   int
	Value int

	// height counts nodes (not edges)
	height int
	left   *AVLNode
	right  *AVLNode
}

// Displays nodes left-depth first (used for debugging)
func (n *AVLNode) displayNodesInOrder() {
	if n.left != nil {
		n.left.displayNodesInOrder()
	}
	fmt.Print(n.key, " ")
	if n.right != nil {
		n.right.displayNodesInOrder()
	}
}

// Adds a new node
func (n *AVLNode) add(key int, value int) *AVLNode {
	if n == nil {
		return &AVLNode{key, value, 1, nil, nil}
	}

	if key <= n.key {
		n.left = n.left.add(key, value)
	} else if key > n.key {
		n.right = n.right.add(key, value)
	}
	return n.rebalanceTree()
}

// Removes a node
func (n *AVLNode) remove(key int) *AVLNode {
	if n == nil {
		return nil
	}
	if key < n.key {
		n.left = n.left.remove(key)
	} else if key > n.key {
		n.right = n.right.remove(key)
	} else {
		if n.left != nil && n.right != nil {
			// node to delete found with both children;
			// replace vals with smallest node of the right sub-tree
			rightMinNode := n.right.findSmallest()
			n.key = rightMinNode.key
			n.Value = rightMinNode.Value
			// delete smallest node that we replaced
			n.right = n.right.remove(rightMinNode.key)
		} else if n.left != nil {
			// node only has left child
			n = n.left
		} else if n.right != nil {
			// node only has right child
			n = n.right
		} else {
			// node has no children
			n = nil
			return n
		}

	}
	return n.rebalanceTree()
}

func (n *AVLNode) getHeight() int {
	if n == nil {
		return 0
	}
	return n.height
}

func (n *AVLNode) recalculateHeight() {
	n.height = 1 + max(n.left.getHeight(), n.right.getHeight())
}

// Checks if node is balanced and rebalance
func (n *AVLNode) rebalanceTree() *AVLNode {
	if n == nil {
		return n
	}
	n.recalculateHeight()

	// check balance factor and rotateLeft if right-heavy and rotateRight if left-heavy
	balanceFactor := n.left.getHeight() - n.right.getHeight()
	if balanceFactor == -2 {
		// check if child is left-heavy and rotateRight first
		if n.right.left.getHeight() > n.right.right.getHeight() {
			n.right = n.right.rotateRight()
		}
		return n.rotateLeft()
	} else if balanceFactor == 2 {
		// check if child is right-heavy and rotateLeft first
		if n.left.right.getHeight() > n.left.left.getHeight() {
			n.left = n.left.rotateLeft()
		}
		return n.rotateRight()
	}
	return n
}

// Rotate nodes left to balance node
func (n *AVLNode) rotateLeft() *AVLNode {
	newRoot := n.right
	n.right = newRoot.left
	newRoot.left = n

	n.recalculateHeight()
	newRoot.recalculateHeight()
	return newRoot
}

// Rotate nodes right to balance node
func (n *AVLNode) rotateRight() *AVLNode {
	newRoot := n.left
	n.left = newRoot.right
	newRoot.right = n

	n.recalculateHeight()
	newRoot.recalculateHeight()
	return newRoot
}

// Finds the smallest child (based on the key) for the current node
func (n *AVLNode) findSmallest() *AVLNode {
	if n.left != nil {
		return n.left.findSmallest()
	} else {
		return n
	}
}

func (n *AVLNode) findBig() *AVLNode {
	if n.right != nil {
		return n.right.findBig()
	} else {
		return n
	}
}

func max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var n int
	fmt.Fscanf(r, "%d\n", &n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &a[i])
	}
	fmt.Fscanf(r, "\n")

	t := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &t[i])
	}
	fmt.Fscanf(r, "\n")

	mp := make(map[int][]int)
	cats := make([]int, 0)
	for i := 0; i < n; i++ {
		_, ok := mp[a[i]]
		if !ok {
			cats = append(cats, a[i])
		}
		mp[a[i]] = append(mp[a[i]], t[i])
	}

	sort.Ints(cats)

	tree := new(AVLTree)
	sum := int64(0)
	cc := 0
	ans := int64(0)
	for i, cat := range cats {
		for _, t := range mp[cat] {
			tree.Add(t, t)
			sum += int64(t)
			cc++
		}

		var lim int
		if i+1 < len(cats) {
			lim = cats[i+1]
		} else {
			lim = 2000000000
		}

		for j := cat; j < lim && cc > 0; j++ {
			big := tree.Big()
			tree.Remove(big)
			sum -= int64(big)
			cc--
			ans += sum
		}
	}

	fmt.Fprintf(w, "%d\n", ans)
}

package main

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

// AVLTree structure. Public methods are Add, Remove, Update, Search, DisplayTreeInOrder.
type AVLTree struct {
	root *AVLNode
}

func (t *AVLTree) Add(key int, value int) {
	t.root = t.root.add(key, value)
}

func (t *AVLTree) Remove(key int) {
	t.root = t.root.remove(key)
}

func (t *AVLTree) Big() int {
	s := t.root.findBig()
	return s.Value
}

// AVLNode structure
type AVLNode struct {
	key   int
	Value int

	// height counts nodes (not edges)
	height int
	left   *AVLNode
	right  *AVLNode
}

// Displays nodes left-depth first (used for debugging)
func (n *AVLNode) displayNodesInOrder() {
	if n.left != nil {
		n.left.displayNodesInOrder()
	}
	fmt.Print(n.key, " ")
	if n.right != nil {
		n.right.displayNodesInOrder()
	}
}

// Adds a new node
func (n *AVLNode) add(key int, value int) *AVLNode {
	if n == nil {
		return &AVLNode{key, value, 1, nil, nil}
	}

	if key < n.key {
		n.left = n.left.add(key, value)
	} else if key > n.key {
		n.right = n.right.add(key, value)
	} else {
		// if same key exists update value
		n.Value = value
	}
	return n.rebalanceTree()
}

// Removes a node
func (n *AVLNode) remove(key int) *AVLNode {
	if n == nil {
		return nil
	}
	if key < n.key {
		n.left = n.left.remove(key)
	} else if key > n.key {
		n.right = n.right.remove(key)
	} else {
		if n.left != nil && n.right != nil {
			// node to delete found with both children;
			// replace vals with smallest node of the right sub-tree
			rightMinNode := n.right.findSmallest()
			n.key = rightMinNode.key
			n.Value = rightMinNode.Value
			// delete smallest node that we replaced
			n.right = n.right.remove(rightMinNode.key)
		} else if n.left != nil {
			// node only has left child
			n = n.left
		} else if n.right != nil {
			// node only has right child
			n = n.right
		} else {
			// node has no children
			n = nil
			return n
		}

	}
	return n.rebalanceTree()
}

func (n *AVLNode) getHeight() int {
	if n == nil {
		return 0
	}
	return n.height
}

func (n *AVLNode) recalculateHeight() {
	n.height = 1 + max(n.left.getHeight(), n.right.getHeight())
}

// Checks if node is balanced and rebalance
func (n *AVLNode) rebalanceTree() *AVLNode {
	if n == nil {
		return n
	}
	n.recalculateHeight()

	// check balance factor and rotateLeft if right-heavy and rotateRight if left-heavy
	balanceFactor := n.left.getHeight() - n.right.getHeight()
	if balanceFactor == -2 {
		// check if child is left-heavy and rotateRight first
		if n.right.left.getHeight() > n.right.right.getHeight() {
			n.right = n.right.rotateRight()
		}
		return n.rotateLeft()
	} else if balanceFactor == 2 {
		// check if child is right-heavy and rotateLeft first
		if n.left.right.getHeight() > n.left.left.getHeight() {
			n.left = n.left.rotateLeft()
		}
		return n.rotateRight()
	}
	return n
}

// Rotate nodes left to balance node
func (n *AVLNode) rotateLeft() *AVLNode {
	newRoot := n.right
	n.right = newRoot.left
	newRoot.left = n

	n.recalculateHeight()
	newRoot.recalculateHeight()
	return newRoot
}

// Rotate nodes right to balance node
func (n *AVLNode) rotateRight() *AVLNode {
	newRoot := n.left
	n.left = newRoot.right
	newRoot.right = n

	n.recalculateHeight()
	newRoot.recalculateHeight()
	return newRoot
}

// Finds the smallest child (based on the key) for the current node
func (n *AVLNode) findSmallest() *AVLNode {
	if n.left != nil {
		return n.left.findSmallest()
	} else {
		return n
	}
}

func (n *AVLNode) findBig() *AVLNode {
	if n.right != nil {
		return n.right.findBig()
	} else {
		return n
	}
}

func max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var n int
	fmt.Fscanf(r, "%d\n", &n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &a[i])
	}
	fmt.Fscanf(r, "\n")

	t := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &t[i])
	}
	fmt.Fscanf(r, "\n")

	mp := make(map[int][]int)
	cats := make([]int, 0)
	for i := 0; i < n; i++ {
		_, ok := mp[a[i]]
		if !ok {
			cats = append(cats, a[i])
		}
		mp[a[i]] = append(mp[a[i]], t[i])
	}

	sort.Ints(cats)

	tree := new(AVLTree)
	sum := int64(0)
	ans := int64(0)
	for _, cat := range cats {
		for _, t := range mp[cat] {
			tree.Add(t, t)
			sum += int64(t)
		}
		big := tree.Big()
		tree.Remove(big)
		sum -= int64(big)
		ans += sum
	}

	fmt.Fprintf(w, "%d\n", ans)
}