package main

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

const (
	MAX_N      = 10000
	MAX_WEIGHT = 100000
)

type Edge struct {
	start  int
	end    int
	weight int
}

type ShortestInfo struct {
	edges    []Edge
	shortest int
}

func main() {
	doMain(os.Stdin)
}

func doMain(reader io.Reader) {
	sc := bufio.NewScanner(reader)
	sc.Split(bufio.ScanWords)

	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}

	shortestList := make([]ShortestInfo, n)
	for i := 1; i < n; i++ {
		shortestList[i] = ShortestInfo{edges: []Edge{}, shortest: MAX_N*MAX_WEIGHT + 1}
	}

	adjacentMatrix, err := createAdjacentMatrix(n, sc)
	if err != nil {
		panic(err)
	}

	sssp([]int{0}, shortestList, adjacentMatrix)
	for _, v := range shortestList {
		fmt.Println(v.getEnd(), v.shortest)
	}
}

func (si ShortestInfo) getEnd() int {
	if len(si.edges) == 0 {
		return 0
	} else {
		return si.edges[len(si.edges)-1].end
	}
}

func createAdjacentMatrix(n int, sc *bufio.Scanner) ([][]int, error) {
	adjacentMatrix := make([][]int, n)
	for i := 0; i < n; i++ {
		id, err := nextInt(sc)
		if err != nil {
			return nil, err
		}
		adjacentMatrix[id] = make([]int, n)
		for j := 0; j < n; j++ {
			adjacentMatrix[id][j] = -1
		}
		vertexNum, err := nextInt(sc)
		if err != nil {
			return nil, err
		}
		for j := 0; j < vertexNum; j++ {
			v, err := nextInt(sc)
			if err != nil {
				return nil, err
			}
			c, err := nextInt(sc)
			if err != nil {
				return nil, err
			}
			adjacentMatrix[id][v] = c
		}
	}
	return adjacentMatrix, nil
}

func sssp(nodeStack []int, shortestList []ShortestInfo, adjacentMatrix [][]int) {
	for len(nodeStack) > 0 {
		currentNode := nodeStack[0]
		nodeStack = nodeStack[1:]
		currentShortest := getShortest(currentNode, shortestList)
		adjacents := findAdjacents(currentNode, adjacentMatrix)
		for i := 0; i < len(adjacents); i++ {
			adj := adjacents[i]
			if currentShortest.shortest+adj.weight < getShortest(adj.end, shortestList).shortest {
				setShortest(adj.end, adj, currentShortest, shortestList)
				nodeStack = append(nodeStack, adj.end)
			}
		}
	}
}

func getShortest(node int, shortestList []ShortestInfo) ShortestInfo {
	return shortestList[node]
}

func setShortest(node int, edge Edge, currentShortest ShortestInfo, shortestList []ShortestInfo) {
	newEdges := make([]Edge, len(currentShortest.edges)+1)
	for i := 0; i < len(newEdges)-1; i++ {
		newEdges[i] = currentShortest.edges[i]
	}
	newEdges[len(newEdges)-1] = edge
	shortestInfo := ShortestInfo{edges: newEdges, shortest: currentShortest.shortest + edge.weight}
	shortestList[node] = shortestInfo
}

func findAdjacents(currentNode int, adjacentMatrix [][]int) []Edge {
	adjacents := adjacentMatrix[currentNode]
	edges := []Edge{}
	for i, v := range adjacents {
		if v >= 0 {
			edges = append(edges, Edge{start: currentNode, end: i, weight: v})
		}
	}
	return edges
}

func nextInt(sc *bufio.Scanner) (int, error) {
	sc.Scan()
	return strconv.Atoi(sc.Text())
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Single Source Shortest Path II

For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format:

$u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$

Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$).

Output

For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 10,000$

$0 \leq c_i \leq 100,000$

$|E| < 500,000$

All vertices are reachable from vertex $0$

Sample Input 1

5
0 3 2 3 3 1 1 2
1 2 0 2 3 4
2 3 0 3 3 1 4 1
3 4 2 1 0 1 1 4 4 3
4 2 2 1 3 3

Sample Output 1

0 0
1 2
2 2
3 1
4 3

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


package main

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

var sc = bufio.NewScanner(os.Stdin)

func search(in [16]byte) int {
	for i := 0; i < 16; i++ {
		if in[i] == byte(0) {
			return i
		}
	}
	panic("not found 0")
}

func up(in [16]byte) (bool, [16]byte) {
	pos := search(in)
	if pos > 3 {
		in[pos], in[pos-4] = in[pos-4], in[pos]

	} else {
		return false, in
	}
	return true, in

}

func down(in [16]byte) (bool, [16]byte) {
	pos := search(in)
	if pos < 12 {
		in[pos], in[pos+4] = in[pos+4], in[pos]
	} else {
		return false, in

	}
	return true, in

}

func left(in [16]byte) (bool, [16]byte) {
	pos := search(in)
	// mod(pos, 4) == 0
	if pos != 0 && pos != 4 && pos != 8 && pos != 12 {
		in[pos], in[pos-1] = in[pos-1], in[pos]
	} else {
		return false, in
	}
	return true, in

}
func right(in [16]byte) (bool, [16]byte) {
	pos := search(in)
	// mod(pos, 4) == 3
	if pos != 3 && pos != 7 && pos != 11 && pos != 15 {
		in[pos], in[pos+1] = in[pos+1], in[pos]
	} else {
		return false, in

	}
	return true, in

}

func next() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i

}

var goal = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}

func pp(s [16]byte) {

	for i := 0; i < 4; i++ {
		fmt.Printf("%2d %2d %2d %2d\n", s[0+4*i], s[1+4*i], s[2+4*i], s[3+4*i])
	}
	fmt.Println("----------------------")

}

func dls(limit int, now int, state [16]byte, parents map[[16]byte]bool) bool {

	if parents[state] {
		return false
	}

	if now == limit+1 {
		return false

	}

	if state == goal {
		return true
	}

	parents[state] = true

	ok, ur := up(state)
	if ok {
		if dls(limit, now+1, ur, parents) {
			return true

		}
	}
	ok, dr := down(state)
	if ok {
		if dls(limit, now+1, dr, parents) {
			return true

		}
	}
	ok, lr := left(state)
	if ok {
		if dls(limit, now+1, lr, parents) {
			return true
		}
	}
	ok, rr := right(state)
	if ok {
		if dls(limit, now+1, rr, parents) {
			return true
		}
	}

	return false

}

func main() {
	sc.Split(bufio.ScanWords)
	var state [16]byte
	for i := 0; i < 16; i++ {
		state[i] = byte(next())
	}
	for i := 0; i < 45; i++ {
		if dls(i, 0, state, map[[16]byte]bool{}) {
			fmt.Println(i)
			return
		}
	}
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

15 Puzzle

The goal of the 15 puzzle problem is to complete pieces on $4 \times 4$ cells where one of the cells is empty space.

In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 15 as shown below.

1 2 3 4
6 7 8 0
5 10 11 12
9 13 14 15

You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0

Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.

Input

The $4 \times 4$ integers denoting the pieces or space are given.

Output

Print the fewest steps in a line.

Constraints

The given puzzle is solvable in at most 45 steps.

Sample Input

1 2 3 4
6 7 8 0
5 10 11 12
9 13 14 15

Sample Output

8


package main

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

var up=[2]int{-1,0}
var down=[2]int{1,0}
var left=[2]int{0,-1}
var right=[2]int{0,1}

const size int =4

const UP int =0
const DOWN int =2
const LEFT int =1
const RIGHT int =3

var targetPoints [size*size][2]int

var movesHistory [100000]int
var ans=0
var tState =[][]int {//aim state
{1 ,2 ,3 ,4 } ,
{5 ,6 ,7 ,8 } ,
{9 ,10,11,12} ,
{13,14,15,0 }}
var STEP_SUM=0
var sState [][]int  //Init state
var blank_row,blank_column int
func main(){
	var in = bufio.NewReader(os.Stdin)
	var out = bufio.NewWriter(os.Stdout)
	sState=make([][]int,size)
	for i,_ := range sState {
		sState[i]=make([]int,size)
	}
	for i := 0; i < size; i++ {
		fmt.Fscanf(in, "%d %d %d %d\n", &sState[i][0], &sState[i][1],&sState[i][2],&sState[i][3])
	}
	getPoint()
	j:=getHeuristic(sState)
	i:=-1
	for ans = j; ; ans++ {
		if solve(sState,blank_row,blank_column,0,i,j) {
			break
		}
	}
	for k:=0;k<ans;k++ {
		move(sState, movesHistory[k])
	}
	fmt.Fprintln(out,STEP_SUM)
	out.Flush()
}
func getPoint(){
	for i:=0;i<size;i++ {
		for j:=0;j<size;j++ {
			if sState[i][j] == 0 {
				blank_row = i;
				blank_column = j;
				break;
			}
		}
	}
	for i:=0;i<size;i++ { //get aim coordinate
		for j:=0;j<size;j++ {
			targetPoints[tState[i][j]][0] = i; //y-coordinate
			targetPoints[tState[i][j]][1] = j; //x-coordinate
		}
	}
}
func getHeuristic(state [][]int) int {
	heuristic := 0;
	for i:=0;i<len(state);i++ {
			for j:=0;j<len(state[i]);j++ {
				if state[i][j] != 0 {
					heuristic = heuristic +	int(math.Abs(float64(targetPoints[state[i][j]][0] - i))+math.Abs(float64(targetPoints[state[i][j]][1] - j)))
				}
			}
	}
	return heuristic;
}

func solve(state [][]int, blank_row, blank_column, dep, d, h int) bool{
	//compare with aim matrix, check same or not, if same mean it's solved.
	isSolved := true
	for i:=0;i<size;i++ {
		for j:=0;j<size;j++ {
			if state[i][j] != tState[i][j] {
				isSolved = false
			}
		}
	}
	if isSolved {
		return true
	}
	if dep == ans {
		return false
	}
	//For express "blank" moved coordinate location
	blank_row1:= blank_row
	blank_column1:= blank_column
	state2 := make([][]int,size)
	for i,_ := range state2 {
		state2[i]=make([]int,size)
	}
	for direction:=0;direction<4;direction++ {
		for i:=0;i<len(state);i++ {
			for j:=0;j<len(state);j++ {
				state2[i][j] = state[i][j]
			}
		}
		//if backtrace same with last time. end this situation.
		if direction != d && (d%2 == direction%2) {
			continue
		}

		if direction == UP {
			blank_row1 = blank_row + up[0]
			blank_column1 = blank_column + up[1]
		} else if direction == DOWN {
			blank_row1 = blank_row + down[0]
			blank_column1 = blank_column + down[1]
		} else if direction == LEFT {
			blank_row1 = blank_row + left[0]
			blank_column1 = blank_column + left[1]
		} else {
			blank_row1 = blank_row + right[0]
			blank_column1 = blank_column + right[1]
		}

		//check the edge
		if blank_column1 < 0 || blank_column1 == size|| blank_row1 < 0 || blank_row1 == size {
			continue
		}

		//swap blank and right now moved locate coordinate
		state2[blank_row][blank_column] = state2[blank_row1][blank_column1]
		state2[blank_row1][blank_column1] = 0
		var h1 int
		//check the blank whether close the aim coordinate
		if direction == DOWN && blank_row1> targetPoints[state[blank_row1][blank_column1]][0] {
			h1 = h - 1
		} else if direction == UP && blank_row1< targetPoints[state[blank_row1][blank_column1]][0] {
			h1 = h - 1
		} else if direction == RIGHT && blank_column1> targetPoints[state[blank_row1][blank_column1]][1] {
			h1 = h - 1
		} else if direction == LEFT && blank_column1< targetPoints[state[blank_row1][blank_column1]][1] {
			h1 = h - 1
		} else {
			//bad situation make the step bigger.
			h1 = h + 1
		}
		if h1+dep+1>ans { //pruning
			continue
		}
		movesHistory[dep] = direction

		if solve(state2, blank_row1, blank_column1, dep+1, direction, h1) {
			return true
		}
		}
	return false
}
func move(state [][]int,direction int)  {
	row := 0
	column := 0
	for i:=0;i<len(state);i++ {
		for j:=0;j<len(state);j++ {
			if state[i][j] == 0 {
				row = i
				column = j
			}
		}
	}
	switch direction {
		case UP:
			state[row][column] = state[row-1][column]
			state[row-1][column] = 0
			break
		case DOWN:
			state[row][column] = state[row+1][column]
			state[row+1][column] = 0
			break
		case LEFT:
			state[row][column] = state[row][column-1]
			state[row][column-1] = 0
			break
		case RIGHT:
			state[row][column] = state[row][column+1]
			state[row][column+1] = 0
			break
	}
	STEP_SUM++
}


package main

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

func toInt(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return n
}

type Process struct {
	name string
	time int
}

type Queue struct {
	ps    []*Process
	start int
	end   int
	len   int
}

func (q *Queue) enq(p *Process) {
	if q.len == len(q.ps) {
		panic("")
	}
	if q.end == len(q.ps) {
		q.ps[0] = p
		q.end = 0
	} else {
		q.ps[q.end] = p
	}
	q.end++
	q.len++
}

func (q *Queue) deq() *Process {
	if q.len == 0 {
		panic("")
	}
	result := q.ps[q.start]
	if q.start == len(q.ps)-1 {
		q.start = 0
	} else {
		q.start++
	}
	q.len--
	return result
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanLines)
	sc.Scan()
	in := strings.Split(sc.Text(), " ")
	n := toInt(in[0])
	q := toInt(in[1])

	l := make([]*Process, n)
	queue := Queue{ps: l}
	for i := 0; i < n; i++ {
		sc.Scan()
		p := strings.Split(sc.Text(), " ")
		queue.enq(&Process{name: p[0], time: toInt(p[1])})
	}

	total := 0
	for queue.len > 0 {
		p := queue.deq()
		if p.time > q {
			total = total + q
			p.time = p.time - q
			queue.enq(p)
		} else {
			total = total + p.time
			fmt.Printf("%s %d\n", p.name, total)
		}
	}
}

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C


package main

import "fmt"

func main() {
	var N, Q int
	fmt.Scan(&N)
	S := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scan(&S[i])
	}
	fmt.Scan(&Q)
	T := make([]int, Q)
	for i := 0; i < Q; i++ {
		fmt.Scan(&T[i])
	}
	var count int
	for _, t := range T {
		for _, s := range S {
			if t == s {
				count++
				break
			}
		}
	}
	fmt.Println(count)
}

Search I

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

n ≤ 10000

q ≤ 500

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
3 1 2
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


package main

/*
パーティション
*/

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

func partitionString(a []int, base int) string {
	var buf bytes.Buffer
	sep := ""
	for i, v := range a {
		if i == base {
			buf.WriteString(fmt.Sprintf("%s[%d]", sep, v))
		} else {
			buf.WriteString(fmt.Sprintf("%s%d", sep, v))
		}
		sep = " "
	}
	return buf.String()
}

func partition(a []int) ([]int, int) {
	x := a[len(a)-1]
	i := -1
	for j := 0; j < len(a)-1; j++ {
		if a[j] <= x {
			i++
			a[i], a[j] = a[j], a[i]
		}
	}
	a[len(a)-1], a[i+1] = a[i+1], a[len(a)-1]
	return a, i + 1
}

func main() {
	scanner := makeScanner(100000 * 100000)
	eGetInt(scanner)
	s := eGetInts(scanner)
	s, idx := partition(s)
	fmt.Println(partitionString(s, idx))
}

////////////////////////////////////////////////////////////////////////////////
// ライブラリ
////////////////////////////////////////////////////////////////////////////////
func makeScanner(max int) *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]uint8, 0, 8192), max)
	return scanner
}
func eGetLine(r *bufio.Scanner) string {
	if r.Scan() {
		return r.Text()
	}
	err := r.Err()
	if err != nil {
		log.Fatal(err)
	}
	// EOF
	return ""
}
func eGetInt(r *bufio.Scanner) int {
	line := eGetLine(r)
	return eAtoi(line)
}
func eGetFields(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Fields(line)
}
func eGetInts(r *bufio.Scanner) []int {
	fields := eGetFields(r)
	var ints []int
	for _, f := range fields {
		ints = append(ints, eAtoi(f))
	}
	return ints
}
func eGetChars(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Split(line, "")
}
func eAtoi(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil {
		log.Fatal(err)
	}
	return n
}

type ints []int

func (s ints) String() string {
	var buf bytes.Buffer
	sep := ""
	for _, v := range s {
		buf.WriteString(fmt.Sprintf("%s%d", sep, v))
		sep = " "
	}
	return buf.String()
}

func reverse(a ints) ints {
	r := make(ints, len(a))
	for i := 0; i < len(a); i++ {
		r[i] = a[len(a)-1-i]
	}
	return r
}
func max(a ints) (int, bool) {
	if len(a) == 0 {
		return 0, false
	}
	m := a[0]
	for _, e := range a {
		if e > m {
			m = e
		}
	}
	return m, true
}
func sum(a ints) int {
	if len(a) == 0 {
		return 0
	}
	sum := 0
	for _, e := range a {
		sum += e
	}
	return sum
}

Partition

Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.

In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).

Your task is to read a sequence A and perform the Partition based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].

Input

The first line of the input includes an integer n, the number of elements in the sequence A.

In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [  ].

Constraints

1 ≤ n ≤ 100,000

0 ≤ Ai ≤ 100,000

Sample Input 1

12
13 19 9 5 12 8 7 4 21 2 6 11

Sample Output 1

9 5 8 7 4 2 6 [11] 21 13 19 12


// AOJ ALDS1_9_B: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_B

package main

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

type maxHeap struct {
	heap []int
	size int
}

func nextInt(sc *bufio.Scanner) int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

func (mh maxHeap) buildMaxHeap() {
	for i := mh.size / 2; i >= 1; i-- {
		mh.maxHeapify(i)
	}
}

func (mh maxHeap) maxHeapify(i int) {
	l := mh.left(i)
	r := mh.right(i)

	// 自分、左の子、右の子で値が最大のnodeを選ぶ
	largest := i
	if l <= mh.size && mh.heap[l] > mh.heap[i] {
		largest = l
	}

	if r <= mh.size && mh.heap[r] > mh.heap[largest] {
		largest = r
	}

	// iの子のほうが値が大きい場合
	if i != largest {
		mh.heap[i], mh.heap[largest] = mh.heap[largest], mh.heap[i]
		mh.maxHeapify(largest) // 再帰的に呼び出し
	}
}

func (mh maxHeap) left(i int) int {
	return 2 * i
}

func (mh maxHeap) right(i int) int {
	return 2*i + 1
}

func (mh maxHeap) printHeap() {
	buf := bufio.NewWriter(os.Stdout)
	for i := 1; i < mh.size+1; i++ {
		buf.Write([]byte(fmt.Sprintf(" %d", mh.heap[i])))
	}
	buf.Write([]byte("\n"))
	buf.Flush()
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	h := nextInt(sc)

	mh := maxHeap{make([]int, h+1), h}

	for i := 1; i < h+1; i++ {
		mh.heap[i] = nextInt(sc)
	}

	mh.buildMaxHeap()
	mh.printHeap()
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Heap

A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.

Here is an example of a max-heap.

Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.

$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.

1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i　// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively

The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.

1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)

Input

In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).

Output

Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.

Constraint

$1 \leq H \leq 500,000$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

10
4 1 3 2 16 9 10 14 8 7

Sample Output 1

16 14 10 8 7 9 3 2 4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


package main

import "fmt"

const size = 100001

func main() {
    var n, t int
    var l, r int
    var mem [size]int
    fmt.Scan(&n)
    fmt.Scan(&t)
    for i := 0; i < n; i++ {
        fmt.Scan(&l)
        fmt.Scan(&r)
        mem[l] += 1
        mem[r] -= 1
    }
    ans := mem[0]
    for i := 1; i < t + 1; i++ {
        mem[i] += mem[i - 1]
        if ans < mem[i] {
            ans = mem[i]
        }
    }
    fmt.Println(ans)
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

The Maximum Number of Customers

$N$ persons visited a restaurant. The restaurant is open from 0 to $T$. The $i$-th person entered the restaurant at $l_i$ and left at $r_i$. Find the maximum number of persons during the business hours.

Constraints

$ 1 \leq N \leq 10^5 $

$ 1 \leq T \leq 10^5 $

$ 0 \leq l_i < r_i \leq T $

Input

The input is given in the following format.

$N$ $T$

$l_1$ $r_1$

$l_2$ $r_2$

:

$l_N$ $r_N$

Output

Print the maximum number of persons in a line.

Sample Input 1

6 10
0 2
1 3
2 6
3 8
4 10
5 10

Sample Output 1

4

Sample Input 2

2 2
0 1
1 2

Sample Output 2

1


package main

// http://www.prefield.com/algorithm/graph/tree_diameter.html

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

var infty = 1000000000

var scanner = bufio.NewScanner(os.Stdin)

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

type DirectedGraphNodeID int

func newDirectedGraph(nNodes int) *DirectedGraph {
	graph := DirectedGraph{}

	graph.nodes = make([]*DirectedGraphNode, nNodes)
	for iNode := 0; iNode < nNodes; iNode++ {
		graph.nodes[iNode] = &DirectedGraphNode{
			key:       DirectedGraphNodeID(iNode),
			adjacents: map[DirectedGraphNodeID]*DirectedGraphNode{},
			costs:     map[DirectedGraphNodeID]int{},
			d:         infty,
		}
	}

	return &graph
}

type DirectedGraph struct {
	nodes []*DirectedGraphNode
	time  int
}

func (graph *DirectedGraph) sedAdjacent(leftID, rightID DirectedGraphNodeID, weight int) {
	graph.nodes[leftID].adjacents[rightID] = graph.nodes[rightID]
	graph.nodes[leftID].costs[rightID] = weight
}

type DirectedGraphNode struct {
	key       DirectedGraphNodeID
	adjacents map[DirectedGraphNodeID]*DirectedGraphNode
	costs     map[DirectedGraphNodeID]int

	parent   *DirectedGraphNode
	d, f     int
	visitied bool
	distance int
}

func dfsVisit(graph *DirectedGraph, startNode *DirectedGraphNode) {
	graph.time++
	startNode.d = graph.time
	startNode.visitied = true

	for adjacentID, adjacent := range startNode.adjacents {
		if !adjacent.visitied {
			adjacent.parent = startNode
			adjacent.distance = startNode.distance + startNode.costs[adjacentID]
			dfsVisit(graph, adjacent)
		}
	}
	graph.time++
	startNode.f = graph.time
}

func fillDistances(graph *DirectedGraph, startNode *DirectedGraphNode) {
	for _, node := range graph.nodes {
		node.visitied = false
		node.parent = nil
		node.distance = infty
	}
	graph.time = 0
	startNode.distance = 0
	dfsVisit(graph, startNode)
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

func getFarthestNode(graph *DirectedGraph) *DirectedGraphNode {
	maxDistance := 0
	var nodeMaxDistance *DirectedGraphNode
	for _, node := range graph.nodes {
		if node.distance >= maxDistance {
			maxDistance = node.distance
			nodeMaxDistance = node
		}
	}
	return nodeMaxDistance
}

func main() {
	scanner.Split(bufio.ScanWords)

	nNodes := nextInt()
	graph := newDirectedGraph(nNodes)
	for iNode := 0; iNode < nNodes-1; iNode++ {
		parent := DirectedGraphNodeID(nextInt())
		child := DirectedGraphNodeID(nextInt())
		weight := nextInt()
		graph.sedAdjacent(parent, child, weight)
		graph.sedAdjacent(child, parent, weight)
	}

	fillDistances(graph, graph.nodes[0])
	nodeMaxDistance := getFarthestNode(graph)
	// fmt.Println(nodeMaxDistance)

	fillDistances(graph, nodeMaxDistance)
	nodeMaxDistance = getFarthestNode(graph)
	fmt.Println(nodeMaxDistance.distance)
}

Diameter of a Tree

Given a tree T with non-negative weight, find the diameter of the tree.

The diameter of a tree is the maximum distance between two nodes in a tree.

Input

n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given.

si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output

Print the diameter of the tree in a line.

Constraints

1 ≤ n ≤ 100,000

0 ≤ wi ≤ 1,000

Sample Input 1

4
0 1 2
1 2 1
1 3 3

Sample Output 1

5

Sample Input 2

4
0 1 1
1 2 2
2 3 4

Sample Output 2

7


package main

import (
	"fmt"
	"math"
)

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

	var min float64 = 9999999999
	var max float64 = -9999999999
	var total float64 = 0
	for i := 0; i < n; i++ {
		var a float64
		fmt.Scan(&a)
		max = math.Max(max, a)
		min = math.Min(min, a)
		total += a
	}

	fmt.Println(int(min), int(max), int(total))

}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Min, Max and Sum

Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.

Input

In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in a line.

Output

Print the minimum value, maximum value and sum in a line. Put a single space between the values.

Constraints

$0 < n \leq 10000$

$-1000000 \leq a_i \leq 1000000$

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37


package main

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

func main() {
  //fmt.Print("Input :")
  sc := bufio.NewScanner(os.Stdin)
  sc.Split(bufio.ScanWords)

  var h int
  var w int

  for {
    if sc.Scan() { h, _ = strconv.Atoi(sc.Text()) }
    if sc.Scan() { w, _ = strconv.Atoi(sc.Text()) }

    if h == 0 && w == 0 { break }
    for i := 0; i < h; i++ {
      for j := 0; j < w; j++ {
        fmt.Print("#")
      }
      fmt.Println()
    }
    fmt.Println()
  }
}

Print a Rectangle

Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the rectangle made of H × W '#'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
2 2
0 0

Sample Output

####
####
####

######
######
######
######
######

##
##


package main

import (
	"fmt"
)

func main() {
	var w, h int

	for {
		fmt.Scan(&h, &w)

		if w == 0 && h == 0 {
			break
		}

		for i := 0; i < h; i++ {
			for j := 0; j < w; j++ {
				if (i+j)%2 == 0 {
					fmt.Print("#")
				} else {
					fmt.Print(".")
				}
			}
			fmt.Println()
		}
		fmt.Println()
	}
}

Print a Chessboard

Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.

#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#

Note that the top left corner should be drawn by '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the chessboard made of '#' and '.'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
3 3
2 2
1 1
0 0

Sample Output

#.#.
.#.#
#.#.

#.#.#.
.#.#.#
#.#.#.
.#.#.#
#.#.#.

#.#
.#.
#.#

#.
.#

#


package main
import (
   "fmt"
   "os"
   "bufio"
   "strconv"
)
var sc = bufio.NewScanner(os.Stdin)

func main() {
  sc.Split(bufio.ScanWords)
  n := nextInt()
  m := nextInt()
  l := nextInt()
  vector1 := make([][]int, n)
  for i := 0; i < n; i++ {
    vector1[i] = make([]int, m)
    for j := 0; j < m; j++ {
      vector1[i][j] = nextInt()
	}
  }

  vector2 := make([][]int, m)
  for i := 0; i < m; i++ {
    vector2[i] = make([]int, l)
    for j := 0; j < l; j++ {
      vector2[i][j] = nextInt()
	}
  }

  for i := 0; i < n; i++ {
      for r := 0; r < l; r++ {
		sum := 0
        for q := 0; q < m; q++ {
			  sum = sum +vector1[i][q] * vector2[q][r]
        }
        fmt.Print(sum)
		if r != l - 1{
          fmt.Print(" ")
	    }
      }
      fmt.Println()
  }

}

func getStdin() (string) {
	sc.Scan()
	v := sc.Text()
	return v
}

func nextInt() (int) {
	sc.Scan()
	v, e := strconv.Atoi(sc.Text())
    if e != nil { panic(e) }
    return v
}

func nextFloat() (float64) {
	sc.Scan()
	v, e := strconv.ParseFloat(sc.Text(), 64)
    if e != nil { panic(e) }
    return v
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Matrix Multiplication

Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:

\[
c_{ij} = \sum_{k=1}^m a_{ik}b_{kj}
\]

where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.

Input

In the first line, three integers $n$, $m$ and $l$ are given separated by space characters

In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.

Output

Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.

Constraints

$1 \leq n, m, l \leq 100$

$0 \leq a_{ij}, b_{ij} \leq 10000$

Sample Input

3 2 3
1 2
0 3
4 5
1 2 1
0 3 2

Sample Output

1 8 5
0 9 6
4 23 14

Note

      解説


package main

import (
	"bufio"
	"os"
	"strconv"
	"container/list"
	"fmt"
)

var scanner = bufio.NewScanner(os.Stdin)

func nextInt() int {
	scanner.Scan()
	i,  e := strconv.Atoi(scanner.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	scanner.Split(bufio.ScanWords)
	pointer_list := make([]*list.Element, 0)
	dequeue := list.New()
	q := nextInt()

	for i := 0; i < q; i++ {
		switch nextInt() {
		case 0:
			switch nextInt() {
			case 0:
				// 先頭に挿入
				x := nextInt()
				if len(pointer_list) == 0 {
					pointer_list = append(pointer_list, dequeue.PushFront(x))
					continue
				}
				pointer_list = append(pointer_list[:1], pointer_list[0:]...)
				pointer_list[0] = dequeue.PushFront(x)
				// for tmp := dequeue.Front(); tmp != nil; tmp = tmp.Next() {
				// 	fmt.Printf("%+v\n", tmp.Value)
				// }
			case 1:
				// 末尾に挿入
				x := nextInt()
				pointer_list = append(pointer_list, dequeue.PushBack(x))
				// for tmp := dequeue.Front(); tmp != nil; tmp = tmp.Next() {
				// 	fmt.Printf("%+v\n", tmp.Value)
				// }
			}
		case 1:
			p := nextInt()
			fmt.Println(pointer_list[p].Value)
		case 2:
			switch nextInt() {
			case 0:
				// 先頭を削除
				dequeue.Remove(dequeue.Front())
				pointer_list = pointer_list[1:]
			case 1:
				// 末尾を削除
				dequeue.Remove(dequeue.Back())
				pointer_list = pointer_list[:len(pointer_list)-1]
			}
		default:
			println("no such operation!")
		}
	}
}

Deque

For a dynamic array $A = \{a_0, a_1, ...\}$ of integers, perform a sequence of the following operations:

push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$.

randomAccess($p$): Print element $a_p$.

pop($d$): Delete the first element of $A$, if $d = 0$. Delete the last element of $A$, if $d = 1$.

$A$ is a 0-origin array and it is empty in the initial state.

Input

The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $d$ $x$

or

1 $p$

or

2 $d$

where the first digits 0, 1 and 2 represent push, randomAccess and pop operations respectively.

randomAccess and pop operations will not be given for an empty array.

Output

For each randomAccess, print $a_p$ in a line.

Constraints

$1 \leq q \leq 400,000$

$0 \leq p < $ the size of $A$

$-1,000,000,000 \leq x \leq 1,000,000,000$

Sample Input 1

11
0 0 1
0 0 2
0 1 3
1 0
1 1
1 2
2 0
2 1
0 0 4
1 0
1 1

Sample Output 1

2
1
3
4
1


package main

import (
	"fmt"

	"os"
	"io"
	"bufio"
	"bytes"

	"strings"
	"strconv"
)

//  長い入力を読む
func ReadLongLines(times int) ([]string, error) {
	result := make([]string, times)
	reader := bufio.NewReader(os.Stdin)
	buffer := bytes.NewBuffer(make([]byte, 0))
	readBytes := int64(2)
	for i := 0; i < times; i++ {
		for {
			readBuf, isPrefix, err := reader.ReadLine()
			// fmt.Printf("Reader.Read: %d\n", len(readBuf))
			readBytes += int64(len(readBuf) + 1)
			if err != nil {
				if err == io.EOF {
					fmt.Println("EOF")
					break
				} else {
					return result, err
				}
			}
			_, err = buffer.Write(readBuf)
			if err != nil {
				return result, err
			}
			// end of line
			if !isPrefix {
				result[i] = buffer.String()
				buffer.Reset()
				// reader = bufio.NewReader(os.Stdin)
				break
			}
		}
	}
	// 先読みしてしまうようなので、戻しておく
	os.Stdin.Seek(-int64(reader.Buffered()), os.SEEK_CUR)
	return result, nil
}

// go だと固定長配列とか辛いので無理だった
type Vector struct {
	arr [] int
	back int
}
func NewVector() Vector {
	return Vector{make([]int, 0, 10000), 0}
}
func (this *Vector)PushBack(i int) {
	if len(this.arr) - 1 < this.back {
		this.arr = append(this.arr, i)
		this.back++
	} else {
		this.arr[this.back] = i
		this.back++
	}
}
func (this *Vector)Dump() {
	for i := 0; i < this.back; i++ {
		if i == 0 {
			fmt.Printf("%d", this.arr[i])
		} else {
			fmt.Printf(" %d", this.arr[i])
		}
	}
	fmt.Println()
}
func (this *Vector) Clear() {
	this.back = 0
}

func main() {
	var n int
	var q int

	fmt.Scanf("%d %d", &n, &q)
	// 構造体の初期化が走るの嫌だな
	vectors := make([]Vector, n)

	for i := 0; i < n; i++ {
		vectors[i] = NewVector()
	}
	lines, _ := ReadLongLines(q)
	for _, line := range lines {
		args := strings.Split(line, " ")
		cmd := args[0]
		switch cmd {
		case "0":
			t, _ := strconv.Atoi(args[1])
			x, _ := strconv.Atoi(args[2])
			vectors[t].PushBack(x)
		case "1":
			t, _ := strconv.Atoi(args[1])
			vectors[t].Dump()
		case "2":
			t, _ := strconv.Atoi(args[1])
			vectors[t].Clear()
		}
	}
}

Vector II

For $n$ dynamic arrays $A_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations:

pushBack($t$, $x$): Add element $x$ at the end of $A_t$.

dump($t$): Print all elements in $A_t$.

clear($t$): Clear $A_t$. If $A_t$ is empty, do nothing.

$A_i$ is a 0-origin array and it is empty in the initial state.

Input

The input is given in the following format.

$n$ $q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $t$ $x$

or

1 $t$

or

2 $t$

where the first digits 0, 1 and 2 represent pushBack, dump and clear operations respectively.

Output

For each dump operation, print elements of $A_t$ a line. Separete adjacency elements by a space character (do not print the space after the last element). Note that, if the array is empty, an empty line should be printed.

Constraints

$1 \leq n \leq 1,000$

$1 \leq q \leq 500,000$

$-1,000,000,000 \leq x \leq 1,000,000,000$

The total number of elements printed by dump operations do not exceed 500,000

Sample Input 1

3 13
0 0 1
0 0 2
0 0 3
0 1 -1
0 2 4
0 2 5
1 0
1 1
1 2
2 1
1 0
1 1
1 2

Sample Output 1

1 2 3
-1
4 5
1 2 3

4 5


package main

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

func nextInt(sc *bufio.Scanner) int {
	sc.Scan()
	t, _ := strconv.Atoi(sc.Text())
	return t
}

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	n := nextInt(sc)
	set := make(map[int]int, n)
	for i := 0; i < n; i++ {
		set[nextInt(sc)]++
	}
	m := nextInt(sc)
	var v int
	for i := 0; i < m; i++ {
		v = nextInt(sc)
		if _, ok := set[v]; ok {
			set[v]++
		}
	}
	ans := make([]int, 0, max(n, m))
	for k, v := range set {
		if v == 1 {
			ans = append(ans, k)
		}
	}
	sort.Ints(ans)
	wtr := bufio.NewWriter(os.Stdout)
	for _, v := range ans {
		fmt.Fprintln(wtr, v)
	}
	wtr.Flush()
}

Set Difference

Find the difference of two sets $A = \{a_0, a_1, ..., a_{n-1}\}$ and $B = \{b_0, b_1, ..., b_{m-1}\}$, $A - B$.

Input

The input is given in the following format.

$n$
$a_0 \; a_1 \; ... \; a_{n-1}$
$m$
$b_0 \; b_1 \; ... \; b_{m-1}$

Elements in $A$ and $B$ are given in ascending order. There are no duplicate elements in each set.

Output

Print elements in the difference in ascending order. Print an element in a line.

Constraints

$1 \leq n, m \leq 200,000$

$0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$

$0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$

Sample Input 1

5
1 2 3 5 8
2
2 5

Sample Output 1

1
3
8


package main

import(
  "fmt"
)

func main(){
  var n,tmp_x, tmp_y int
  var town_x []int
  var town_y []int
  fmt.Scanf("%d", &n)
  for i:= 0 ; i < n ; i++{
    fmt.Scanf("%d %d", &tmp_x, &tmp_y)
    town_x = append(town_x, tmp_x)
    town_y = append(town_y, tmp_y)
  }

  //初期化
  var group []int
  var cnt []int
  for m:=0; m<n; m++{
    group = append(group, -1)
    cnt = append(cnt, 1)
  }

  for j:=0; j<n; j++{
    if (group[j] != -1){//すでにグループが決まってれば抜ける
      //fmt.Printf("Town %d in Group %d/", j, group[j])
      continue
    }else{//グループが決まってなければ新しいグループを作る
        group[j] = j
    }
    for k:= j; k<n; k++{
      if (group[k] != -1){//すでにグループが決まってれば抜ける
        continue
      }else if(k != j &&
         ((town_x[k] > town_x[j] && town_y[k] > town_y[j]) ||
          (town_x[k] < town_x[j] && town_y[k] < town_y[j]) )){
          group[k] = group[j] //kとjがつながってる場合にJを同じグループにする
          cnt[group[k]]++ //group j の個数を増やす
      }
    }
  }

  //fmt.Println("Group:", group)
  //fmt.Println("Cnt:", cnt)
  for l:=0 ; l< n; l++{
  	fmt.Println(cnt[group[l]])
  }
}

Score : 300 points

Problem Statement

There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N).

For each k = 1,2,\dots,N, find the answer to the following question:

Rng is in City k.
Rng can perform the following move arbitrarily many times:

move to another city that has a smaller x-coordinate and a smaller y-coordinate, or a larger x-coordinate and a larger y-coordinate, than the city he is currently in.

How many cities (including City k) are reachable from City k?

Constraints

1 \leq N \leq 200,000

(x_1, x_2, \dots, x_N) is a permutation of (1, 2, \dots, N).

(y_1, y_2, \dots, y_N) is a permutation of (1, 2, \dots, N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print N lines. In i-th line print the answer to the question when k = i.

Sample Input 1

4
1 4
2 3
3 1
4 2

Sample Output 1

1
1
2
2

Rng can reach City 4 from City 3, or conversely City 3 from City 4.

Sample Input 2

7
6 4
4 3
3 5
7 1
2 7
5 2
1 6

Sample Output 2

3
3
1
1
2
3
2


package main

import(
  "fmt"
)

func main(){
  var n,tmp_x, tmp_y int
  var tmp_cnt int
  var town_x []int
  var town_y []int
  var cnt []int
  fmt.Scanf("%d", &n)
  for i:= 0 ; i < n ; i++{
    fmt.Scanf("%d %d", &tmp_x, &tmp_y)
    town_x = append(town_x, tmp_x)
    town_y = append(town_y, tmp_y)
  }

  can := make([][]bool, n)
  for m:=0; m<n; m++{
    can[m] = make([]bool, n)
  }

  for j:=0; j<n; j++{
    for k:= 0; k<n; k++{
      if(k != j &&
         ((town_x[k] > town_x[j] && town_y[k] > town_y[j]) ||
          (town_x[k] < town_x[j] && town_y[k] < town_y[j]) )){
          can[j][k] = true
      }else{
        can[j][k] = false
      }

    }

  }

  //fmt.Println(canReach(0,2,can, path))

  for l:=0 ; l< n; l++{
    tmp_cnt = 1
    var path []int
    for o:= 0; o<n; o++{
      if  o != l && canReach(l, o, can, path){
        tmp_cnt++
      }
    }
    cnt = append(cnt, tmp_cnt)
  }

  for l:=0 ; l< n; l++{
  	fmt.Println(cnt[l])
  }

}

func canReach(start int, end int, can [][]bool, path []int)bool{
  if start == end {
    return true
  }
  for i := 0; i< len(can) ; i++ {
    if !contains(path, i) && can[start][i] == true{
      path = append(path, start)
      //fmt.Printf("can reach %d to %d", start, i)
      return canReach(i, end, can, path)
    }
  }
  return false
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)

func Scan() string {
	sc.Scan()
	return sc.Text()
}
func rScan() []rune {
	return []rune(Scan())
}
func iScan() int {
	n, _ := strconv.Atoi(Scan())
	return n
}
func fScan() float64 {
	n, _ := strconv.ParseFloat(Scan(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func SScan(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scan()
	}
	return a
}
func iSScan(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = iScan()
	}
	return a
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}
func mod(x, d int) int {
	x %= d
	if x < 0 {
		x += d
	}
	return x
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := -int(1e+18)
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := int(1e+18)
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func sum(a []int) int {
	x := 0
	for _, v := range a {
		x += v
	}
	return x
}
func fSum(a []float64) float64 {
	x := 0.
	for _, v := range a {
		x += v
	}
	return x
}
func bPrint(f bool, x string, y string) {
	if f {
		fmt.Println(x)
	} else {
		fmt.Println(y)
	}
}
func iSSPrint(x []int) {
	fmt.Println(strings.Trim(fmt.Sprint(x), "[]"))
}

var lp1 int = 1000000007
var lp2 int = 998244353

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, lp1)
	sc.Split(bufio.ScanWords)
	n := iScan()
	m := iScan()
	s := SScan(n)
	mcf := newMinCostFlow(n*m + 2)
	st, g := n*m, n*m+1
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			mcf.AddEdge(i*m+j, g, 1, 0)
			if s[i][j] == 'o' {
				mcf.AddEdge(st, i*m+j, 1, 0)
				d := make([][]int, n)
				for k := 0; k < n; k++ {
					d[k] = make([]int, m)
					for l := 0; l < m; l++ {
						d[k][l] = -lp1
					}
				}
				d[i][j] = 0
				for k := 0; k < n; k++ {
					for l := 0; l < m; l++ {
						if s[k][l] != '#' {
							if k > 0 {
								d[k][l] = larger(d[k][l], d[k-1][l]+1)
							}
							if l > 0 {
								d[k][l] = larger(d[k][l], d[k][l-1]+1)
							}
						}
					}
				}
				for k := 0; k < n; k++ {
					for l := 0; l < m; l++ {
						mcf.AddEdge(m*i+j, m*k+l, 1, -d[k][l])
					}
				}
			}
		}
	}
	fmt.Println(-mcf.Flow(st, g)[1])
}

type MinCostFlow struct {
	n   int
	pos [][2]int
	g   [][]_Edge
}
type _Edge struct {
	to   int
	rev  int
	capa int
	cost int
}
type Edge struct {
	from int
	to   int
	capa int
	flow int
	cost int
}

func newMinCostFlow(n int) *MinCostFlow {
	return &MinCostFlow{n: n, g: make([][]_Edge, n)}
}
func (mcf *MinCostFlow) AddEdge(from, to, capa, cost int) int {
	m := len(mcf.pos)
	mcf.pos = append(mcf.pos, [2]int{from, len(mcf.g[from])})
	mcf.g[from] = append(mcf.g[from], _Edge{to, len(mcf.g[to]), capa, cost})
	mcf.g[to] = append(mcf.g[to], _Edge{from, len(mcf.g[from]) - 1, 0, -cost})
	return m
}
func (mcf *MinCostFlow) GetEdge(i int) Edge {
	e := mcf.g[mcf.pos[i][0]][mcf.pos[i][1]]
	re := mcf.g[e.to][e.rev]
	return Edge{mcf.pos[i][0], e.to, e.capa + re.capa, re.capa, e.cost}
}
func (mcf *MinCostFlow) Edges() []Edge {
	m := len(mcf.pos)
	res := make([]Edge, m)
	for i := 0; i < m; i++ {
		res[i] = mcf.GetEdge(i)
	}
	return res
}
func (mcf *MinCostFlow) Flow(s, t int) [2]int {
	res := mcf.Slope(s, t)
	return res[len(res)-1]
}
func (mcf *MinCostFlow) FlowL(s, t, flowLim int) [2]int {
	res := mcf.SlopeL(s, t, flowLim)
	return res[len(res)-1]
}
func (mcf *MinCostFlow) Slope(s, t int) [][2]int {
	return mcf.SlopeL(s, t, int(1e+18))
}
func (mcf *MinCostFlow) SlopeL(s, t, flowLim int) [][2]int {
	dual, dist := make([]int, mcf.n), make([]int, mcf.n)
	pv, pe := make([]int, mcf.n), make([]int, mcf.n)
	vis := make([]bool, mcf.n)
	dualRef := func() bool {
		for i := 0; i < mcf.n; i++ {
			dist[i], pv[i], pe[i] = int(1e+18), -1, -1
			vis[i] = false
		}
		pq := make(PriorityQueue, 0)
		heap.Init(&pq)
		item := &Item{value: s, priority: 0}
		dist[s] = 0
		heap.Push(&pq, item)
		for pq.Len() != 0 {
			v := heap.Pop(&pq).(*Item).value
			if vis[v] {
				continue
			}
			vis[v] = true
			if v == t {
				break
			}
			for i := 0; i < len(mcf.g[v]); i++ {
				e := mcf.g[v][i]
				if vis[e.to] || e.capa == 0 {
					continue
				}
				cost := e.cost - dual[e.to] + dual[v]
				if dist[e.to]-dist[v] > cost {
					dist[e.to] = dist[v] + cost
					pv[e.to] = v
					pe[e.to] = i
					item := &Item{value: e.to, priority: dist[e.to]}
					heap.Push(&pq, item)
				}
			}
		}
		if !vis[t] {
			return false
		}
		for v := 0; v < mcf.n; v++ {
			if !vis[v] {
				continue
			}
			dual[v] -= dist[t] - dist[v]
		}
		return true
	}
	flow, cost, prevCost := 0, 0, -1
	res := make([][2]int, 0, mcf.n)
	res = append(res, [2]int{flow, cost})
	for flow < flowLim {
		if !dualRef() {
			break
		}
		c := flowLim - flow
		for v := t; v != s; v = pv[v] {
			c = mcf.Min(c, mcf.g[pv[v]][pe[v]].capa)
		}
		for v := t; v != s; v = pv[v] {
			mcf.g[pv[v]][pe[v]].capa -= c
			mcf.g[v][mcf.g[pv[v]][pe[v]].rev].capa += c
		}
		d := -dual[s]
		flow += c
		cost += c * d
		if prevCost == d {
			res = res[:len(res)-1]
		}
		res = append(res, [2]int{flow, cost})
		prevCost = cost
	}
	return res
}
func (mcf *MinCostFlow) Min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

type Item struct {
	value    int
	priority int
	index    int
}
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].priority < pq[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}
func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil
	item.index = -1
	*pq = old[0 : n-1]
	return item
}
func (pq *PriorityQueue) update(item *Item, value int, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

Score : 600 points

Problem Statement

There is a board with N rows and M columns.
The information of this board is represented by N strings S_1,S_2,\ldots,S_N.
Specifically, the state of the square at the i-th row from the top and the j-th column from the left is represented as follows:

S_{i,j}=. : the square is empty.

S_{i,j}=# : an obstacle is placed on the square.

S_{i,j}=o : a piece is placed on the square.

Yosupo repeats the following operation:

Choose a piece and move it to its right adjecent square or its down adjacent square.
Moving a piece to squares with another piece or an obstacle is prohibited.
Moving a piece out of the board is also prohibited.

Yosupo wants to perform the operation as many times as possible.
Find the maximum possible number of operations.

Constraints

1 \leq N \leq 50

1 \leq M \leq 50

S_i is a string of length M consisting of ., # and o.

1 \leq ( the number of pieces )\leq 100.
In other words, the number of pairs (i, j) that satisfy S_{i,j}=o is between 1 and 100, both inclusive.

Input

Input is given from Standard Input in the following format:

N M
S_1
S_2
\vdots
S_N

Output

Print the maximum possible number of operations in a line.

Sample Input 1

3 3
o..
...
o.#

Sample Output 1

4

Yosupo can perform operations 4 times as follows:

o.. .o. ..o ... ...
... -> ... -> ... -> ..o -> ..o
o.# o.# o.# o.# .o#

Sample Input 2

9 10
.#....o#..
.#..#..##o
.....#o.##
.###.#o..o
#.#...##.#
..#..#.###
#o.....#..
....###..o
o.......o#

Sample Output 2

24


package main

import "fmt"

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

	var num int
	ans := false
	d1 := make([]int, n)
	d2 := make([]int, n)
	for i := range d1 {
		fmt.Scan(&d1[i], &d2[i])
		if d1[i] == d2[i] {
			num++
		}else{
			num = 0
		}
		if num >= 3 {
			ans = true
		}
	}
	if ans == true {
		fmt.Println("Yes")
	}else{
		fmt.Println("No")
	}
}

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

6
1 1
2 2
3 3
4 4
5 5
6 6

Sample Output 3

Yes


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int) []int {
	ret := make([]int, N)
	for i := 0; i < N; i++ {
		ret[i] = getInt()
	}
	return ret
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

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

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

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func small(N, X, M int) {
	a := X
	ans := X
	for i := 2; i <= N; i++ {
		a *= a
		a %= M
		ans += a
	}
	out(ans)
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 1000000)

	N, X, M := getInt(), getInt(), getInt()

	// if N < 1000000000 {
	// 	small(N, X, M)
	// 	return
	// }
	m := make([]int, M)
	b := make([]int, 0)

	last := -1
	a := X % M
	b = append(b, a)
	tot := a
	m[a]++
	for i := 1; i <= N; i++ {
		a *= a
		a %= M
		if m[a] != 0 {
			last = a
			break
		}
		if a == 0 {
			out(tot)
			return
		}
		tot += a
		m[a]++
		b = append(b, a)
	}
	// out(b, last, tot)
	if last == -1 {
		out(tot)
		return
	}
	start := 0
	ans := 0
	for i := 0; i < len(b); i++ {
		if b[i] == last {
			start = i
			break
		}
		ans += b[i]
		tot -= b[i]
	}
	N -= start
	loop := len(b) - start
	// out(N, loop, tot)
	n := N / loop
	ans += n * tot
	rest := N % loop
	for i := 0; i < rest; i++ {
		ans += b[start+i]
	}
	// out(n*loop + rest)
	out(ans)
}

Score : 500 points

Problem Statement

Let us denote by f(x, m) the remainder of the Euclidean division of x by m.

Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.

Constraints

1 \leq N \leq 10^{10}

0 \leq X < M \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X M

Output

Print \displaystyle{\sum_{i=1}^N A_i}.

Sample Input 1

6 2 1001

Sample Output 1

1369

The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.

Sample Input 2

1000 2 16

Sample Output 2

6

The sequence A begins 2,4,0,0,\ldots Therefore, the answer is 6.

Sample Input 3

10000000000 10 99959

Sample Output 3

492443256176507


package main

import "fmt"

func main(){
  var i int
  fmt.Scan(&i)
  switch{
  case i == 0:
      fmt.Println("1")
  case i == 1:
      fmt.Print("0")
  }

}

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


package main

import "fmt"

func main() {
	var num int
	fmt.Scanf("%d", &num)
	if num == 0 {
		fmt.Println(1)
	} else if num == 1 {
		fmt.Println(0)
	} else {
		fmt.Println("hoge")
	}
}


package main

import (
	"fmt"
)

const div = 1000000007

func Powmod(x, n int) int {
	res := 1
	for i := 0; i < n; i++ {
		res = (res * x) % div
	}
	return res
}

func main() {
	var n int
	fmt.Scan(&n)
	ans := Powmod(10, n) - 2*Powmod(9, n) + Powmod(8, n)
	ans %= div
	ans = (ans + div) % div
	fmt.Println(ans)
}

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


package main

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

var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout)

func scanString() string   { sc.Scan(); return sc.Text() }
func scanRunes() []rune    { return []rune(scanString()) }
func scanInt() int         { a, _ := strconv.Atoi(scanString()); return a }
func scanInt64() int64     { a, _ := strconv.ParseInt(scanString(), 10, 64); return a }
func scanFloat64() float64 { a, _ := strconv.ParseFloat(scanString(), 64); return a }

func scanInts(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = scanInt()
	}
	return res
}

func debug(a ...interface{}) {
	if os.Getenv("ONLINE_JUDGE") == "false" {
		fmt.Fprintln(os.Stderr, a...)
	}
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

//•*¨*•.¸¸♪main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)
func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1001001)

	tests := scanInt()
	for test := 0; test < tests; test++ {
		n, m, a, b := scanInt(), scanInt(), scanInt(), scanInt()
		fmt.Fprintln(wr, floorSum(n, m, a, b))
	}
}

func floorSum(n, m, a, b int) int {
	ans := 0
	if a >= m {
		ans += (n - 1) * n * (a / m) / 2
		a %= m
	}
	if b >= m {
		ans += n * (b / m)
		b %= m
	}

	yma := (a*n + b) / m
	if yma == 0 {
		return ans
	}
	xma := yma*m - b
	ans += (n - (xma+a-1)/a) * yma
	ans += floorSum(yma, a, m, (a-xma%a)%a)
	return ans
}

Score : 100 points

Problem Statement

In this problem, you should process T testcases.

For each testcase, you are given four integers N, M, A, B.

Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M).

Constraints

1 \leq T \leq 100,000

1 \leq N, M \leq 10^9

0 \leq A, B < M

Input

Input is given from Standard Input in the following format:

T
N_0 M_0 A_0 B_0
N_1 M_1 A_1 B_1
:
N_{T - 1} M_{T - 1} A_{T - 1} B_{T - 1}

Output

Print the answer for each testcase.

Sample Input 1

5
4 10 6 3
6 5 4 3
1 1 0 0
31415 92653 58979 32384
1000000000 1000000000 999999999 999999999

Sample Output 1

3
13
0
314095480
499999999500000000


package main

import "fmt"

func main() {
	var D, T, S float64
	fmt.Scan(&D, &T, &S)

  var dis = (T * S)

  if T <= dis {
    fmt.Println("Yes")
  }else{
    fmt.Println("No")
  }
}

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


package main

import (
	"fmt"
	"strings"
)

func intmin() func(int) int {
	isFirst := true
	min := 0
	return func(a int) int {
		if isFirst {
			isFirst = false
			min = a
			return a
		}
		if min > a {

			return a
		}
		return min
	}
}
func main() {
	var S, T string
	fmt.Scan(&S, &T)

	s := strings.Split(S, "")
	t := strings.Split(T, "")

	count := 0
	min := 0
	isFirst := true

	for offset := 0; offset < len(S)-len(T); offset++ {

		for i := 0; i < len(T); i++ {

			if s[offset+i] != t[i] {
				count++
			}

		}

		min = func(a int) int {
			if isFirst {
				isFirst = false
				return a
			}
			if min > a {
				return a
			}
			return min
		}(count)

		count = 0

	}
	fmt.Println(min)

}

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


package main

import "fmt"

func main() {
	var S, T string
	fmt.Scan(&S, &T)

	result := 0
	for i := 0; i <= len(S)-len(T); i++ {
		count := 0
		for j := 0; j < len(T); j++ {
			if S[i+j] == T[j] {
				count++
			}
		}
		if count > result {
			result = count
		}
	}
	fmt.Println(len(T) - result)
}


package main

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

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

	var s, t string
	fmt.Fscan(r, &s)
	fmt.Fscan(r, &t)

	min := len(t)

	for i := 0; i < len(s)-len(t)+1; i++ {
		diff := 0
		for j := 0; j < len(t); j++ {
			if s[i+j] != t[j] {
				diff++
			}
		}

		if diff < min {
			min = diff
		}
	}

	fmt.Fprintln(w, min)
}


package main

import "fmt"

func main() {
	var s, t string
	fmt.Scan(&s, &t)

	ss := split(s)
	tt := split(t)
	min := 1000
	for i := 0; i < len(ss);i++ {
		cnt := len(tt)
		for j := 0; j < len(tt); j++ {

			if ss[i+j] == tt[j] {
				cnt--
			}
			if i+j == len(ss)-1 {
			// if i+j >= len(ss)-1 {
				break
			}
		}
		if cnt <  min {
			min = cnt
		}
	}

	fmt.Println(min)
}

func split(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}


package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)

	var t string
	fmt.Scan(&t)

	s1 := strings.Split(s, "")
	s2 := strings.Split(t, "")

	length1 := len(s1)
	length2 := len(s2)

	length := length1 - length2
	var count int
	max := 0
	for i := 0; i < length; i++ {
		count = 0
		for j := 0; j < length2; j++ {
			if s1[j+i] == s2[j]{
				count++
			}
		}
		if max < count{
			max = count
		}
	}

	ans := length2 - max
	fmt.Println(ans)
}


package main

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

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

func main() {
	/*/TODO:!!!!!!!テスト用!!!!!!!!!
	sc = bufio.NewScanner(strings.NewReader(`
										`))
	//TODO:!!!!!!!テスト用!!!!!!!!!*/

	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)
	defer out.Flush() // !!!!caution!!!! you must use Fprint(out, ) not Print()
	/* --- code --- */
	//fmt.Fprintln(out, "[DEBUG]", time.Now())

	s := next()
	t := next()

	ans := len(t)
	for i := 0; i < len(s)-len(t); i++ {
		w := 0
		for j := 0; j < len(t); j++ {
			if s[i+j] != t[j] {
				w++
			}
		}
		ans = minInt(ans, w)
	}

	//fmt.Fprintln(out, "[DEBUG]", a)
	fmt.Fprintln(out, ans)

}

// 挿入ソート配列
type slist struct {
	l []int
}

func makeSlist() slist {
	return slist{[]int{}}
}

func (s *slist) add(a int) {
	pos := sort.Search(len(s.l), func(i int) bool { return s.l[i] >= a })
	if pos < len(s.l) {
		s.l = append(s.l[:pos+1], s.l[pos:]...)
		s.l[pos] = a
	} else {
		s.l = append(s.l, a)
	}
}
func (s slist) contains(a int) bool {
	pos := sort.Search(len(s.l), func(i int) bool { return s.l[i] >= a })
	return pos < len(s.l) && s.l[pos] == a
}

//------------------------------------------------------------------------------

// -*-*-*-*-*-*-*-*-
// * I/O utilities *
// -*-*-*-*-*-*-*-*-

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

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

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

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}
func nextFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := 0; i < n; i++ {
		ret[i] = nextFloat64()
	}
	return ret
}
func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func chars(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}

func printArray(a []int) {
	for i := 0; i < len(a); i++ {
		if i >= 1 {
			fmt.Fprint(out, " ")
		}
		fmt.Fprint(out, a[i])
	}
	fmt.Fprintln(out)
}

func absInt(x int) int {
	return int(math.Abs(float64(x)))
}
func minInt(x, y int) int {
	if x < y {
		return x
	}
	return y
}
func maxInt(x, y int) int {
	if x > y {
		return x
	}
	return y
}
func sign(x int) int {
	if x == 0 {
		return 0
	}
	if x > 0 {
		return 1
	}
	return -1
}
func log10(x int) float64 {
	return math.Log10(float64(x))
}
func divCeil(shi, bo int) int {
	ans := shi / bo
	if shi%bo != 0 {
		ans++
	}
	return ans
}


package main

import (
	"fmt"
)

func main() {
	var N, M int
	fmt.Scan(&N, &M)
	uf := newUF(N)
	var x, y int
	for i := 0; i < M; i++ {
		fmt.Scan(&x, &y)
		uf.unite(x-1, y-1)
	}
	checked := make([]int, uf.n)
	for i := range checked {
		r := uf.root(i)
		checked[r]++
	}
	fmt.Println(max(checked))

}

type unionFind struct {
	pair []int
	n    int
}

func newUF(N int) *unionFind {
	uf := new(unionFind)
	uf.n = N
	pair := make([]int, N)
	for i := 0; i < N; i++ {
		pair[i] = i
	}
	uf.pair = pair
	return uf
}
func (uf unionFind) unite(x int, y int) {
	rx := uf.root(x)
	ry := uf.root(y)
	if rx != ry {
		uf.pair[rx] = ry
	}
}
func (uf unionFind) root(x int) int {
	r := x
	for {
		if uf.pair[r] == r {
			break
		}
		r = uf.pair[r]
	}
	return r
}
func (uf unionFind) same(x int, y int) bool {
	rx := uf.root(x)
	ry := uf.root(y)
	return rx == ry
}
func (uf unionFind) countTree() int {
	ans := 0
	checked := make([]bool, uf.n)
	for i := range checked {
		r := uf.root(i)
		if checked[r] {
			checked[r] = true
			ans++
		}
	}
	return ans
}
func max(a []int) int {
	max := a[0]
	for _, i := range a {
		if i > max {
			max = i
		}
	}
	return max
}

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

2 \leq N \leq 2\times 10^5

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

4 10
1 2
2 1
1 2
2 1
1 2
1 3
1 4
2 3
2 4
3 4

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


// Takoyaki

package main

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

func takoyaki(n, x, t int) int {
	return int(math.Ceil(float64(n)/float64(x))) * t
}

func nextInt(sc *bufio.Scanner) (int, error) {
	sc.Scan()
	t := sc.Text()
	return strconv.Atoi(t)
}

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

	n, _ := nextInt(sc)
	x, _ := nextInt(sc)
	t, _ := nextInt(sc)

	r := takoyaki(n, x, t)
	fmt.Println(r)
}

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


package main

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

func main() {
	N := nextInt()
	X := nextInt()
	T := nextInt()

	fmt.Println((N + X - 1) / X * T)
}

var stdin = initStdin()

func initStdin() *bufio.Scanner {
	bufsize := 1 * 1024 * 1024 // 1 MB
	var stdin = bufio.NewScanner(os.Stdin)
	stdin.Buffer(make([]byte, bufsize), bufsize)
	stdin.Split(bufio.ScanWords)
	return stdin
}

func nextString() string {
	stdin.Scan()
	return stdin.Text()
}

func nextBytes() []byte {
	stdin.Scan()
	return stdin.Bytes()
}

func nextInt() int {
	i, _ := strconv.Atoi(nextString())
	return i
}

func nextInt64() int64 {
	i, _ := strconv.ParseInt(nextString(), 10, 64)
	return i
}

func debug(args ...interface{}) {
	fmt.Fprintln(os.Stderr, args)
}


//go:generate echo "https://atcoder.jp/contests/abc176/tasks/abc176_b"
package main

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

type scanner struct{ *bufio.Scanner }

func newScanner(r io.Reader) *scanner {
	s := bufio.NewScanner(r)
	s.Split(bufio.ScanWords)
	s.Buffer(nil, 100000000)
	return &scanner{s}
}

func (s *scanner) String() string {
	s.Scan()
	return s.Text()
}

func (s *scanner) StringSlice(l int) []string {
	if l == 0 {
		return []string{}
	}
	sl := make([]string, l, l)
	for i := range sl {
		sl[i] = s.String()
	}
	return sl
}

func solve(n string) bool {
	sum := 0
	for _, c := range n {
		n, _ := strconv.Atoi(string(c))
		sum += n
	}
	return sum%9 == 0
}

func main() {
	scan := newScanner(os.Stdin)
	n := scan.String()
	if solve(n) {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

const inf = 1000000000

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

type PriorityQueueItem struct {
	value    int
	priority int
}

type PrioirtyQueue struct {
	items       []PriorityQueueItem
	value2Index map[int]int
}

func newPriorityQueue() *PrioirtyQueue {
	q := new(PrioirtyQueue)
	q.value2Index = make(map[int]int, 0)
	return q
}

func (q *PrioirtyQueue) Len() int {
	return len(q.items)
}
func (q *PrioirtyQueue) Less(i, j int) bool {
	return q.items[i].priority < q.items[j].priority
}
func (q *PrioirtyQueue) Swap(i, j int) {
	q.items[i], q.items[j] = q.items[j], q.items[i]
	q.value2Index[q.items[i].value] = i
	q.value2Index[q.items[j].value] = j
}
func (q *PrioirtyQueue) Push(x interface{}) {
	q.items = append(q.items, x.(PriorityQueueItem))
	q.value2Index[x.(PriorityQueueItem).value] = len(q.items) - 1
}
func (q *PrioirtyQueue) Pop() interface{} {
	x := q.items[len(q.items)-1]
	q.items = q.items[0 : len(q.items)-1]
	delete(q.value2Index, x.value)
	return x
}
func (q *PrioirtyQueue) update(x PriorityQueueItem) {
	q.items[q.value2Index[x.value]] = x
	heap.Fix(q, q.value2Index[x.value])
}

type AdjacencyList struct {
	node int
	cost int
	next *AdjacencyList
}

func dijkstra(als []*AdjacencyList, s int) []int {
	ds := make([]int, len(als))
	q := newPriorityQueue()
	for v := 0; v < len(als); v++ {
		if v == s {
			ds[v] = 0
		} else {
			ds[v] = inf
		}
		q.Push(PriorityQueueItem{v, ds[v]})
	}
	heap.Init(q)
	for q.Len() != 0 {
		u := heap.Pop(q).(PriorityQueueItem).value
		for al := als[u]; al != nil; al = al.next {
			if ds[u]+al.cost < ds[al.node] {
				ds[al.node] = ds[u] + al.cost
				q.update(PriorityQueueItem{al.node, ds[al.node]})
			}
		}
	}
	return ds
}

func main() {
	var H, W int
	fmt.Scanf("%d%d", &H, &W)
	var Ch, Cw int
	fmt.Scanf("%d%d", &Ch, &Cw)
	Ch--
	Cw--
	var Dh, Dw int
	fmt.Scanf("%d%d", &Dh, &Dw)
	Dh--
	Dw--
	reader := bufio.NewReader(os.Stdin)
	bytes, _ := reader.ReadBytes(0)
	bytesIndex := 0
	S := make([][]byte, H)
	for i := 0; i < H; i++ {
		S[i] = make([]byte, W)
		for j := 0; j < W; j++ {
			S[i][j] = bytes[bytesIndex]
			bytesIndex++
		}
		bytesIndex++
	}
	als := make([]*AdjacencyList, H*W)
	for i := 0; i < H; i++ {
		for j := 0; j < W; j++ {
			if S[i][j] == '#' {
				continue
			}
			for k := -2; k <= 2; k++ {
				for l := -2; l <= 2; l++ {
					if i+k < 0 || i+k >= H || j+l < 0 || j+l >= W || (k == 0 && l == 0) || S[i+k][j+l] == '#' {
						continue
					}
					al := new(AdjacencyList)
					al.node = (i+k)*W + j + l
					if abs(k)+abs(l) == 1 {
						al.cost = 0
					} else {
						al.cost = 1
					}
					al.next = als[i*W+j]
					als[i*W+j] = al
				}
			}
		}
	}
	s := Ch*W + Cw
	g := Dh*W + Dw
	dsg := dijkstra(als, s)[g]
	if dsg == inf {
		fmt.Printf("-1\n")
	} else {
		fmt.Printf("%d\n", dsg)
	}
	return
}

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2


package main

import (
	"fmt"
	"math/bits"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	if n < 3 {
		fmt.Println(0)
		return
	}
	l := make([]int, n)
	for i := range l {
		fmt.Scan(&l[i])
	}
	var ans int

	x := Combinations(l, 3)
	for _, v := range x {
		sort.Ints(v)
		if !(v[0]+v[1] < v[2]) {
			ans++
		}
	}

	fmt.Println(ans)
}

func Combinations(set []int, n int) (subsets [][]int) {
	length := uint(len(set))

	if n > len(set) {
		n = len(set)
	}

	// Go through all possible combinations of objects
	// from 1 (only first object in subset) to 2^length (all objects in subset)
	for subsetBits := 1; subsetBits < (1 << length); subsetBits++ {
		if n > 0 && bits.OnesCount(uint(subsetBits)) != n {
			continue
		}

		var subset []int

		for object := uint(0); object < length; object++ {
			// checks if object is contained in subset
			// by checking if bit 'object' is set in subsetBits
			if (subsetBits>>object)&1 == 1 {
				// add object to subset
				subset = append(subset, set[object])
			}
		}
		// add subset to subsets
		subsets = append(subsets, subset)
	}
	return subsets
}

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wt = bufio.NewWriter(os.Stdout)
)

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

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

func nextInt3() (int, int, int) {
	return nextInt(), nextInt(), nextInt()
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func min(nums ...int) int {
	ret := nums[0]
	for _, v := range nums {
		if v < ret {
			ret = v
		}
	}
	return ret
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer wt.Flush()

	x, k, d := nextInt3()

	var ans int
	if abs(x) > d*k {
		ans = min(abs(x-d*k), abs(x+d*k))
		puts(ans)
		return
	}

	x, k = x-(x/d)*d, k-abs(x)/d
	if k%2 == 0 {
		ans = x
	} else if x > 0 {
		ans = x - d
	} else {
		ans = x + d
	}
	puts(abs(ans))
}

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


package main

import (
	"fmt"
	"math"
)

func main() {
	var x, k, d int
	fmt.Scan(&x, &k, &d)
	x = int(math.Abs(float64(x)))
	for x > 0 {
		x = x - d
		k--
		if k == 0 {
			break
		}
	}
	if k >= 2 {
		s := 0
		for k >= 1 {
			if s == 0 {
				x += d
				s = 1
			} else {
				x -= d
				s = 0
			}
		}
	}
	min := int(math.Abs(float64(x)))
	if int(math.Abs(float64(x+d))) < min {
		fmt.Println(int(math.Abs(float64(x + d))))
		return
	}
	if int(math.Abs(float64(x-d))) < min {
		fmt.Println(int(math.Abs(float64(x - d))))
		return
	}
	fmt.Println(min)
	return
}


package main

import "fmt"

func main() {
	var x, k, d int
	fmt.Scan(&x, &k, &d)

	x = abs(x)
	c := min(k, max(1, x/d))
	x = abs(x - c*d)
	k -= c
	if k == 0 {
		fmt.Println(abs(x))
		return
	}

	if k%2 == 1 {
		x = abs(x - d)
	}

	fmt.Println(x)
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024*1024), bufio.MaxScanTokenSize)
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func nextFloat() float64 {
	sc.Scan()
	f, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

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

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

func main() {
	N := nextInt()
	K := nextInt()
	D := nextInt()
	TOTAL := K * D
	MIN := N / D
	if TOTAL <= N {
		fmt.Println(N - TOTAL)
	} else {
		if (K-MIN)%2 == 0 {
			fmt.Println(abs(TOTAL - N - D*(K-MIN)))
		} else {
			fmt.Println(abs(TOTAL-N-D*(K-MIN)) + D)
		}
	}
}

func abs(n int) int {
	if n < 0 {
		n = -n
	}
	return n
}


package main

import "fmt"

func main() {
	var x, d, k int64
	fmt.Scan(&x)
	fmt.Scan(&k)
	fmt.Scan(&d)
	if x < 0 {
		x = -x
	}
	if d * k <= x {
		fmt.Println(x - d * k)
		return
	}
	b := x/d
	m := k - b
	if m % 2 == 0 {
		fmt.Println(x - d * b)
		return
	}
	fmt.Println((b+1) * d - x)
}


package main

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

func main() {
	X, K, D := ReadInt(), ReadInt(), ReadInt()
	if X < 0 {
		X = -X
	}
	L := (X + D - 1) / D
	if K < L {
		fmt.Println(X - K*D)
		return
	}
	lx := X - L*D
	if lx == 0 {
		if (K-L)%2 == 0 {
			fmt.Println(0)
		} else {
			fmt.Println(D)
		}
		return
	}
	if (K-L)%2 == 1 {
		fmt.Println(X % D)
	} else {
		fmt.Println(D - X%D)
	}
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}


package main

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

const Inf = 1 << 60

func main() {
	N, K := ReadInt(), ReadInt()
	P := ReadInts(N)
	C := ReadInts(N)

	for i := 0; i < N; i++ {
		P[i]--
	}

	maxScore := -Inf
	for i := 0; i < N; i++ {
		seen := make([]bool, N)
		var dfs func(v int) (int, int)
		dfs = func(v int) (int, int) {
			if seen[v] {
				return 0, 0
			}
			seen[v] = true
			size, score := dfs(P[v])
			return size + 1, C[v] + score
		}
		size, loopScore := dfs(i)

		score := 0
		rest := 0
		if loopScore > 0 {
			loop := K/size - 1
			score += loop * loopScore
			rest = K - loop*size
			if score > maxScore {
				maxScore = score
			}
		} else {
			rest = size
		}
		v := i
		for j := 0; j < rest; j++ {
			v = P[v]
			score += C[v]
			if score > maxScore {
				maxScore = score
			}
		}
	}

	fmt.Println(maxScore)
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


package main

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
)

func init() {
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
}

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

func readInt() int {
	n, _ := strconv.Atoi(ReadString())
	return n
}

// 10 11 12 => [10, 11, 12]
func readIntSlice(size int) []int {
	a := make([]int, size)
	for i := 0; i < size; i++ {
		a[i] = readInt()
	}
	return a
}

func get2byte(size int) [][]byte {
	a := make([][]byte, size)
	for i := 0; i < size; i++ {
		var low string
		fmt.Scan(&low)
		a[i] = []byte(low)
	}
	return a
}

func transpose(a [][]int) {
	n := len(a)
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			a[i][j], a[j][i] = a[j][i], a[i][j]
		}
	}
}

func fact(n, m int) int {
	res := 1
	for i := m + 1; i <= n; i++ {
		res *= i
	}
	return res
}

func perm(n, r int) int {
	if r > n {
		return 0
	}
	return fact(n, n-r)
}

func comb(n, m int) int {
	if m > n {
		return 0
	}
	return fact(n, n-m) / fact(m, 0)
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

func max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}
func sum(integers ...int) int64 {
	var res int64
	for _, integer := range integers {
		res += int64(integer)
	}
	return res
}
func cumulativeSum(as []int) []int64 {
	cs := make([]int64, len(as)+1)
	for i, a := range as {
		cs[i+1] = cs[i] + int64(a)
	}
	return cs
}

func main() {
	n, k := readInt(), readInt()
	ps := readIntSlice(n)
	cs := readIntSlice(n)

	fmt.Println(naiveSolve(n, k, ps, cs))
}

func naiveSolve(n, k int, ps, cs []int) int64 {
	var max int64 = -10000000000
	for i := 0; i < n; i++ {
		var sum int64
		j := ps[i] - 1
		var counter int

		for counter < k {
			sum += int64(cs[j])
			if max < sum {
				max = sum
			}
			j = ps[j] - 1
			counter++
		}
	}
	return max
}

func solve(n, k int, ps, cs []int) int64 {
	visited := make(map[int]struct{})
	var arrays [][]int
	for i := 0; i < n; i++ {
		if _, ok := visited[i]; ok {
			continue
		}
		var as []int
		visited[i] = struct{}{}
		as = append(as, cs[i])
		j := ps[i] - 1
		for j != i {
			as = append(as, cs[j])
			visited[j] = struct{}{}
			j = ps[j] - 1
		}
		arrays = append(arrays, as)
	}
	var max int64
	max = -10000000000
	for _, as := range arrays {
		tmp := calcMaxScore(as, k)
		if max < tmp {
			max = tmp
		}
	}
	return max
}

func calcMaxScore(as []int, k int) int64 {
	n := len(as)
	loopArray := append(as, as...)
	loopArray = append(loopArray, as...)
	start := 0
	end := 1
	cs := cumulativeSum(loopArray)
	sum := sum(as...)
	var baseScore int64
	if sum > 0 {
		count := k/n - 1
		baseScore = sum * int64(count)
	}
	var calcRange int
	if k%n == 0 {
		calcRange = n
	} else {
		calcRange = k%n + n
	}
	var max int64
	max = -10000000000
	for end < len(loopArray) || (loopArray[start] < 0 && start != end-1) {
		if start != end-1 && loopArray[start] < 0 {
			start++
		}
		sum := cs[end] - cs[start]
		if sum > max {
			max = sum
		}
		if calcRange == 1 {
			start++
			end++
		} else if end-start == calcRange {
			start++
		} else if end < len(loopArray) {
			end++
		}
	}
	return max + baseScore
}


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
	"strconv"
)

const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
)

func main() {
	N := getInt()
	K := getInt()
	P := getIntArray(N)
	C := getIntArray(N)

	g := NewGraph(N, C)
	for i := 0; i < N; i++ {
		g.AddEdge(i, P[i]-1)
	}

	routes := make([][]int, N)
	for i := 0; i < N; i++ {
		route := make([]int, 0)
		dfs(i, g.edges, make(map[int]struct{}), &route)
		routes[i] = route
	}

	points := make([]int, N)
	for i := 0; i < N; i++ {
		routePoint := 0
		for _, p := range routes[i] {
			routePoint += C[p]
		}

		if routePoint > 0 {
			points[i] = routePoint * (K / len(routes[i]))
			rest := K % len(routes[i])
			for j := 0; j < rest; j++ {
				points[i] += C[routes[i][j+1]]
			}
		} else {
			for j := 0; j < len(routes[i]) - 1; j++ {
				if j != 0 && routePoint < 0 && C[routes[i][j+1]] < 0 {
					break
				}

				points[i] += C[routes[i][j+1]]
			}
		}
	}

	//for i := 0; i < N; i++ {
	//	fmt.Println(routes[i], points[i])
	//}

	fmt.Println(max(points...))
}

type Graph struct {
	n      int
	edges  []map[int]struct{}
	points []int
}

func NewGraph(n int, points []int) *Graph {
	g := &Graph{
		n:     n,
		edges: make([]map[int]struct{}, n),
		points: points,
	}
	for i := 0; i < n; i++ {
		g.edges[i] = make(map[int]struct{})
	}
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.edges[u][v] = struct{}{}
}

func dfs(c int, edges []map[int]struct{}, visited map[int]struct{}, route *[]int) {
	visited[c] = struct{}{}
	*route = append(*route, c)

	for v := range edges[c] {
		_, flag := visited[v]
		if flag {
			continue
		}
		dfs(v, edges, visited, route)
	}
}

func bfs(c int, graph *Graph) {
	standby := make(map[int]struct{})
	next := make([]int, 0)
	next = append(next, c)
	visited := make(map[int]struct{})

	for ; len(next) != 0; {
		u := next[0]
		next = next[1:]
		visited[u] = struct{}{}
		delete(standby, u)

		for v := range graph.edges[u] {
			_, flag := visited[v]
			if flag {
				continue
			}

			// なにか処理

			if _, exists := standby[v]; !exists {
				next = append(next, v)
				standby[v] = struct{}{}
			}
		}
	}
}

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getIntArray(n int) []int {
	array := make([]int, n)
	for i := 0; i < n; i++ {
		array[i] = getInt()
	}
	return array
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

func getStringArray(n int) []string {
	array := make([]string, n)
	for i := 0; i < n; i++ {
		array[i] = getString()
	}
	return array
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func powMod(n, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 0 {
		t := powMod(n, p/2)
		return calcMod(t * t)
	} else {
		return calcMod(n * powMod(n, p-1))
	}
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray)-1])
}

func calcMod(x int) int {
	return x % mod
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func isPrime(n int) bool {
	if n < 2 {
		return false
	} else if n == 2 {
		return true
	} else if n%2 == 0 {
		return false
	}

	sqrtN := int(math.Sqrt(float64(n)))
	for i := 3; i <= sqrtN; i += 2 {
		if n%i == 0 {
			return false
		}
	}

	return true
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}

func makeRange(min, max int) []int {
	a := make([]int, max-min+1)
	for i := range a {
		a[i] = min + i
	}
	return a
}

func powerset2(nums []int) [][]int {
	length := int(math.Pow(2, float64(len(nums))))
	result := make([][]int, length)

	index := 0
	result[index] = []int{}
	index++

	for _, n := range nums {
		max := index
		for i := 0; i < max; i++ {
			result[index] = copyAndAppend(result[i], n)
			index++
		}
	}

	return result
}

func copyAndAppend(nums []int, n int) []int {
	dst := make([]int, len(nums)+1)
	copy(dst, nums)
	dst[len(nums)] = n
	return dst
}

func calcGcd(x, y int) int {
	if y == 0 {
		return x
	} else if x >= y {
		return calcGcd(y, x%y)
	} else {
		return calcGcd(x, y%x)
	}
}

func getDivisor(n int) []int {
	divisor := make(map[int]struct{})
	divisor[1] = struct{}{}
	if n != 1 {
		divisor[n] = struct{}{}
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n%i == 0 {
			divisor[i] = struct{}{}
			divisor[n/i] = struct{}{}
		}
	}

	var divisorArray []int
	for d := range divisor {
		divisorArray = append(divisorArray, d)
	}
	return divisorArray
}

type intHeap []int

func (h intHeap) Len() int {
	return len(h)
}

func (h intHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h intHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *intHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *intHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func initHeap() *intHeap {
	ih := &intHeap{}
	heap.Init(ih)
	return ih
}

func (h *intHeap) pushHeap(n int) {
	heap.Push(h, n)
}

func (h *intHeap) popHeap() int {
	return heap.Pop(h).(int)
}

func factMod(n int) int {
	value := 1
	for ; n > 1; n-- {
		value = calcMod(value * n)
	}
	return value
}

func combinationMod(n, k int) int {
	factN := factMod(n)
	factK := factMod(k)
	factNK := factMod(n - k)
	factKR := powMod(factK, mod-2)
	factNKR := powMod(factNK, mod-2)
	return calcMod(factN * calcMod(factKR*factNKR))
}

func primeFactors(n int) []int {
	factors := make([]int, 0)
	i := 2
	for i*i <= n {
		r := n % i
		if r != 0 {
			i += 1
		} else if r == 0 {
			n /= i
			factors = append(factors, i)
		}
	}
	if n > 1 {
		factors = append(factors, n)
	}
	return factors
}