The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

NoteLets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired. The answer is one, as one crime (on step 5) will go untreated.

package main

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

func main() {

	//Working solution, Runtime 888ms

	// var n, in int
	// fmt.Scan(&n)
	// var count, cops int
	// for i := 0; i < n; i++ {
	// 	fmt.Scan(&in)
	// 	if in == -1 {
	// 		if cops == 0 {
	// 			count++
	// 		} else {
	// 			cops--
	// 		}
	// 	} else {
	// 		cops += in
	// 	}
	// }
	// fmt.Println(count)

	var n int
	fmt.Scan(&n)
	var count, cops int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		scanner.Scan()
		val := scanner.Text()
		if val == "-1" {
			if cops == 0 {
				count++
			} else {
				cops--
			}
		} else {
			vals, _ := strconv.Atoi(val)
			cops += vals
		}
	}
	fmt.Println(count)
}

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

package main

import (
	"fmt"
)

func main() {
	n, x, l, z := 0, 0, 0, 0
	fmt.Scanf("%d ", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &x);
		if x == -1 {
			if l > 0 {
				l--
			} else {
				z++
			}
		} else {
			l += x
		}
	}
	fmt.Println(z)
}

package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n)
	sum := 0
	count := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&m)

		if m > 0 {
			count += m
		} else if count > 0 {
			count -= 1
		} else {
			sum += 1
		}
	}
	fmt.Println(sum)

}

package main

import "fmt"

func main() {
	var n, v int
	fmt.Scan(&n)

	untreated := 0
	police := 0
	crime := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&v)
		if v >= 0 {
			police += v
		} else {
			if police > 0 {
				police -= 1
			} else {
				crime += 1
				if crime > untreated {
					untreated = crime
				}
			}
		}
	}

	fmt.Print(untreated)
}

package main

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

var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n int

func main() {
	fmt.Fscan(reader, &n)
	var sum, ans int
	for ; n != 0; n-- {
		var a int
		fmt.Fscan(reader, &a)
		if a < 0 {
			if sum == 0 {
				ans++
			} else {
				sum--
			}
		} else {
			sum += a
		}
	}
	fmt.Println(ans)
}

package main

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

func main() {
	var n, t, c int32
	var pos uint32
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)
	for i := int32(0); i < n-1; i++ {
		fmt.Fscanf(in, "%d", &t)
		if t < 0 {
			if pos == 0 {
				c += int32(math.Abs(float64(t)))
			} else {
				pos--
			}
		} else {
			pos += uint32(t)
		}
	}
	fmt.Fscanf(in, "%d\n", &t)
	if t < 0 {
		if pos == 0 {
			c += int32(math.Abs(float64(t)))
		} else {
			pos--
		}
	} else {
		pos += uint32(t)
	}
	fmt.Println(math.Abs(float64(c)))
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var total int
	var hired int
	var out int
	fmt.Fscan(reader, &total)
	for i := 0; i < total; i++ {
		var in int
		fmt.Fscan(reader, &in)
		if in == -1 {
			if hired == 0 {
				out++
			} else {
				hired--
			}
		}
		if in > 0 {
			hired += in
		}
	}
	fmt.Println(out)
}

package main

import (
    "fmt"
    )

func main() {
    var n int
    fmt.Scan(&n)

    event := 0
    police := 0
    result := 0
    for i := 0; i < n; i++ {
        fmt.Scan(&event)
        if event < 0 {
            if police > 0 {
                police--
            } else {
                result++
            }
        } else {
            police += event
        }
    }

    fmt.Println(result)
}

package main

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

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

	fmt.Fscan(reader, &noOfEvents)
	var noOfOfficers, untreatedCrimes, event int
	for index := 0; index < noOfEvents; index++ {
		fmt.Fscan(reader, &event)
		if event != -1 { //Case hire offices
			noOfOfficers += event
		} else { //Case new case
			if noOfOfficers == 0 { //No officers
				untreatedCrimes++
			} else {
				//Assign offices to case
				noOfOfficers--
			}
		}
	}
	fmt.Println(untreatedCrimes)
}

package main

import "fmt"

func main() {
	var noOfEvents int
	fmt.Scan(&noOfEvents)
	var noOfOfficers, untreatedCrimes, event int
	for index := 0; index < noOfEvents; index++ {
		fmt.Scan(&event)
		if event != -1 { //Case hire offices
			noOfOfficers += event
		} else { //Case new case
			if noOfOfficers == 0 { //No officers
				untreatedCrimes++
			} else {
				//Assign offices to case
				noOfOfficers--
			}
		}
	}
	fmt.Println(untreatedCrimes)
}

// 427A-mic
package main

import (
    "fmt"
    "math"
)

func main() {
    var n, crime, police, k int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&k)
        if k < 0 && police == 0 {
            crime += k
        } else {
            police += k
        }
    }
    fmt.Println(int(math.Abs(float64(crime))))
}

package main
import (
    "fmt"
)
func main() {
    var b,c int
    fmt.Scan(&b)
    s,n:=0,0
    for i:=0; i<b; i++ {
        fmt.Scan(&c)
        if c==-1 {
            if s==0 {
                n++
            } else {s--}
        }else {
            s+=c
        }
    }
    fmt.Println(n)
}

package main

import ("fmt")

type set map[byte]bool
type long int64
type fl float64

func main(){
	var n, t, w, p int
	scan(&n)
	for i := 0; i < n; i++{
		scan(&t)
		if t > 0{
			p+=t
			}else{
				if p > 0{
					p--
				}else{
					w++
				}
			}
	}
	sout(w)
}

func scan(in ... interface{}){
	for _,k := range in{
		fmt.Scan(k)
	}
}

func sout(obj ... interface{}){
	for _, k := range obj{
		fmt.Print(k)
	}
	fmt.Println()
}

package main

import ("bufio";"os";"strconv")

func main(){
	defer out.Flush()
    scan.Split(bufio.ScanWords)
    var n, t, w, p int
	n = nextInt()
	for i := 0; i < n; i++{
		t = nextInt()
		if t > 0{
			p+=t
			}else{
				if p > 0{
					p--
				}else{
					w++
				}
			}
	}
	sout(w)

}

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

var out *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func next()string{
	scan.Scan()
	return scan.Text()
}

func sout(obj ... int) {
    for _, value := range obj {
        out.WriteString(strconv.Itoa(value))
      //  out.WriteByte(' ')
    }
}

package main

// https://codeforces.com/problemset/problem/427/A
// A. Police Recruits
// time limit per test
// 1 second
// memory limit per test
// 256 megabytes
// input
// standard input
// output
// standard output

// The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.

// Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.

// If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.

// Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
// Input

// The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers.

// If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.
// Output

// Print a single integer, the number of crimes which will go untreated.

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

var (
    bufStdin  = bufio.NewReader(os.Stdin)
    bufStdout = bufio.NewWriter(os.Stdout)
)

func main() {
    defer bufStdout.Flush()

    var n int
    _, _ = fmt.Fscan(bufStdin, &n)

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

    var copsAvailable, untreatedCrimes int
    for _, event := range events {
        if event == -1 {
            // crime occurred
            if copsAvailable == 0 {
                untreatedCrimes++
            } else {
                copsAvailable--
            }
        } else {
            // some number of cops was recruited
            copsAvailable += event
        }
    }

    _, _ = fmt.Fprintln(bufStdout, untreatedCrimes)
}

package main

import "fmt"

// https://codeforces.com/problemset/problem/427/A
// комментарии к решению
// Для решения нам необходимо на каждом событии знать кол-во
// свободных полицейских, а далее мы просто итерируемся по массиву,
// идентифицируя каждое событие как один из 3-х возможных вариантов
func taskSolution(a []int) (ans int) {
	for i, free_officers := 0, 0; i < len(a); i += 1 {
		if a[i] > 0 {
			free_officers += a[i]
		} else if free_officers > 0 {
			free_officers -= 1
		} else {
			ans += 1
		}
	}
	return ans
}

func main() {
	var n int
	if _, err := fmt.Scan(&n); err != nil {
		panic(err)
	}

	a := []int{}
	for i := 0; i < n; i += 1 {
		var ai int
		if _, err := fmt.Scan(&ai); err != nil {
			panic(err)
		}
		a = append(a, ai)
	}

	fmt.Println(taskSolution(a))
}

package main

import "fmt"

func main()  {
	var noOfEvents int
	fmt.Scan(&noOfEvents)

	var noOfCrimes int
	noORecruits := 0
	for index := 0; index < noOfEvents; index++ {
		var event int
		fmt.Scan(&event)
		if event < 0 {
			if noORecruits > 0 {
				noORecruits = noORecruits - 1
			} else {
				noOfCrimes = noOfCrimes + 1
			}
		} else {
			noORecruits = noORecruits + event
		}
	}
	fmt.Println(noOfCrimes)
}

package main
import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var a [100000]int
	for i:=0;i<n;i++ {
		fmt.Scan(&a[i])
	}
	result:=0
	t:=0
	for i:=0;i<n;i++ {
		if a[i]<0 && t==0 {
			result+=t+a[i]
			if t>-a[i] {
				t=t+a[i]
			} else {
				t=0
			}
		} else {
			t+=a[i]
		}
	}
	fmt.Println(-result)
}

package main

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

func main() {
	var n, tmp int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &n)
	manpower := 0
	untreated := 0
	for i := 0; i < n; i += 1 {
		fmt.Fscan(reader, &tmp)
		if tmp > 0 {
			manpower += tmp
		} else if manpower > 0 {
			manpower -= 1
		} else {
			untreated += 1
		}
	}
	fmt.Println(untreated)
}

package main

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

func main() {
	var n, c int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &n)
	p := 0
	count := 0
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &c)
		p = p + c
		if p < 0 {
			count++
			p = 0
		}
	}
	fmt.Println(count)
}

package main

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

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

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

	n := nextInt()
	a := 0
	numberOfRecruited := 0
	count := 0

	for i:=0; i<n; i++ {
		a = nextInt()

		if a > 0 {
			numberOfRecruited += a
		} else {
			if numberOfRecruited > 0 {
				numberOfRecruited--
			} else {
				count++
			}
		}
	}

	println(count)
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	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"
)

var (
    reader = bufio.NewReader(os.Stdin)
)

func main() {
    var n, x, g, cnt int
    fmt.Fscan(reader, &n)
    for i := 1; i <= n; i++ {
        fmt.Fscan(reader, &x)
        if x == -1 {
            if g == 0 {
                cnt++
            } else {
                g--
            }
        } else {
            g += x
        }
    }
    fmt.Println(cnt)
}

package main

import (
	"fmt"
)

func main() {
	var n, temp int
	fmt.Scanf("%d \n", &n)
	count := 0
	free := 0
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &temp)
		if temp == -1 {
			if free == 0 {
				count++
			}
		}
		free += temp
		if free < 0 {
			free = 0
		}
	}
	fmt.Print(count)
}

package main

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

func main() {
	var n, temp int
	fmt.Scanf("%d \n", &n)
	count := 0
	free := 0
	reader := bufio.NewReader(os.Stdin)
	ss, _ := reader.ReadString('\n')
	list := strings.Split(strings.TrimRight(ss, "\r\n"), " ")
	for i := 0; i < n; i++ {
		t, _ := strconv.ParseInt(list[i], 10, 64)
		temp = int(t)
		if temp == -1 {
			if free == 0 {
				count++
			}
		}
		free += temp
		if free < 0 {
			free = 0
		}
	}
	fmt.Print(count)
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)

    var n int
    fmt.Scan(&n)
    ans, police := 0, 0
    for i := 0; i < n; i++ {
        scanner.Scan()
        a, _ := strconv.Atoi(scanner.Text())
        if a < 0 {
            if police > 0 {
                police--
            } else {
                ans++
            }
        } else {
            police += a
        }
    }
    fmt.Println(ans)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	var officers int
	var untreated int
	for i := 0; i < n; i++ {
		var event int
		fmt.Scanf("%d", &event)
		if event == -1 {
			if officers == 0 {
				untreated++
			} else {
				officers--
			}
		} else {
			officers += event
		}

	}
	fmt.Println(untreated)
}

package main

import (
	"bufio"
	"errors"
	"flag"
	"os"
	"strconv"
	"time"
)

// ******************************** CODE STARTS ********************************

var ()

func solve() {
	n := readInt()

	have := 0
	ans := 0
	for i := 0; i < n; i++ {
		value := readInt()
		if value == -1 {
			if have == 0 {
				ans++
			} else {
				have--
			}
		} else {
			have += value
		}
	}
	printInt(ans)
	printLine()
}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *bufio.Scanner
	writer  *bufio.Writer
)

func main() {
	local := flag.Bool("local", false, "Defines whether run is local or remote.")
	flag.Parse()

	var (
		input  *os.File
		output *os.File
	)

	if *local {
		input, _ = os.Open("/home/outside/coding/workspace/go/io/input.txt")
		output, _ = os.Create("/home/outside/coding/workspace/go/io/output.txt")
		startTime := time.Now()
		defer func() {
			print("Time: ")
			print(strconv.FormatFloat(time.Since(startTime).Seconds(), 'f', 5, 64))
			println("s")
		}()
	} else {
		input = os.Stdin
		output = os.Stdout
		// input, _ = os.Open("")
		// output, _ = os.Create("")
	}
	defer input.Close()
	defer output.Close()

	scanner = bufio.NewScanner(input)
	writer = bufio.NewWriter(output)
	defer writer.Flush()

	scanner.Split(bufio.ScanWords)

	solve()
}

// Read.

func readString() string {
	scanner.Scan()
	ans := scanner.Text()
	return ans
}

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

func readInt64() int64 {
	ans, _ := strconv.ParseInt(readString(), 10, 64)
	return ans
}

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFLoat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Min, max, abs.

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

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

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

package main

import "fmt"

func main() {
	var n, in int
	fmt.Scan(&n)
	var count, cops int
	for i := 0; i < n; i++ {
		fmt.Scan(&in)
		if in == -1 {
			if cops == 0 {
				count++
			} else {
				cops--
			}
		} else {
			cops += in
		}
	}
	fmt.Println(count)
}

package main

import (
	"fmt"
)

func main() {
	n, x, l, z := 0, 0, 0, 0
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &x);
		if x == -1 {
			if l > 0 {
				l--
			} else {
				z++
			}
		} else {
			l += x
		}
	}
	fmt.Println(z)
}

package main

import (
	"fmt"
)

func main() {
	var n, x int
	l, z := 0, 0
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &x);
		if x == -1 {
			if l > 0 {
				l--
			} else {
				z++
			}
		} else {
			l += x
		}
	}
	fmt.Println(z)
}

package main

import (
	"fmt"
)

func main() {
	var n, m int
	fmt.Scan(&n)
	sum := 0
	count := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&m)

		if m > 0 {
			count += 1
		} else if count > 0 {
			count -= 1
		} else {
			sum += 1
		}
	}
	fmt.Println(sum)

}

package main

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

var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n int

func main() {
	fmt.Fscan(reader, &n)
	var sum, ans int
	for ; n != 0; n-- {
		var a int
		fmt.Fscan(reader, &a)
		if a < 0 {
			if sum == 0 {
				ans++
			} else {
				sum--
			}
		} else {
			sum = a
		}
	}
	fmt.Println(ans)
}

package main

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

func main() {
	var n, t, c int16
	var pos uint16
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)
	for i:=int16(0); i < n - 1; i++{
		fmt.Fscanf(in, "%d", &t)
		if t < 0{
			if pos == 0{
				c += t
			}else{
				pos--
			}
		}else{
			pos++
		}
	}
	fmt.Fscanf(in, "%d\n", &t)
	if t < 0{
		if pos == 0{
			c += t
		}
	}else{
		pos++
	}
	fmt.Println(math.Abs(float64(c)))
}

package main

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

func main() {
	var n, t, c int16
	var pos uint16
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)
	for i := int16(0); i < n-1; i++ {
		fmt.Fscanf(in, "%d", &t)
		if t < 0 {
			if pos == 0 {
				c += int16(math.Abs(float64(t)))
			} else {
				pos--
			}
		} else {
			pos += uint16(t)
		}
	}
	fmt.Fscanf(in, "%d\n", &t)
	if t < 0 {
		if pos == 0 {
			c += int16(math.Abs(float64(t)))
		} else {
			pos--
		}
	} else {
		pos += uint16(t)
	}
	fmt.Println(math.Abs(float64(c)))
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdout)
	var total int
	var hired int
	var out int
	fmt.Fscan(reader, &total)
	for i := 0; i < total; i++ {
		var in int
		fmt.Fscan(reader, &in)
		if in == -1 {
			if hired == 0 {
				out++
			} else {
				hired--
			}
		}
		if in > 0 {
			hired += hired
		}
		//fmt.Println(in,out,hired)
	}
	fmt.Println(out)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var total int
	var hired int
	var out int
	fmt.Fscan(reader, &total)
	for i := 0; i < total; i++ {
		var in int
		fmt.Fscan(reader, &in)
		if in == -1 {
			if hired == 0 {
				out++
			} else {
				hired--
			}
		}
		if in > 0 {
			hired += 1
		}
	}
	fmt.Println(out)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdout)
	var total int
	var hired int
	var out int
	fmt.Fscan(reader, &total)
	for i := 0; i < total; i++ {
		var in int
		fmt.Fscan(reader, &in)
		if in == -1 {
			if hired == 0 {
				out++
			} else if hired > 0 {
				hired--
			}
		}
		if in > 0 {
			hired++
		}
	}
	fmt.Println(out)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var total int
	var hired int
	var out int
	fmt.Fscan(reader, &total)
	for i := 0; i < total; i++ {
		var in int
		fmt.Fscan(reader, &in)
		if in == -1 {
			if hired == 0 {
				out++
			} else {
				hired--
			}
		}
		if in > 0 {
			hired += hired
		}
		//fmt.Println(in,out,hired)
	}
	fmt.Println(out)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdout)
	var total int
	var hired int
	var out int
	fmt.Fscan(reader, &total)
	for i := 0; i < total; i++ {
		var in int
		fmt.Fscan(reader, &in)
		if in == -1 {
			if hired == 0 {
				out++
			} else if hired > 0 {
				hired--
			}
		}
		if in > 0 {
			hired++
		}
		//fmt.Println(in,out,hired)
	}
	fmt.Println(out)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var total int
	var hired int
	var out int
	fmt.Fscan(reader, &total)
	for i := 0; i < total; i++ {
		var in int
		fmt.Fscan(reader, &in)
		if in == -1 {
			if hired == 0 {
				out++
			} else {
				hired--
			}
		}
		if in > 0 {
			hired += 1
		}
		fmt.Println(in, out, hired)
	}
	fmt.Println(out)
}

package main

import "fmt"

func main() {
	var noOfEvents int
	fmt.Scan(&noOfEvents)
	var noOfOfficers, untreatedCrimes, event int
	for index := 0; index < noOfEvents; index++ {
		fmt.Scan(&event)
		if event == 1 { //Case hire offices
			noOfOfficers++
		} else { //Case new case
			if noOfOfficers == 0 { //No officers
				untreatedCrimes++
			} else {
				//Assign offices to case
				noOfOfficers--
			}
		}
	}
	fmt.Println(untreatedCrimes)
}

package main

import "fmt"

func main()  {
	var noOfEvents int
	fmt.Scan(&noOfEvents)

	noOfCrimes := 0
	noORecruits := 0

	for index := 0; index < noOfEvents; index++ {
		var event int
		fmt.Scan(&event)
		if event < 0 {
			if noORecruits >= noOfCrimes {
				noOfCrimes = noOfCrimes - noORecruits
				noORecruits = noORecruits - 1
			}

			if noORecruits > 0 {
				noORecruits = noORecruits - 1
				noOfCrimes = noOfCrimes - 1
			} else {
				noOfCrimes = noOfCrimes + 1
			}
		} else {
			noORecruits = noORecruits + event
		}
	}
	fmt.Println(noOfCrimes)
}

package main
import (
	"fmt"
)
func main() {
	var b,c int
	fmt.Scan(&b)
	s,n:=0,0
	for i:=0; i<b; i++ {
		fmt.Scan(&c)
		if c==-1 {
			if s==0 {
				n++
			} else {s--}
		}else {
			s+=b
		}
	}
	fmt.Println(n)
}

package main

import (
	"bufio"
	"errors"
	"flag"
	"os"
	"strconv"
	"time"
)

// ******************************** CODE STARTS ********************************

var ()

func solve() {
	n := readInt()

	have := 0
	ans := 0
	for i := 0; i < n; i++ {
		value := readInt()
		if value == -1 {
			if have == 0 {
				ans++
			}
		} else {
			have += value
		}
	}
	printInt(ans)
	printLine()
}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *bufio.Scanner
	writer  *bufio.Writer
)

func main() {
	local := flag.Bool("local", false, "Defines whether run is local or remote.")
	flag.Parse()

	var (
		input  *os.File
		output *os.File
	)

	if *local {
		input, _ = os.Open("/home/outside/coding/workspace/go/io/input.txt")
		output, _ = os.Create("/home/outside/coding/workspace/go/io/output.txt")
		startTime := time.Now()
		defer func() {
			print("Time: ")
			print(strconv.FormatFloat(time.Since(startTime).Seconds(), 'f', 5, 64))
			println("s")
		}()
	} else {
		input = os.Stdin
		output = os.Stdout
		// input, _ = os.Open("")
		// output, _ = os.Create("")
	}
	defer input.Close()
	defer output.Close()

	scanner = bufio.NewScanner(input)
	writer = bufio.NewWriter(output)
	defer writer.Flush()

	scanner.Split(bufio.ScanWords)

	solve()
}

// Read.

func readString() string {
	scanner.Scan()
	ans := scanner.Text()
	return ans
}

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

func readInt64() int64 {
	ans, _ := strconv.ParseInt(readString(), 10, 64)
	return ans
}

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFLoat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Min, max, abs.

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

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

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}


Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.

The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).

Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9. Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if .

NoteIn the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for . Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for . Thus, after four minutes the chicken will be cooked for . Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready .In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.

package main

import "fmt"

func main() {
	var k, d, t int64
	fmt.Scan(&k, &d, &t)
	x := (k + (d - 1)) / d // po kelių kartų ras išjungtą
	p := x * d
	t *= 2
	perP := k*2 + p - k
	ans := float64(t / perP * p)
	t %= perP
	if t <= k*2 {
		ans += float64(t) / 2
	} else {
		ans += float64(k + t - k*2)
	}
	fmt.Println(ans)
}

package main

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

var scanner *bufio.Scanner
var t [1e6 + 1]bool

func init_scanner() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024 * 20
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int64 {
	scanner.Scan()
	val, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return val
}

func main() {
	init_scanner()
	k, d, t := readInt(), readInt(), readInt()
	//fmt.Println(k, d, t)
	y := ((k-1)/d + 1) * d
	x := float64(k) + float64(y-k)/2.
	z := float64(t) - math.Floor(float64(t)/x)*x
	//fmt.Println(x, y, z, math.Floor(float64(t)/x))
	//fmt.Println(math.Floor(float64(t)/x)*float64(y), math.Max(0., z-float64(k)))
	fmt.Println(math.Floor(float64(t)/x)*float64(y) + z + math.Max(0., z-float64(k)))
}

package main

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

var scanner *bufio.Scanner
var t [1e6 + 1]bool

func init_scanner() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024 * 20
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	scanner.Scan()
	val, _ := strconv.Atoi(scanner.Text())
	return val
}

func main() {
	init_scanner()
	k, d, t := readInt(), readInt(), readInt()

	y := ((k-1)/d + 1) * d
	x := float64(k) + float64(y-k)/2.
	z := float64(t) - math.Floor(float64(t)/x)*x
	fmt.Println(x, y, z)
	fmt.Println(math.Floor(float64(t)/x)*float64(y) + z + math.Max(0., z-float64(k)))
}

package main

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

var scanner *bufio.Scanner
var t [1e6 + 1]bool

func init_scanner() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024 * 20
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	scanner.Scan()
	val, _ := strconv.Atoi(scanner.Text())
	return val
}

func main() {
	init_scanner()
	k, d, t := readInt(), readInt(), readInt()

	y := ((k-1)/d + 1) * d
	x := float64(k) + float64(y-k)/2.
	z := float64(t) - math.Floor(float64(t)/x)*x
	// fmt.Println(x, y, z)
	fmt.Println(math.Floor(float64(t)/x)*float64(y) + z + math.Max(0., z-float64(k)))
}


You are given a sequence a consisting of n integers. Find the maximum possible value of  (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.

The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).  The second line contains n space-separated integers ai (1 ≤ ai ≤ 106).

package main

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

const (
	maxN = 2000005
)

var A [maxN]int
var MI [maxN]int

func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	for i := 0; i < N; i++ {
		x := fsc.NextInt()
		A[x] = 1
	}
	for i := 1; i < maxN; i++ {
		if A[i] == 1 {
			MI[i] = i
		} else {
			MI[i] = MI[i-1]
		}
	}
	ma := 0
	for i := 1; i < 1000001; i++ {
		if A[i] == 1 {
			for j := 2; j*i-1 < maxN; j++ {
				// fmt.Println(i, j, j*i-1)
				ma = IntMax(ma, MI[j*i-1]%i)
			}
		}
	}
	fmt.Println(ma)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1024)
	return &FastScanner{r: rdr}
}
func (s *FastScanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *FastScanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *FastScanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *FastScanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *FastScanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *FastScanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

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

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

package main

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

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

const MAXN = 2000010

func main() {

	defer out.Flush()
	in.Split(bufio.ScanWords)

	var n int = NextInt()
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
	}

	sort.Ints(a)

	p := make([]int, MAXN)
	for i := 1; i < MAXN; i++ {
		var lo, hi int = -1, n
		for hi - lo > 1 {
			var m int = lo + (hi - lo) / 2
			if a[m] < i {
				lo = m
			}else {
				hi = m
			}
		}
		p[i] = lo
	}
	var ret int = -1
	for i := 0; i < n; i++ {
		if i > 0 && a[i - 1] == a[i] {
			continue
		}
		for j := 2 * a[i]; j < MAXN; j += a[i] {
			ret = Max(ret, a[p[j]] % a[i])
		}
	}

	fmt.Fprintln(out, ret)
}

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

func Next() string{
	if !in.Scan() {
		panic("Scan error")
	}
	return in.Text()
}

func NextInt() int{
	ret, _ := strconv.Atoi(Next())
	return ret
}

package main

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

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

const MAXN = 2000010

func main() {

	defer out.Flush()
	in.Split(bufio.ScanWords)

	var n int = NextInt()
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
	}

	p := make([]int, MAXN)
	for i := 1; i < MAXN; i++ {
		var lo, hi int = -1, n
		for hi - lo > 1 {
			var m int = lo + (hi - lo) / 2
			if a[m] < i {
				lo = m
			}else {
				hi = m
			}
		}
		p[i] = lo
	}
	var ret int = -1
	for i := 0; i < n; i++ {
		if i > 0 && a[i - 1] == a[i] {
			continue
		}
		for j := 2 * a[i]; j < MAXN; j += a[i] {
			ret = Max(ret, a[p[j]] % a[i])
		}
	}

	fmt.Fprintln(out, ret)
}

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

func Next() string{
	if !in.Scan() {
		panic("Scan error")
	}
	return in.Text()
}

func NextInt() int{
	ret, _ := strconv.Atoi(Next())
	return ret
}

package main

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

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

const MAXN = 20000010

func main() {

	defer out.Flush()
	in.Split(bufio.ScanWords)
	var n int = NextInt()
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
	}

	p := make([]int, MAXN)
	for i := 1; i < MAXN; i++ {
		var lo, hi int = -1, n
		for hi - lo > 1 {
			var m int = lo + (hi - lo) / 2
			if a[m] < i {
				lo = m
			}else {
				hi = m
			}
		}
		p[i] = lo
	}
	var ret int = -1
	for i := 0; i < n; i++ {
		if i > 0 && a[i] == a[i-1] {
			continue
		}
		for j := 2 * a[i]; j < MAXN; j += a[i] {
			var pos int = p[j]
			ret = Max(ret, a[pos] % a[i])
		}
	}

	fmt.Fprintln(out, ret)
}

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

func Next() string{
	if !in.Scan() {
		panic("Scan error")
	}
	return in.Text()
}

func NextInt() int{
	ret, _ := strconv.Atoi(Next())
	return ret
}


Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $$$80\%$$$ of applicants are girls and majority of them are going to live in the university dormitory for the next $$$4$$$ (hopefully) years.The dormitory consists of $$$n$$$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $$$i$$$ costs $$$c_i$$$ burles. Rooms are numbered from $$$1$$$ to $$$n$$$.Mouse doesn't sit in place all the time, it constantly runs. If it is in room $$$i$$$ in second $$$t$$$ then it will run to room $$$a_i$$$ in second $$$t + 1$$$ without visiting any other rooms inbetween ($$$i = a_i$$$ means that mouse won't leave room $$$i$$$). It's second $$$0$$$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $$$1$$$ to $$$n$$$ at second $$$0$$$.What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?

The first line contains as single integers $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of rooms in the dormitory. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^4$$$) — $$$c_i$$$ is the cost of setting the trap in room number $$$i$$$. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — $$$a_i$$$ is the room the mouse will run to the next second after being in room $$$i$$$.

Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.

NoteIn the first example it is enough to set mouse trap in rooms $$$1$$$ and $$$4$$$. If mouse starts in room $$$1$$$ then it gets caught immideately. If mouse starts in any other room then it eventually comes to room $$$4$$$.In the second example it is enough to set mouse trap in room $$$2$$$. If mouse starts in room $$$2$$$ then it gets caught immideately. If mouse starts in any other room then it runs to room $$$2$$$ in second $$$1$$$.Here are the paths of the mouse from different starts from the third example:  $$$1 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$2 \rightarrow 2 \rightarrow \dots$$$;  $$$3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$4 \rightarrow 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$5 \rightarrow 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$;  $$$6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$;  $$$7 \rightarrow 6 \rightarrow 7 \rightarrow \dots$$$; So it's enough to set traps in rooms $$$2$$$ and $$$6$$$.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1027D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	var n, s int
	Fscan(in, &n)
	c := make([]int, n)
	for i := range c {
		Fscan(in, &c[i])
	}
	g := make([]int, n)
	deg := make([]int, n)
	for i := range g {
		Fscan(in, &g[i])
		g[i]--
		deg[g[i]]++
	}

	vis := make([]bool, n)
	q := []int{}
	for i, d := range deg {
		if d == 0 {
			q = append(q, i)
		}
	}
	for len(q) > 0 {
		v := q[0]
		vis[v] = true
		q = q[1:]
		w := g[v]
		deg[w]--
		if deg[w] == 0 {
			q = append(q, w)
		}
	}

	var f func(int) int
	f = func(v int) int {
		vis[v] = true
		if vis[g[v]] {
			return c[v]
		}
		return min(f(g[v]), c[v])
	}
	for i, b := range vis {
		if !b {
			s += f(i)
		}
	}
	Fprint(out, s)
}

func main() { CF1027D(os.Stdin, os.Stdout) }

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1027D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, s int
	Fscan(in, &n)
	c := make([]int, n)
	for i := range c {
		Fscan(in, &c[i])
	}
	g := make([]int, n)
	deg := make([]int, n)
	for i := range g {
		Fscan(in, &g[i])
		g[i]--
		deg[g[i]]++
	}

	vis := make([]bool, n)
	q := []int{}
	for i, d := range deg {
		if d == 0 {
			q = append(q, i)
		}
	}
	for len(q) > 0 {
		v := q[0]
		q = q[1:]
		vis[v] = true
		w := g[v]
		deg[w]--
		if deg[w] == 0 {
			q = append(q, w)
		}
	}

	for i, b := range vis {
		if !b {
			min := int(1e9)
			for v := i; !vis[v]; v = g[v] {
				vis[v] = true
				if c[v] < min {
					min = c[v]
				}
			}
			s += min
		}
	}
	Fprint(out, s)
}

func main() { CF1027D(os.Stdin, os.Stdout) }

package main

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

var scanner * bufio.Scanner

func next_int()(result int64){
  if !scanner.Scan() {
    panic("Unable to read next integer. Input has no data remain")
  }
  res, err := strconv.ParseInt(scanner.Text(), 10, 32)
  if err != nil {
    panic(err)
  }
  return res
}

func next_str()(result string){
  if !scanner.Scan() {
    panic("Unable to read next token. Input has no data remain")
  }
  return scanner.Text()
}

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

var INF int = 2 * 1000 * 1000 * 1000
var c []int = nil
var next []int = nil
var cost []int = nil
var used []int8 = nil
var stack []int = nil

func check_in_stack(v int)(bool) {
  return (used[v] & (1 << 1)) > 0
}
func invert_in_stack(v int)() {
  used[v] = used[v] ^ (1 << 1);
  return
}
func is_used(v int)(bool){
  return (used[v] & 1) > 0
}
func set_used(v int)(){
  used[v] = used[v] ^ 1;
}

func get_min_cost(v int)(int, bool){
  set_used(v)
  invert_in_stack(v)
  stack = append(stack, v)

  res := INF
  solved_before := false
  if check_in_stack(next[v]) { // cycle found!
    for j := len(stack)-1; j >= 0; j-- {
      res = min(res, c[stack[j]])
      if stack[j] == next[v] {
        break
      }
    }
  } else if is_used(next[v]) { // it was solved before, just extract the answer
    res = cost[next[v]]
    solved_before = true
  } else { // no cycle, not solved before - go deeper
    ch_res, solved_ch := get_min_cost(next[v])
    res = ch_res
    solved_before = solved_ch
  }

  invert_in_stack(v)
  stack = stack[0:len(stack)-1]
  return res, solved_before
}

func main() {

  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)

  n := int(next_int());
  c = make([]int, n, n)
  next = make([]int, n, n)
  cost = make([]int, n, n)
  stack = make([]int, 0 , n)
  used = make([]int8, n, n)

  for i := 0; i < n; i++ {
    c[i] = int(next_int());
    used[i] = 0
    cost[i] = INF
  }
  for i := 0; i < n; i++ {
    next[i] = int(next_int() - 1);
  }
  var ans int = 0
  for i := 0; i < n; i++ {
    if 0 == used[i] {
      minc, solved_before := get_min_cost(i)
      if !solved_before {
        ans = ans + minc
      }
    }
  }
  fmt.Println(ans);
  return
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1027D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, min, s int
	Fscan(in, &n)
	c := make([]int, n)
	for i := range c {
		Fscan(in, &c[i])
	}
	g := make([]int, n)
	deg := make([]int, n)
	for i := range g {
		Fscan(in, &g[i])
		g[i]--
		deg[g[i]]++
	}

	vis := make([]int8, n)
	var f func(v int)
	f = func(v int) {
		if vis[v] == 2 {
			return
		}
		vis[v]++
		if vis[v] == 2 && c[v] < min {
			min = c[v]
		}
		f(g[v])
	}
	for i, d := range deg {
		if d == 0 {
			min = 1e9
			f(i)
			if min < 1e9 {
				s += min
			}
		}
	}
	for i, c := range vis {
		if c == 0 {
			min = 1e9
			f(i)
			if min < 1e9 {
				s += min
			}
		}
	}
	Fprint(out, s)
}

func main() { CF1027D(os.Stdin, os.Stdout) }

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1027D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, min, s int
	Fscan(in, &n)
	c := make([]int, n)
	for i := range c {
		Fscan(in, &c[i])
	}
	g := make([]int, n)
	for i := range g {
		Fscan(in, &g[i])
		g[i]--
	}

	vis := make([]int8, n)
	var f func(v int)
	f = func(v int) {
		if vis[v] == 2 || vis[v] == 0 && vis[g[v]] == 2 {
			return
		}
		vis[v]++
		if vis[v] == 2 && c[v] < min {
			min = c[v]
		}
		f(g[v])
	}
	for i, c := range vis {
		if c == 0 {
			min = 1e9
			f(i)
			if min < 1e9 {
				s += min
			}
		}
	}
	Fprint(out, s)
}

func main() { CF1027D(os.Stdin, os.Stdout) }


There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.

Print the minimum number of operations required to change balance in each bank to zero.

NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer:   transfer 1 from the first bank to the second bank;  transfer 3 from the second bank to the third;  transfer 6 from the third bank to the fourth.

package main

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

var _r = bufio.NewReader(os.Stdin)
// var _w = bufio.NewWriter(os.Stdout)

func main() {
	var n int32
	var sum int64
	var cnt map[int64]int32 = make(map[int64]int32)
	// else nil

	fmt.Scan(&n)
	var ans int32 = n - 1
	for i := int32(0); i < n; i++ {
		var x int
		_, _ = fmt.Fscan(_r, &x)
		sum += int64(x)
		cnt[sum]++
		ans = min(ans, n-cnt[sum])
	}
	fmt.Println(ans)
}

var min func(...int32) int32 = func(z ...int32) int32 {
	var ans int32 = math.MaxInt32
	for _, v := range z {
		if v < ans {
			ans = v
		}
	}
	return ans
}


Gianni, SWERC's chief judge, received a huge amount of high quality problems from the judges and now he has to choose a problem set for SWERC.He received $$$n$$$ problems and he assigned a beauty score and a difficulty to each of them. The $$$i$$$-th problem has beauty score equal to $$$b_i$$$ and difficulty equal to $$$d_i$$$. The beauty and the difficulty are integers between $$$1$$$ and $$$10$$$. If there are no problems with a certain difficulty (the possible difficulties are $$$1,2,\dots,10$$$) then Gianni will ask for more problems to the judges.Otherwise, for each difficulty between $$$1$$$ and $$$10$$$, he will put in the problem set one of the most beautiful problems with such difficulty (so the problem set will contain exactly $$$10$$$ problems with distinct difficulties). You shall compute the total beauty of the problem set, that is the sum of the beauty scores of the problems chosen by Gianni.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 100$$$) — the number of test cases. The descriptions of the $$$t$$$ test cases follow. The first line of each test case contains the integer $$$n$$$ ($$$1\le n\le 100$$$) — how many problems Gianni received from the judges. The next $$$n$$$ lines contain two integers each. The $$$i$$$-th of such lines contains $$$b_i$$$ and $$$d_i$$$ ($$$1\le b_i, d_i\le 10$$$) — the beauty score and the difficulty of the $$$i$$$-th problem.

For each test case, print the total beauty of the problem set chosen by Gianni. If Gianni cannot create a problem set (because there are no problems with a certain difficulty) print the string MOREPROBLEMS (all letters are uppercase, there are no spaces).

NoteIn the first test case, Gianni has received only $$$3$$$ problems, with difficulties $$$3, 4, 7$$$ which are not sufficient to create a problem set (for example because there is not a problem with difficulty $$$1$$$).In the second test case, Gianni will create a problem set by taking the problems $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$9$$$, $$$10$$$, $$$11$$$ (which have beauty equal to $$$10$$$ and all difficulties from $$$1$$$ to $$$9$$$) and one of the problems $$$1$$$ and $$$6$$$ (which have both beauty $$$3$$$ and difficulty $$$10$$$). The total beauty of the resulting problem set is $$$10\cdot 9 + 3 = 93$$$.

package main

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

var in, out = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func solve() {
	var n int
	fmt.Fscan(in, &n)
	c := make([]float64, 10)
	for i := range c {
		c[i] = -1
	}
	for i := 0; i < n; i++ {
		var b float64
		var d int
		fmt.Fscan(in, &b)
		fmt.Fscan(in, &d)
		d--
		c[d] = math.Max(c[d], b)
	}
	sum := float64(0)
	for _, i := range c {
		if i == -1 {
			fmt.Fprintf(out,"MOREPROBLEMS\n")
			return
		}
		sum += i
	}
	fmt.Fprintf(out,"%d\n",int(sum))
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscan(in, &t); t > 0; t-- {
		solve()
	}
}

package main

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

var in, out = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func solve() {
	var n int
	fmt.Fscan(in, &n)
	c := make([]float64, 10)
	for i := range c {
		c[i] = -1
	}
	for i := 0; i < n; i++ {
		var b float64
		var d int
		fmt.Fscan(in, &b)
		fmt.Fscan(in, &d)
		d--
		c[d] = math.Max(c[d], b)
	}
	sum := float64(0)
	for _, i := range c {
		if i == -1 {
			fmt.Fprintf(out,"MOREPROBLEMS\n")
			return
		}
		sum += i
	}
	fmt.Fprintf(out,"%d\n",sum)
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscan(in, &t); t > 0; t-- {
		solve()
	}
}

package main

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

var in, out = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func solve() {
	var n int
	fmt.Fscan(in, &n)
	c := make([]float64, 10)
	for i := range c {
		c[i] = -1
	}
	for i := 0; i < n; i++ {
		var b float64
		var d int
		fmt.Fscan(in, &b)
		fmt.Fscan(in, &d)
		d--
		c[d] = math.Max(c[d], b)
	}
	sum := float64(0)
	for _, i := range c {
		if i == -1 {
			print("MOREPROBLEMS\n")
			return
		}
		sum += i
	}
	print(int(sum), "\n")
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscan(in, &t); t > 0; t-- {
		solve()
	}
}

package main

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

var in = bufio.NewReader(os.Stdin)

func solve() {
	var n int
	fmt.Fscan(in, &n)
	c := make([]float64, 10)
	for i := range c {
		c[i] = -1
	}
	for i := 0; i < n; i++ {
		var b float64
		var d int
		fmt.Fscan(in, &b, &d)
		d--
		c[d] = math.Max(c[d], b)
	}
	sum := float64(0)
	for _, i := range c {
		if i == -1 {
			print("MOREPROBLEMS\n")
			return
		}
		sum += i
	}
	print(int(sum), "\n")
}

func main() {
	var t int
	for fmt.Fscan(in, &t); t > 0; t-- {
		solve()
	}
}

package main

import (
	. "fmt"
	"math"
)

func solve() {
	var n int
	Scan(&n)
	c := make([]float64, 10)
	for i := range c {
		c[i] = -1
	}
	for i := 0; i < n; i++ {
		var b float64
		var d int
		Scan(&b, &d)
		d--
		c[d] = math.Max(c[d], b)
	}
	sum := float64(0)
	for _, i := range c {
		if i == -1 {
			print("MOREPROBLEMS\n")
			return
		}
		sum += i
	}
	print(int(sum), "\n")
}

func main() {
	var t int
	for Scan(&t); t > 0; t-- {
		solve()
	}
}

package main

import (
	. "fmt"
	"math"
)

func solve() {
	var n int
	Scan(&n)
	c := make([]float64, 10)
	for i := range c {
		c[i] = -1
	}
	for i := 0; i < n; i++ {
		var b float64
		var d int
		Scan(&b, &d)
		d--
		c[d] = math.Max(c[d], b)
	}
	sum := float64(0)
	for _, i := range c {
		if i == -1 {
			print("MOREPROBLEMS\n")
			return
		}
		sum += i
	}
	print(int(sum))
}

func main() {
	var t int
	for Scan(&t); t > 0; t-- {
		solve()
	}
}

package main

import (
	. "fmt"
	"math"
)

func solve() {
	var n int
	c := make([]float64, 11)
	for i := range c {
		c[i] = -1
	}
	for i := 0; i < n; i++ {
		var b float64
		var d int
		Scan(&b, &d)
		c[d] = math.Max(c[d], b)
	}
	sum := 0
	for i := range c {
		if i == -1 {
			print("MOREPROBLEMS\n")
			return
		}
		sum += i
	}
	print(sum)
}

func main() {
	var t int
	for Scan(&t); t > 0; t-- {
		solve()
	}
}


Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $$$k$$$-th layer of the triangle contains $$$k$$$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $$$(r, c)$$$ ($$$1 \le c \le r$$$), where $$$r$$$ is the number of the layer, and $$$c$$$ is the number of the point in the layer. From each point $$$(r, c)$$$ there are two directed edges to the points $$$(r+1, c)$$$ and $$$(r+1, c+1)$$$, but only one of the edges is activated. If $$$r + c$$$ is even, then the edge to the point $$$(r+1, c)$$$ is activated, otherwise the edge to the point $$$(r+1, c+1)$$$ is activated. Look at the picture for a better understanding.  Activated edges are colored in black. Non-activated edges are colored in gray. From the point $$$(r_1, c_1)$$$ it is possible to reach the point $$$(r_2, c_2)$$$, if there is a path between them only from activated edges. For example, in the picture above, there is a path from $$$(1, 1)$$$ to $$$(3, 2)$$$, but there is no path from $$$(2, 1)$$$ to $$$(1, 1)$$$.Initially, you are at the point $$$(1, 1)$$$. For each turn, you can:   Replace activated edge for point $$$(r, c)$$$. That is if the edge to the point $$$(r+1, c)$$$ is activated, then instead of it, the edge to the point $$$(r+1, c+1)$$$ becomes activated, otherwise if the edge to the point $$$(r+1, c+1)$$$, then instead if it, the edge to the point $$$(r+1, c)$$$ becomes activated. This action increases the cost of the path by $$$1$$$;  Move from the current point to another by following the activated edge. This action does not increase the cost of the path. You are given a sequence of $$$n$$$ points of an infinite triangle $$$(r_1, c_1), (r_2, c_2), \ldots, (r_n, c_n)$$$. Find the minimum cost path from $$$(1, 1)$$$, passing through all $$$n$$$ points in arbitrary order.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) is the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) is the number of points to visit. The second line contains $$$n$$$ numbers $$$r_1, r_2, \ldots, r_n$$$ ($$$1 \le r_i \le 10^9$$$), where $$$r_i$$$ is the number of the layer in which $$$i$$$-th point is located. The third line contains $$$n$$$ numbers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le r_i$$$), where $$$c_i$$$ is the number of the $$$i$$$-th point in the $$$r_i$$$ layer. It is guaranteed that all $$$n$$$ points are distinct. It is guaranteed that there is always at least one way to traverse all $$$n$$$ points. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output the minimum cost of a path passing through all points in the corresponding test case.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		rs := make([]int, n)
		cs := make([]int, n)
		for i := range rs {
			fmt.Fscan(in, &rs[i])
			rs[i]--
		}
		for i := range cs {
			fmt.Fscan(in, &cs[i])
			cs[i]--
		}
		sort.Ints(rs)
		sort.Ints(cs)
		calc := func(r, c int) int64 {
			if r == c {
				return int64(r)
			}
			if c == r-1 {
				return 0
			}
			sr := c + 1
			return int64((r - sr + 1) / 2)
		}
		cost := calc(rs[0], cs[0])
		for i := 1; i<n; i++ {
			if rs[i] == cs[i] {
				cost += calc(rs[i], cs[i]) - calc(rs[i-1], cs[i-1])
				continue
			}
			sr := rs[i-1]+cs[i]-cs[i-1]
			if sr == cs[i] {
				sr++
			}
			if (sr+cs[i])%2 == 0 {
				cost += int64((rs[i] - sr) / 2)
			}else {
				cost += int64((rs[i] - sr + 1)/2)
			}
			if (sr+cs[i])%2 == 0 && sr == rs[i] {
				cost+= int64(cs[i] - cs[i-1])
			}
		}
		fmt.Println(cost)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	_i, buf := 1<<12, make([]byte, 1<<12)
	rc := func() byte {
		if _i == 1<<12 {
			os.Stdin.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	type pair struct{ r, c int }
	for T := r(); T > 0; T-- {
		n := r()
		a := make([]pair, n, n+1)
		for i := range a {
			a[i].r = r()
		}
		for i := range a {
			a[i].c = r()
		}
		a = append(a, pair{1, 1})
		sort.Slice(a, func(i, j int) bool { return a[i].r < a[j].r })
		s := 0
		for i, p := range a[:n] {
			if d := a[i+1].r - a[i+1].c - (p.r-p.c)>>1<<1; d > 1 {
				s += d >> 1
			} else if d == 0 {
				s += a[i+1].r - p.r
			}
		}
		Fprintln(out, s)
	}
}

package main
import (
	"bufio"
	. "fmt"
	"os"
	"sort"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	type pair struct{ r, c int }
	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]pair, n, n+1)
		for i := range a {
			Fscan(in, &a[i].r)
		}
		for i := range a {
			Fscan(in, &a[i].c)
		}
		a = append(a, pair{1, 1})
		sort.Slice(a, func(i, j int) bool { return a[i].r < a[j].r })
		s := 0
		for i, p := range a[:n] {
			if d := a[i+1].r - a[i+1].c - (p.r-p.c)/2*2; d > 1 {
				s += d / 2
			} else if d == 0 {
				s += a[i+1].r - p.r
			}
		}
		Println(s)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1506F(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ r, c int }

	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]pair, n, n+1)
		for i := range a {
			Fscan(in, &a[i].r)
		}
		for i := range a {
			Fscan(in, &a[i].c)
		}
		a = append(a, pair{1, 1})
		sort.Slice(a, func(i, j int) bool { return a[i].r < a[j].r })
		s := 0
		for i, p := range a[:n] {
			rc := p.r - p.c
			if d := a[i+1].r - a[i+1].c - rc; d+rc&1 > 1 {
				s += (d + rc&1) / 2
			} else if d == 0 && rc&1 == 0 {
				s += a[i+1].r - p.r
			}
		}
		Fprintln(out, s)
	}
}

func main() { CF1506F(os.Stdin, os.Stdout) }

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		rs := make([]int, n)
		cs := make([]int, n)
		for i := range rs {
			fmt.Fscan(in, &rs[i])
			rs[i]--
		}
		for i := range cs {
			fmt.Fscan(in, &cs[i])
			cs[i]--
		}
		sort.Ints(rs)
		sort.Ints(cs)
		calc := func(r, c int) int64 {
			if r == c {
				return int64(r)
			}
			if c == r-1 {
				return 0
			}
			sr := c + 1
			return int64((r - sr + 1) / 2)
		}
		cost := calc(rs[0], cs[0])
		for i := 1; i<n; i++ {
			if rs[i] == cs[i] {
				cost += calc(rs[i], cs[i]) - calc(rs[i-1], cs[i-1])
				continue
			}
			sr := rs[i-1]+cs[i]-cs[i-1]
			if sr == cs[i] {
				sr++
			}
			if (sr+cs[i])%2 == 0 {
				cost += int64((rs[i] - sr) / 2)
			}else {
				cost += int64((rs[i] - sr + 1)/2)
			}
			if (sr+cs[i])%2 == 0 && sr == rs[i] {
				cost++
			}
		}
		fmt.Println(cost)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		rs := make([]int, n)
		cs := make([]int, n)
		for i := range rs {
			fmt.Fscan(in, &rs[i])
			rs[i]--
		}
		for i := range rs {
			fmt.Fscan(in, &cs[i])
			cs[i]--
		}
		calc := func(r, c int) int64 {
			if r == c {
				return int64(r)
			}
			if c == r-1 {
				return 0
			}
			sr := c + 1
			return int64((r - sr + 1) / 2)
		}
		cost := calc(rs[0], cs[0])
		for i := 1; i<n; i++ {
			if rs[i] == cs[i] {
				cost += calc(rs[i], cs[i]) - calc(rs[i-1], cs[i-1])
				continue
			}
			sr := rs[i-1]+cs[i]-cs[i-1]
			if sr == cs[i] {
				sr++
			}
			cost += calc(rs[i], cs[i])
			cost -= calc(sr, cs[i])
		}
		fmt.Println(cost)
	}
}


Consider a sequence of integers $$$a_1, a_2, \ldots, a_n$$$. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by $$$1$$$ position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases by $$$1$$$. The indices of the elements after the move are recalculated.E. g. let the sequence be $$$a=[3, 2, 2, 1, 5]$$$. Let's select the element $$$a_3=2$$$ in a move. Then after the move the sequence will be equal to $$$a=[3, 2, 1, 5]$$$, so the $$$3$$$-rd element of the new sequence will be $$$a_3=1$$$ and the $$$4$$$-th element will be $$$a_4=5$$$.You are given a sequence $$$a_1, a_2, \ldots, a_n$$$ and a number $$$k$$$. You need to find the minimum number of moves you have to make so that in the resulting sequence there will be at least $$$k$$$ elements that are equal to their indices, i. e. the resulting sequence $$$b_1, b_2, \ldots, b_m$$$ will contain at least $$$k$$$ indices $$$i$$$ such that $$$b_i = i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two consecutive lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$). The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$). The numbers in the sequence are not necessarily different. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$.

For each test case output in a single line:   $$$-1$$$ if there's no desired move sequence;  otherwise, the integer $$$x$$$ ($$$0 \le x \le n$$$) — the minimum number of the moves to be made so that the resulting sequence will contain at least $$$k$$$ elements that are equal to their indices.

NoteIn the first test case the sequence doesn't satisfy the desired condition, but it can be provided by deleting the first element, hence the sequence will be $$$[1, 2, 3, 4, 5, 6]$$$ and $$$6$$$ elements will be equal to their indices.In the second test case there are two ways to get the desired result in $$$2$$$ moves: the first one is to delete the $$$1$$$-st and the $$$3$$$-rd elements so that the sequence will be $$$[1, 2, 3]$$$ and have $$$3$$$ elements equal to their indices; the second way is to delete the $$$2$$$-nd and the $$$3$$$-rd elements to get the sequence $$$[5, 2, 3]$$$ with $$$2$$$ desired elements.

package main

import (
	"bufio"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	solve := func(Case int) {
		var n, k int
		Fscan(in, &n, &k)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
			a[i]--
		}

		dp := make([][]int, n+1)
		for i := range dp {
			dp[i] = make([]int, n+1)
		}

		for i, v := range a {
			for j := 0; j <= i; j++ {
				if v == i-j {
					dp[i+1][j] = max(dp[i+1][j], dp[i][j]+1)
				} else {
					dp[i+1][j] = max(dp[i+1][j], dp[i][j])
				}
				dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j])
			}
		}

		for i, dv := range dp[n] {
			if dv >= k {
				Fprintln(out, i)
				return
			}
		}
		Fprintln(out, -1)
	}

	T := 1
	Fscan(in, &T)
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}
func main()  { run(os.Stdin, os.Stdout) }
func  max(a, b int) int {
	if a > b {
		return a
	}
	return b
}