package main

import (
        "fmt"
)

const MAX int = 1000000
var primes [MAX]int

func main() {
        Init()
        var n, cnt int
        for {
                _, err := fmt.Scanf("%d", &n)
                if err != nil {
                        break
                }
                cnt = 0
                for i := 2; i <= n; i++ {
                        cnt += primes[i]
                }
                fmt.Printf("%d\n", cnt)
        }
}

func Init() {
        for i := 0; i < MAX; i++ {
                primes[i] = 1
        }
        primes[0] = 0
        primes[1] = 0
        Soe()
}

func Soe() {
        for i := 2; i < MAX; i++ {
                if primes[i] > 0 {
                        for j := i*2; j < MAX; j+=i {
                                primes[j] = 0
                        }
                }
        }
}

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

Prime Number

Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Input

Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.

The number of datasets is less than or equal to 30.

Output

For each dataset, prints the number of prime numbers.

Sample Input

10
3
11

Output for the Sample Input

4
2
5

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 (
	"container/heap"
	"fmt"
)

type Node struct {
	NowPosition          int
	DiscountTicketTCount int
	Amount               int
}

type PriorityQueueNode []*Node

func (pq PriorityQueueNode) Len() int {
	return len(pq)
}

func (pq PriorityQueueNode) Less(i, j int) bool {
	return pq[i].Amount < pq[j].Amount
}

func (pq PriorityQueueNode) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueueNode) Push(node interface{}) {
	*pq = append(*pq, node.(*Node))
}

func (pq *PriorityQueueNode) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

type Point struct {
	NextPoint int
	Fee       int
}

type Memo struct {
	NowPoint             int
	DiscountTicketTCount int
}

func main() {
	var c, n, m, s, d int
	var a, b, f int

	for {
		fmt.Scan(&c, &n, &m, &s, &d)
		if c == 0 && n == 0 && m == 0 && s == 0 && d == 0 {
			break
		}
		s--
		d--
		pointMap := make([][]Point, n)
		for i := 0; i < n; i++ {
			pointMap[i] = make([]Point, 0, n)
		}
		for i := 0; i < m; i++ {
			fmt.Scan(&a, &b, &f)
			a--
			b--
			pointMap[a] = append(pointMap[a], Point{NextPoint: b, Fee: f})
			pointMap[b] = append(pointMap[b], Point{NextPoint: a, Fee: f})
		}
		pq := make(PriorityQueueNode, 0, m)
		start := Node{NowPosition: s, DiscountTicketTCount: c, Amount: 0}
		heap.Push(&pq, &start)
		memo := make(map[Memo]struct{})
		for len(pq) != 0 {
			now := heap.Pop(&pq).(*Node)
			if now.NowPosition == d {
				fmt.Println(now.Amount)
				break
			}
			memo[Memo{NowPoint: now.NowPosition, DiscountTicketTCount: now.DiscountTicketTCount}] = struct{}{}
			for _, v := range pointMap[now.NowPosition] {
				next := &Node{v.NextPoint, now.DiscountTicketTCount, now.Amount + v.Fee}
				if _, ok := memo[Memo{NowPoint: v.NextPoint, DiscountTicketTCount: now.DiscountTicketTCount}]; !ok {
					heap.Push(&pq, next)
				}
				if now.DiscountTicketTCount > 0 {
					next = &Node{v.NextPoint, now.DiscountTicketTCount - 1, now.Amount + v.Fee/2}
					if _, ok := memo[Memo{NowPoint: v.NextPoint, DiscountTicketTCount: now.DiscountTicketTCount}]; !ok {
						heap.Push(&pq, next)
					}
				}
			}
		}
	}
}

高速バス

A 君は高校の休みを利用して、高速バス(以下、「バス」 )で一人旅をする計画を立てています。まず、A 君は一番行ってみたい町を選んでそこを目的地にしました。次に出発地から目的地までバスを乗り継いでいくルートを決めなければなりません。乗り継ぎをするときは、バスを降りてから別のバスに乗り換えるので、それぞれのバスの乗車券が必要になります。

A 君は親戚のおじさんからバスの割引券を何枚かもらいました。 この券を 1 枚使うと乗車券 1 枚を半額で購入できます。例えば、図 1 の出発地5から目的地1へ行く場合には、5→4→6→2→1と5→3→1の二つの経路が考えられます。割引券が 2 枚あるとすると、交通費を最も安くするには5→4→6→2→1の経路をたどった場合、4→6と6→2の路線に割引を利用し、合計料金は 4600円となります。一方、5→3→1の経路をたどった場合、5→3と3→1の路線に割引を利用し、合計料金は 3750 円となります。

A 君は観光にお金を回したいので、交通費はできるだけ少なくしようと考えています。そこで A 君は、出発地から目的地までの最も安い交通費を求めるプログラムを作成することにしました。

図1

割引券の枚数、バスがつなぐ町の数、バスの路線数、各バスの路線情報を入力とし、出発地から目的地までの最も安い交通費を出力するプログラムを作成してください。各バスは双方向に同一料金で運行しています。また、町の数を n とすると、町にはそれぞれ異なる 1 から n までの番号が振られています。出発地から目的地までの経路は必ず存在するものとします。

Input

複数のデータセットの並びが入力として与えられます。 入力の終わりはゼロが５つの行で示されます。
各データセットは以下の形式で与えられます。

c n m s d
a1 b1 f1
a2 b2 f2
:
am bm fm

1 行目に割引券の枚数 c (1 ≤ c ≤ 10)、バスがつなぐ町の数 n (2 ≤ n ≤ 100)、バスの路線数 m (1 ≤ m ≤ 500)、出発地の町番号 s と目的地の町番号 d (s ≠ d) が与えられます。

続く m 行に第 i のバスの路線情報 ai, bi, fi (1 ≤ ai, bi ≤ n, 1000 ≤ fi ≤ 10000) が与えられます。ai, bi はバスの路線の始点と終点の町番号、fi はこの路線の料金を表す100 刻みの整数です。

データセットの数は 100 を超えません。

Output

入力データセットごとに、最も安い交通費を１行に出力します。

Sample Input

1 3 3 1 3
1 3 2000
1 2 1000
2 3 1000
2 3 3 1 3
1 3 2300
1 2 1000
2 3 1200
2 6 6 5 1
1 2 1500
1 3 4500
2 6 2000
5 4 1000
6 4 2200
3 5 3000
0 0 0 0 0

Output for the Sample Input

1000
1100
3750


package main

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

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

func (s *Scanner) nextStr() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

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

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

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

// Sort
type Val struct {
	id, num int
}
type ByNum []Val

func (a ByNum) Len() int           { return len(a) }
func (a ByNum) Less(i, j int) bool { return a[i].num < a[j].num }
func (a ByNum) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	N, M := sc.nextInt(), sc.nextInt()
	A := sc.nextIntSlice(N)
	B := sc.nextIntSlice(M)
	And := []int{}
	Or := []int{}
	setOr := make(map[int]bool)
	for _, a := range A {
		setOr[a] = true
	}
	for _, b := range B {
		if setOr[b] {
			And = append(And, b)
		}
		setOr[b] = true
	}
	for k, _ := range setOr {
		Or = append(Or, k)
	}
	sort.Ints(Or)
	sort.Ints(And)

	fmt.Fprintln(wtr, len(And), len(Or))
	for _, v := range And {
		fmt.Fprintln(wtr, v)
	}
	for _, v := range Or {
		fmt.Fprintln(wtr, v)
	}
	wtr.Flush()
}

A: 情報検索 / Information Search

問題

ポスティングリストとは、検索語と出現文書 ID の対応関係を持たせたリストである。例えば

北海道: 1, 2, 4, 9

観光: 1, 3, 4, 7

などである。

上記のポスティングリストから、and 検索をすると、ID 1, 4 の文書がヒットし、or 検索をすると、ID 1, 2, 3, 4, 7, 9 がヒットする。

ここで and 検索とは「どちらのリストにも含まれる要素を列挙する」ことであり、 or 検索とは「少なくともどちらか一方のリストに含まれる要素を列挙する」ことである。

ポスティングリストが与えられるので、and 検索と or 検索の結果をそれぞれ出力せよ。

入力形式

n m
a_1 a_2 $\ldots$ a_n
b_1 b_2 $\ldots$ b_m

入力はすべて整数からなる。

1 行目には検索すべき 2 つのポスティングリストの長さ n と m が空白区切りで与えられる。

2 行目と 3 行目にはそれぞれのポスティングリストに含まれる ID が空白区切りで与えられる。

制約

1 \leq n, m \leq 2\times10^5

a_i < a_j (i < j)

b_i < b_j (i < j)

1 \leq a_i, b_i \leq 10^9

出力形式

and 検索のヒット数を A、or 検索のヒット数を B とする。

最初の一行に A B の順に空白区切りで出力せよ。

続く A 行に and 検索でヒットした ID を昇順に出力せよ。

続く B 行に or 検索でヒットした ID を昇順に出力せよ。

入力例1

4 4
1 2 4 9
1 3 4 7

出力例1

2 6
1
4
1
2
3
4
7
9

入力例2

4 4
1 3 5 7
2 4 6 8

出力例2

0 8
1
2
3
4
5
6
7
8

入力例3

3 5
1 2 3
1 2 3 4 5

出力例3

3 5
1
2
3
1
2
3
4
5


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 [][16]byte) bool {

	for _, s := range parents {
		if s == state {
			return false
		}

	}

	if now == limit+1 {
		return false

	}

	if state == goal {
		return true
	}

	parents = append(parents, state)

	ok, ur := up(state)
	if ok {
		var p [][16]byte
		copy(p, parents)
		if dls(limit, now+1, ur, p) {
			return true

		}
	}
	ok, dr := down(state)
	if ok {
		var p [][16]byte
		copy(p, parents)
		if dls(limit, now+1, dr, p) {
			return true

		}
	}
	ok, lr := left(state)
	if ok {
		var p [][16]byte
		copy(p, parents)
		if dls(limit, now+1, lr, p) {
			return true
		}
	}
	ok, rr := right(state)
	if ok {
		var p [][16]byte
		copy(p, parents)
		if dls(limit, now+1, rr, p) {
			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, [][16]byte{}) {
			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"
	"index/suffixarray"
	"os"
)

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

	var s string
	var q int

	fmt.Fscan(r, &s)
	fmt.Fscan(r, &q)

	index := suffixarray.New([]byte(s))

	for i := 0; i < q; i++ {
		var p string
		fmt.Fscan(r, &p)

		res := index.Lookup([]byte(p), 1)
		if len(res) > 0 {
			fmt.Fprintln(w, 1)
		} else {
			fmt.Fprintln(w, 0)
		}
	}
}

String Search

Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i.

Input

In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively.

Output

For each question, print 1 if the text includes P_i, or print 0 otherwise.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P_i ≤ 1000

1 ≤ Q ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
4
aa
ba
bb
xyz

Sample Output 1

1
1
0
0


package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	n := stdin(sc)
	ary := make([]int, n)
	for i := 0; i < n; i++ {
		v := stdin(sc)
		ary[i] = v
	}
	maxv := -math.MaxInt32
	minv := ary[0]
	for i := 1; i < n; i++ {
		maxv = max(maxv, ary[i]-minv)
		minv = min(minv, ary[i])
	}
	fmt.Println(maxv)
}

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

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

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

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

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	num, e := strconv.Atoi(sc.Text())
	if e != nil {
		log.Fatal(e)
	}
	return num
}

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

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

func main() {
	N := scanInt()
	maxv := -1000000000
	minv := scanInt()
	for i := 0; i < N-1; i++ {
		r := scanInt()
		maxv = max(maxv, r-minv)
		minv = min(minv, r)
	}
	fmt.Println(maxv)
}


package main

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

var sc = NewScanner()

func main() {
        n := sc.NextInt()
        minr := sc.NextInt()

        var (
                r   int
                max = int(-1*2e10 - 1)
        )
        for i := 1; i < n; i++ {
                r = sc.NextInt()
                diff := r - minr
                if max < diff {
                        max = diff
                }
                if minr > r {
                        minr = r
                }
        }
        fmt.Println(max)
}

type Scanner struct {
        sc *bufio.Scanner
}

func NewScanner() *Scanner {
        sc := bufio.NewScanner(os.Stdin)
        sc.Split(bufio.ScanWords)
        return &Scanner{sc}
}

func (sc *Scanner) NextInt() int {
        sc.sc.Scan()
        i, err := strconv.Atoi(sc.sc.Text())
        if err != nil {
                panic(err)
        }
        return i
}


package main

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

func main() {
	stdin := bufio.NewScanner(os.Stdin)
	stdin.Scan()
	//n := stdin.Text()
	stdin.Scan()
	s := stdin.Text()
	stdin.Scan()
	//q := stdin.Text()
	stdin.Scan()
	t := stdin.Text()

	cnt := 0
	for _, tv := range strings.Split(t, " ") {
		for _, sv := range strings.Split(s, " ") {
			if tv == sv {
				cnt++
				break
			}
		}
	}
	fmt.Println(cnt)

}

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"
	"fmt"
	"os"
	"strconv"
)

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}
	as, err := nextInts(n, sc)
	if err != nil {
		panic(err)
	}
	q, err := nextInt(sc)
	if err != nil {
		panic(err)
	}
	ms, err := nextInts(q, sc)
	if err != nil {
		panic(err)
	}
	for _, v := range ms {
		if exhaustiveSearch(v, as) {
			fmt.Println("yes")
		} else {
			fmt.Println("no")
		}
	}
}

func exhaustiveSearch(x int, elements []int) bool {
	return solve(x, 0, elements)
}

func solve(target int, index int, elements []int) bool {
	if target == 0 {
		return true
	} else if target < 0 || index >= len(elements) {
		return false
	} else {
		return solve(target-elements[index], index+1, elements) ||
			solve(target, index+1, elements)
	}
}

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

func nextInts(n int, sc *bufio.Scanner) ([]int, error) {
	rs := make([]int, n)
	for i, _ := range rs {
		x, err := nextInt(sc)
		if err != nil {
			return nil, err
		}
		rs[i] = x
	}
	return rs, nil
}

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

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 (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


package main

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

const (
	SENTINEL = 2000000000
)

func main() {
	fmt.Println(answer(os.Stdin))
}

func answer(r io.Reader) int {
	sc := bufio.NewScanner(r)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	A := make([]int, n)
	for i := 0; i < n; i++ {
		sc.Scan()
		A[i], _ = strconv.Atoi(sc.Text())
	}
	return mergeSort(A, n, 0, n)
}

func merge(A []int, n, left, mid, right int) int {
	n1 := mid - left
	n2 := right - mid
	L, R := make([]int, n1+1), make([]int, n2+1)
	for i := 0; i < n1; i++ {
		L[i] = A[left+i]
	}
	for i := 0; i < n2; i++ {
		R[i] = A[mid+i]
	}
	L[n1], R[n2] = SENTINEL, SENTINEL

	cnt := 0
	i, j := 0, 0
	for k := left; k < right; k++ {
		if L[i] <= R[j] {
			A[k] = L[i]
			i++
			continue
		}
		A[k] = R[j]
		j++
		cnt += n1 - i
	}
	return cnt
}

func mergeSort(A []int, n, left, right int) int {
	if left+1 < right {
		mid := (left + right) / 2
		v1 := mergeSort(A, n, left, mid)
		v2 := mergeSort(A, n, mid, right)
		v3 := merge(A, n, left, mid, right)
		return v1 + v2 + v3
	}
	return 0
}

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

The Number of Inversions

For a given sequence $A = \{a_0, a_1, ... a_{n-1}\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
cnt = 0 // the number of inversions
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
swap(A[j], A[j-1])
cnt++

return cnt

For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded.

Input

In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters.

output

Print the number of inversions in a line.

Constraints

$ 1 \leq n \leq 200,000$

$ 0 \leq a_i \leq 10^9$

$a_i$ are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2


package main

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

type Card struct {
	mark  string
	value int
}

func (self Card) Equal(other Card) bool {
	return self.mark == other.mark && self.value == other.value
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}
	cards, err := nextCards(n, sc)
	if err != nil {
		panic(err)
	}
	copied := make([]Card, len(cards))
	copy(copied, cards)
	quickSort(cards)
	sortedByMerge, _ := mergeSort(copied)
	if isEqualCards(cards, sortedByMerge) {
		fmt.Println("Stable")
	} else {
		fmt.Println("Not stable")
	}
	for _, card := range cards {
		fmt.Printf("%s %d\n", card.mark, card.value)
	}
}

func quickSort(cards []Card) {
	if len(cards) > 1 {
		q := partition(cards, 0, len(cards)-1)
		quickSort(cards[:q])
		quickSort(cards[q+1:])
	}
}

func partition(cards []Card, p int, r int) int {
	// fmt.Printf("before: %v\n", cards)
	k := p - 1
	v := cards[r].value
	for i := p; i < r; i++ {
		if cards[i].value <= v {
			k++
			cards[i], cards[k] = cards[k], cards[i]
		}
	}
	k++
	cards[r], cards[k] = cards[k], cards[r]
	// fmt.Printf("after: %v\n", cards)
	return k
}

func mergeSort(elems []Card) ([]Card, int) {
	length := len(elems)
	if length == 1 {
		return elems, 0
	}
	mid := length / 2
	left, countL := mergeSort(elems[:mid])
	right, countR := mergeSort(elems[mid:])
	sorted, countS := merge(left, right)
	return sorted, (countL + countR + countS)
}

func merge(xs, ys []Card) ([]Card, int) {
	sorted := make([]Card, 0)
	count := 0
	for len(xs) > 0 && len(ys) > 0 {
		if xs[0].value <= ys[0].value {
			sorted = append(sorted, xs[0])
			xs = xs[1:]
		} else {
			sorted = append(sorted, ys[0])
			ys = ys[1:]
		}
		count++
	}
	if len(xs) > 0 {
		sorted = append(sorted, xs...)
		count += len(xs)
	} else if len(ys) > 0 {
		sorted = append(sorted, ys...)
		count += len(ys)
	}
	return sorted, count
}

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

func nextText(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func nextCard(sc *bufio.Scanner) (Card, error) {
	mark := nextText(sc)
	value, err := nextInt(sc)
	if err != nil {
		panic(err)
	}
	return Card{mark, value}, nil
}

func nextCards(n int, sc *bufio.Scanner) ([]Card, error) {
	ns := make([]Card, n)
	for i, _ := range ns {
		x, err := nextCard(sc)
		if err != nil {
			return nil, err
		}
		ns[i] = x
	}
	return ns, nil
}

func isEqualCards(x []Card, y []Card) bool {
	if len(x) != len(y) {
		return false
	}
	for i := 0; i < len(x); i++ {
		if !x[i].Equal(y[i]) {
			return false
		}
	}
	return true
}

Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards 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

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


package main

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

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

func scanIntArray() []int {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	n := nextInt(sc)
	result := []int{}
	for i := 0; i < n; i++ {
		result = append(result, nextInt(sc))
	}

	return result
}

type Input struct {
	id    int
	left  int
	right int
}

type Element struct {
	id      int
	parent  int
	sibling int
	degree  int
	depth   int
	height  int
	left    *Element
	right   *Element
}

var maxDepth int
var elements []Element

func main() {
	// assemble input
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	n := nextInt(sc)
	inputs := []Input{}

	inputTable := NewHashTable()
	childTable := NewHashTable()

	for i := 0; i < n; i++ {
		id := nextInt(sc)
		left := nextInt(sc)
		right := nextInt(sc)
		input := Input{id, left, right}
		inputs = append(inputs, input)
		inputTable.Put(id, input)
		childTable.Put(input.left, true)
		childTable.Put(input.right, true)
	}

	// find root
	var rootInput Input
	for _, input := range inputs {
		_, exist := childTable.Find(input.id)
		if !exist {
			rootInput = input
			break
		}
	}

	// assemble tree
	leftElement := Element{id: rootInput.left}
	rightElement := Element{id: rootInput.right}
	rootElement := Element{id: rootInput.id, parent: -1, sibling: -1, depth: 0, left: &leftElement, right: &rightElement}

	assembleTree(&rootElement, inputTable)

	// print
	flat(rootElement)
	sort.Slice(elements, func(i, j int) bool {
		return elements[i].id < elements[j].id
	})

	for _, elem := range elements {
		printElement(elem)
	}
}

func printElement(element Element) {
	if element.id == -1 {
		return
	}
	degree := 0
	if element.left.id != -1 {
		degree++
	}
	if element.right.id != -1 {
		degree++
	}

	height := getMaxDepthLeaf(element, element.depth) - element.depth

	elementType := "root"
	if element.parent != -1 {
		if element.left.id != -1 || element.right.id != -1 {
			elementType = "internal node"
		} else {
			elementType = "leaf"
		}
	}

	fmt.Printf("node %v: parent = %v, sibling = %v, degree = %v, depth = %v, height = %v, %v\n",
		element.id, element.parent, element.sibling, degree, element.depth, height, elementType)

}

func getMaxDepthLeaf(element Element, maxDepth int) int {
	max := maxDepth
	if element.left.depth > max {
		max = element.left.depth
	}

	if element.right.depth > max {
		max = element.right.depth
	}

	if element.left.id != -1 {
		left := getMaxDepthLeaf(*element.left, max)
		if left > max {
			max = left
		}
	}

	if element.right.id != -1 {
		right := getMaxDepthLeaf(*element.right, max)
		if right > max {
			max = right
		}
	}

	return max
}

func flat(element Element) {
	elements = append(elements, element)
	if element.left != nil {
		flat(*element.left)
	}
	if element.right != nil {
		flat(*element.right)
	}
}

func assembleTree(element *Element, inputTable HashTable) {
	if element.depth > maxDepth {
		maxDepth = element.depth
	}

	// assemble left and children of left
	if element.left.id != -1 {
		leftInputOrg, _ := inputTable.Find(element.left.id)
		leftInput := leftInputOrg.(Input)
		leftElement := Element{id: element.left.id,
			left:    &Element{id: leftInput.left, sibling: leftInput.right},
			right:   &Element{id: leftInput.right, sibling: leftInput.left},
			depth:   element.depth + 1,
			parent:  element.id,
			sibling: element.right.id}
		element.left = &leftElement
		assembleTree(&leftElement, inputTable)
	}

	// assemble right and children of right
	if element.right.id != -1 {
		rightInputOrg, _ := inputTable.Find(element.right.id)
		rightInput := rightInputOrg.(Input)
		rightElement := Element{id: element.right.id,
			left:    &Element{id: rightInput.left, sibling: rightInput.right},
			right:   &Element{id: rightInput.right, sibling: rightInput.left},
			depth:   element.depth + 1,
			parent:  element.id,
			sibling: element.left.id}

		element.right = &rightElement
		assembleTree(&rightElement, inputTable)
	}
}

// ======= Hashtable =======

// HashTable is HashTables
type HashTable struct {
	hashtable []*element
	length    int
}

type element struct {
	key int
	val interface{}
}

// NewHashTable generate HashTable
func NewHashTable() HashTable {
	length := 1046527
	return HashTable{make([]*element, length), length}
}

// Put new value
func (h *HashTable) Put(key int, val interface{}) {
	new := element{key, val}
	hash := abs(key % h.length)

	index := 0
	for {
		// double hash
		if h.hashtable[((1+hash%(h.length-1))*index+hash)%h.length] == nil {
			h.hashtable[((1+hash%(h.length-1))*index+hash)%h.length] = &new
			break
		} else {
			index++
		}
	}
}

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

// Find new value
func (h *HashTable) Find(key int) (val interface{}, ok bool) {
	hash := abs(key % h.length)
	index := 0
	for {
		target := h.hashtable[((1+hash%(h.length-1))*index+hash)%h.length]
		if target == nil {
			return Input{}, false
		}

		if target.key == key {
			return h.hashtable[((1+hash%(h.length-1))*index+hash)%h.length].val, true
		}
		index++
	}
}

Binary Tree

A rooted binary tree is a tree with a root node in which every node has at most two children.

Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:

node ID of u

parent of u

sibling of u

the number of children of u

depth of u

height of u

node type (root, internal node or leaf)

If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.

Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.

Output

Print the information of each node in the following format:

node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type

p is ID of its parent. If the node does not have a parent, print -1.

s is ID of its sibling. If the node does not have a sibling, print -1.

deg, dep and h are the number of children, depth and height of the node respectively.

type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 25

Sample Input 1

9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

Sample Output 1

node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf

Reference

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


package main

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

type Node struct {
	value int
	left *Node
	right *Node
}

/****************************************************************
*関数insert():													*
*	 挿入される二分探索木のrootノードを表すポインタrootと				*
*	 挿入したいノードのvalueを引数に、適切な葉に新たなノードを挿入して、	*
*	 挿入された二分探索木のルートノードのポインタを返す関数				*
*****************************************************************/
func insert(root *Node, val int) *Node {

	// 二分探索木がまだ構築されていないときはここが呼び出される
	if root == nil {
		return &Node{val, nil,nil}
	}

	// すでにある二分探索木に対するノード（value: val）を挿入する
	// ここを抜けるとparentに挿入されるノードの親へのポインタが入っている
	// 変数nodeは、挿入すべき場所を探すための一時的なポインタ変数
	var parent *Node
	node := root
	for node != nil {
		parent = node
		if node.value > val {
			node = node.left
		} else {
			node = node.right
		}
	}

	// 新たなノードの挿入を実行
	if parent.value > val {
		parent.left = &Node{val, nil,nil}
	} else {
		parent.right = &Node{val, nil, nil}
	}

	// 二分探索木の根は変わらないのでそのまま返す
	return root
}

func printNodes(nodes []int) {
	// 木の走査によって得られたint型スライスを引数に、
	// 指定されたフォーマットに出力する関数
	writer := bufio.NewWriter(os.Stdout)
	for _, v := range nodes{
		writer.Write([]byte(fmt.Sprintf(" %d", v)))
	}
	writer.Write([]byte("\n"))
	writer.Flush()
}

func preorder(root *Node, memo []int) []int {
	// 引数rootが根となっている二分探索木に対して先行巡回によって
	// 各ノードをを舐めて、引数memoで与えられる空のスライスに書き込み、
	// 書き込まれた後のスライスを返す関数
	if root != nil {
		memo = append(memo, root.value)
		memo = preorder(root.left, memo)
		memo = preorder(root.right, memo)
	}
	return memo
}

func inorder(root *Node, memo []int) []int {
	// 引数rootが根となっている二分探索木に対して中間巡回によって
	// 各ノードをを舐めて、引数memoで与えられる空のスライスに書き込み、
	// 書き込まれた後のスライスを返す関数
	if root != nil {
		memo = inorder(root.left, memo)
		memo = append(memo, root.value)
		memo = inorder(root.right, memo)
	}
	return memo
}

/****************************************************************
*関数find():														*
*	 探索対象の二分探索木のrootノードを表すポインタrootと				*
*	 探したいノードのtargetを引数に、								*
*	 存在すればtrueを、なければfalseを返す関数						*
*****************************************************************/
func find(root *Node, target int) bool {
	switch {
	//　rootを根とする二分探索木が未構築
	case root == nil:
		return false
	case root.value == target:
		return true
	case root.value > target:
		return find(root.left, target)
	default:
		return find(root.right, target)
	}
}

func main() {
	var n int
	var root *Node
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	n, _  = strconv.Atoi(scanner.Text())
	for i := 0; i < n; i++ {
		scanner.Scan()
		operation := scanner.Text()
		switch operation {
		case "insert":
			scanner.Scan()
			value, _ := strconv.Atoi(scanner.Text())
			root = insert(root, value)
		case "print":
			printNodes(inorder(root, []int{}))
			printNodes(preorder(root, []int{}))
		case "find":
			scanner.Scan()
			target, _ := strconv.Atoi(scanner.Text())
			if find(root, target) {
				fmt.Println("yes")
			} else {
				fmt.Println("no")
			}
		default:
			panic("No such operation!")
		}
	}
}

Binary Search Tree II

Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

10
insert 30
insert 88
insert 12
insert 1
insert 20
find 12
insert 17
insert 25
find 16
print

Sample Output 1

yes
no
1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

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


package main

import (
	"fmt"
	"sort"
)

var n int

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

	var arr []int
	for i := 0; i < n; i++ {
		var a int
		fmt.Scan(&a)
		arr = append(arr, a)
	}

	var lis []int
	lis = append(lis, arr[0])
	for i := 1; i < len(arr); i++ {
		if val, last := arr[i], lis[len(lis)-1]; val == last {
		} else if last < val {
			lis = append(lis, val)
		} else {
			f := func(j int) bool {
				return val < lis[j]
			}
			index := sort.Search(len(lis), f)
			if index == 0 || lis[index-1] != val {
				lis[index] = val
			}
		}
	}
	fmt.Println(len(lis))
}

Longest Increasing Subsequence

For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.

An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.

Input

n
a0
a1
:
an-1

In the first line, an integer n is given. In the next n lines, elements of A are given.

Output

The length of the longest increasing subsequence of A.

Constraints

1 ≤ n ≤ 100000

0 ≤ ai ≤ 109

Sample Input 1

5
5
1
3
2
4

Sample Output 1

3

Sample Input 2

3
1
1
1

Sample Output 2

1


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
  for i := 1; ; i++ {
    data := nextInt()
    if data == 0 {
      break
    }
    fmt.Printf("Case %d: %d\n", i, data)
  }
}

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


package main

import "fmt"

func main() {
	for i := 1; ; i++ {
		var x, y int
		fmt.Scan(&x)
		fmt.Scan(&y)
		if x == 0 && y == 0 {
			break
		}
		if x < y {
			fmt.Println(x, y)
		} else {
			fmt.Println(y, x)
		}
	}
}

Swapping Two Numbers

Write a program which reads two integers x and y, and prints them in ascending order.

Input

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

The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print x and y in ascending order in a line. Put a single space between x and y.

Constraints

0 ≤ x, y ≤ 10000

the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5


package main

import (
	"fmt"
)

func main() {

	var r, c int

	fmt.Scanf("%d%d", &r, &c)

	var rowcol [][]int

	for i := 0; i < r; i++ {

		var row []int

		for j := 0; j < c; j++ {
			var val int
			fmt.Scanf("%d", &val)

			row = append(row, val)
		}

		rowcol = append(rowcol, row)
	}

	for i := 0; i < r; i++ {

		colsum := 0

		for j := 0; j < c; j++ {
			fmt.Printf("%d ", rowcol[i][j])
			colsum += rowcol[i][j]
		}

		fmt.Println(colsum)

	}

	sum := 0

	for j := 0; j < c; j++ {
		rowsum := 0
		for i := 0; i < r; i++ {
			rowsum += rowcol[i][j]
		}

		sum += rowsum

		fmt.Printf("%d ", rowsum)
	}

	fmt.Println(sum)
}

Spreadsheet

Your task is to perform a simple table calculation.

Write a program which reads the number of rows r, columns c and a table of r × c elements, and prints a new table, which includes the total sum for each row and column.

Input

In the first line, two integers r and c are given. Next, the table is given by r lines, each of which consists of c integers separated by space characters.

Output

Print the new table of (r+1) × (c+1) elements. Put a single space character between adjacent elements. For each row, print the sum of it's elements in the last column. For each column, print the sum of it's elements in the last row. Print the total sum of the elements at the bottom right corner of the table.

Constraints

1 ≤ r, c ≤ 100

0 ≤ an element of the table ≤ 100

Sample Input

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

Sample Output

1 1 3 4 5 14
2 2 2 4 5 15
3 3 0 1 1 8
2 3 4 4 6 19
8 9 9 13 17 56


package main

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

func nextInt(sc *bufio.Scanner) int {
	sc.Scan()
	t, _ := strconv.Atoi(sc.Text())
	return t
}
func nextString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}
func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	q := nextInt(sc)
	ans := make([]int, 0)
	m := make(map[string]int)
	for i := 0; i < q; i++ {
		t := nextInt(sc)
		k := nextString(sc)
		if t == 0 {
			x := nextInt(sc)
			m[k] = x
		} else {
			ans = append(ans, m[k])
		}
	}
	wtr := bufio.NewWriter(os.Stdout)
	for i := 0; i < len(ans); i++ {
		fmt.Fprintln(wtr, ans[i])
	}
	wtr.Flush()
}

Map: Search

For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.

insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.

get($key$): Print the value with the specified $key$.

Input

The input is given in the following format.

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

Each query $query_i$ is given by

0 $key$ $x$

or

1 $key$

where the first digits 0, 1 and 2 represent insert and get operations respectively.

Output

For each get operation, print an integer in a line.

Constraints

$1 \leq q \leq 200,000$

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

$1 \leq $ length of $key$ $ \leq 20$

$key$ consits of lower-case letter

For a get operation, the element with the specified key exists in $M$.

Sample Input 1

7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black

Sample Output 1

1
4
8


package main

import "fmt"

func main() {
	var a, b, c, d int
	fmt.Scan(&a, &b, &c, &d)

	if a <= d && c <= b {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

Score : 100 points

Problem Statement

You are given an integer K.
Print the string obtained by repeating the string ACL K times and concatenating them.

For example, if K = 3, print ACLACLACL.

Constraints

1 \leq K \leq 5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string ACL K times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL


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)
  }

  //can := make([][]bool, n)
  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:= 0; 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 process(in string) (ret string) {
	if tail := in[len(in)-1 : len(in)]; tail != "s" {
		ret = in + "s"
	} else {
		ret = in + "es"
	}
	return
}

func main() {
	var in string
	fmt.Scanln(&in)

	ret := process(in)
	fmt.Println(ret)
}

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


package main

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

const (
	initialBufSize = 1e4
	maxBufSize     = 1e6 + 7
)

var buf []byte = make([]byte, initialBufSize)
var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(buf, maxBufSize)
}

var d = []Position{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
var d8 = []Position{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}

// 問題によって値は調整する
const (
	mod     = int(1e9) + 7
	maxsize = 51000
)

func main() {
	N := nextInt()
	var ans int
	sieve := MakeSieve(N)
	for i := 1; i < N; i++ {
		pf := FastPrimeFactorize(N-i, sieve)
		sum := 1
		for _, v := range pf {
			sum *= v + 1
		}
		ans += sum
	}
	fmt.Println(ans)
}

func cntDivisors(N int) int {
	var res int
	for i := 1; i*i <= N; i++ {
		if N%i == 0 {
			res++
			if N/i != i {
				res++
			}
		}
	}
	return res
}

// Position として迷路問題での現在地を表す構造体を定義
type Position struct {
	H int
	W int
}

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

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

// Math Utilities
// https://play.golang.org/p/bm7uZi0zCN

// Abs Absolute Value
func Abs(a int) int {
	if a > 0 {
		return a
	}
	return -a
}

// Pow Integer power: compute a**b using binary powering algorithm
// See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3
func Pow(a, b int) int {
	p := 1
	for b > 0 {
		if b&1 != 0 {
			p *= a
		}
		b >>= 1
		a *= a
	}
	return p
}

// PowMod Modular integer power: compute a**b mod m using binary powering algorithm
func PowMod(a, b, m int) int {
	a = a % m
	p := 1 % m
	for b > 0 {
		if b&1 != 0 {
			p = (p * a) % m
		}
		b >>= 1
		a = (a * a) % m
	}
	return p
}

func ceil(a, b int) int {
	return (a + (b - 1)) / b
}

// MinOf 与えられたintのうち最小のものを返す
func MinOf(vars ...int) int {
	min := vars[0]
	for _, i := range vars {
		if min > i {
			min = i
		}
	}
	return min
}

// MaxOf 与えられたintのうち最大のものを返す
func MaxOf(vars ...int) int {
	max := vars[0]
	for _, i := range vars {
		if max < i {
			max = i
		}
	}
	return max
}

func gcdof2numbers(a int, b int) int {
	if b == 0 {
		return a
	}
	return gcdof2numbers(b, a%b)
}

func lcmof2numbers(a int, b int) int {
	return a / gcdof2numbers(a, b) * b
}

// マイナスの場合は考慮していない
func fuctorial(a int) int {
	if a == 1 || a == 0 {
		return 1
	} else {
		return fuctorial(a-1) * a
	}
}

// NextPermutation はsortインターフェース（要はソート済みスライス）から次の順列にスライスを並べ替える
// https://play.golang.org/p/ljft9xhOEn
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}

// PrimeFactorize 素因数分解したmapを返す
func PrimeFactorize(n int) map[int]int {
	pf := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			pf[i]++
			n /= i
		}
	}
	if n != 1 {
		pf[n]++
	}
	return pf
}

// FastPrimeFactorize osa_k法を使った高速素因数分解
// sieveを作るところのjはi*2スタートでもよい？
// https://qiita.com/rsk0315_h4x/items/ff3b542a4468679fb409
func FastPrimeFactorize(n int, sieve []int) map[int]int {
	pf := make(map[int]int)
	for n > 1 {
		pf[sieve[n]]++
		n /= sieve[n]
	}
	return pf
}

// MakeSieve は高速素数判定に使う篩を作る。
// Sieve[i] < i なら合成数なので、Sieveは素数判定にも使える
func MakeSieve(max int) []int {
	sieve := make([]int, max)
	for i := range sieve {
		sieve[i] = i
	}
	for i := 2; i*i <= max; i++ {
		if sieve[i] == i {
			for j := i; j < max; j += i {
				if sieve[j] == j {
					sieve[j] = i
				}
			}
		}
	}
	return sieve
}

// IH golangの公式サンプルより
// https://xn--go-hh0g6u.com/pkg/container/heap/#example__intHeap
// IntHeap は，整数の最小ヒープです。
type IH []int

func (h IH) Len() int           { return len(h) }
func (h IH) Less(i, j int) bool { return h[i] < h[j] }
func (h IH) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IH) Push(x interface{}) {
	// Push と Pop はポインタレシーバを使っています。
	// なぜなら，スライスの中身だけでなく，スライスの長さも変更するからです。
	*h = append(*h, x.(int))
}

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

// golangの公式サンプルより
// https://xn--go-hh0g6u.com/pkg/container/heap/#example__priorityQueue

// Item は，優先キューで管理する項目です。
type Item struct {
	value    string // 値。任意です。
	priority int    // キューにおける優先度
	// index は heap.Interface メソッドで更新されます。
	index int // ヒープにおけるインデックス
}

// PriorityQueue は heap.Interface を実装し，Item のリストを保持します。
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// Pop が最小ではなく最大の優先度を持つ項目を返して欲しいので，ここでは > を使っています。
	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
}

// update はキューの Item の優先度と値を更新します。
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

// UnionFind の定義
// 下記を参考
// https://youtu.be/TdR816rqc3s?t=6822
// https://github.com/atcoder/live_library/blob/master/uf.cpp
// https://qiita.com/haru1843/items/2295d0ec1f5002bd5c33#%E5%AE%9F%E8%A3%85
type UnionFind struct {
	parent []int
	maxlen int
}

// UnionFind のスライス初期化
func newUnionFind(N int) *UnionFind {
	u := new(UnionFind)
	u.parent = make([]int, N)
	u.maxlen = 1
	for i := range u.parent {
		u.parent[i] = -1
	}
	return u
}

// xの根を見つける
func (u *UnionFind) find(x int) int {
	if u.parent[x] < 0 {
		return x
	}
	u.parent[x] = u.find(u.parent[x])
	return u.parent[x]
}

// xとyのグループを結合する
func (u *UnionFind) unite(x, y int) {
	xf := u.find(x)
	yf := u.find(y)
	if xf == yf {
		return
	}
	// 常に大きい方に小さい木をくっつける
	if xf > yf {
		xf, yf = yf, xf
	}
	u.parent[xf] += u.parent[yf]
	u.parent[yf] = xf
	if u.parent[xf] < 0 {
		u.maxlen = MaxOf(u.maxlen, Abs(u.parent[xf]))
	}
}

// xとyが同じグループに所属するかどうかを返す
func (u *UnionFind) same(x, y int) bool {
	if u.find(x) == u.find(y) {
		return true
	}
	return false
}

// xの所属するグループの木の大きさを返す
func (u *UnionFind) size(x int) int {
	return -u.parent[u.find(x)]
}

// 根の数を返す
func (u UnionFind) rootcnt() int {
	var cnt int
	for _, v := range u.parent {
		if v < 0 {
			cnt++
		}
	}
	return cnt
}

// COMで使うスライス
var fac = make([]int, maxsize)
var finv = make([]int, maxsize)
var inv = make([]int, maxsize)

// COMinit で COMで使うためのテーブルを作る前処理
// O(N)
// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a#5-%E4%BA%8C%E9%A0%85%E4%BF%82%E6%95%B0-ncr
func COMinit() {
	fac[0], fac[1] = 1, 1
	finv[0], finv[1] = 1, 1
	inv[1] = 1
	for i := 2; i < maxsize; i++ {
		fac[i] = fac[i-1] * i % mod
		inv[i] = mod - inv[mod%i]*(mod/i)%mod
		finv[i] = finv[i-1] * inv[i] % mod
	}
}

// COM nCkを求める。COMinitを先に実行する
// COMinitの結果を使ってO(1)で行える
func COM(n, k int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % mod) % mod
}

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


package main

import (
	"fmt"
	"math"
)

func main() {
	var n float64
	fmt.Scan(&n)
	cnt := 0
	for c := float64(n - 1); c >= 1; c-- {
		max := math.Floor(math.Sqrt(n - c))
		for a := float64(1); a <= max; a++ {
			b := (n - c) / a
			if b == math.Floor(b) {
				if a != b {
					cnt += 2
				} else {
					cnt++
				}
			}
		}
	}
	fmt.Println(cnt)
}


package main

import (
	"fmt"
)

func main() {
	var n int

	fmt.Scanf("%d", &n)

	total := 0
	var a, b, c, tmp int
	for a = 1; a < n; a++ {
		for b = 1; b < n; b++ {
			tmp = a * b
			for c = n - tmp; c >= 1; c-- {
				if tmp+c == n {
					total++
				}
			}
		}
	}
	fmt.Println(total)
}


package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	numT := scanner.Text()
	num, _ := strconv.ParseInt(numT, 10, 64)
	n := int(num)
	c := 0

	for i := 0; i < n; i++ {
		target := n - i

		for j := 1; j < target; j++ {
			k := target / j
			if k*j == target {
				c++
			}
		}
	}

	fmt.Println(c)
}


package main

import "fmt"

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

	ans := 0
	ss := make(map[int]int)
	done := make(map[int]int)
	a := x
	ss[1] = a
	done[a] = 1
	ans += a
	for i := 2; i <= n; i++ {
		a = ((a % m) * a) % m
		ss[i] = ss[i-1] + a
		if done[a] > 0 {
			l, r := done[a], i
			s := ss[r-1] - ss[l-1]
			rem := n - r + 1
			sl := r - l
			ans += s * (rem / sl)

			x := rem % sl
			ans += ss[l+x-1] - ss[l-1]
			break
		}
		done[a] = i
		ans += a
	}
	fmt.Println(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 n int
  fmt.Scan(&n)
  if n == 0 {
    fmt.Println("1")
  } else {
    fmt.Println("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 (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"sort"
	"strconv"
)

const (
	initialBufSize = 1e4
	maxBufSize     = 1e6 + 7
)

var buf []byte = make([]byte, initialBufSize)
var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(buf, maxBufSize)
}

var d = []Position{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
var d8 = []Position{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}

// 問題によって値は調整する
const (
	mod     = int(1e9) + 7
	maxsize = 51000
)

func main() {
	N := nextInt()
	var ans int
	ans = PowMod(10, N, mod) - PowMod(9, N, mod) - PowMod(9, N, mod) + PowMod(8, N, mod)
	fmt.Println(ans)
}

// Position として迷路問題での現在地を表す構造体を定義
type Position struct {
	H int
	W int
}

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

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

// Math Utilities
// https://play.golang.org/p/bm7uZi0zCN

// Abs Absolute Value
func Abs(a int) int {
	if a > 0 {
		return a
	}
	return -a
}

// Pow Integer power: compute a**b using binary powering algorithm
// See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3
func Pow(a, b int) int {
	p := 1
	for b > 0 {
		if b&1 != 0 {
			p *= a
		}
		b >>= 1
		a *= a
	}
	return p
}

// PowMod Modular integer power: compute a**b mod m using binary powering algorithm
func PowMod(a, b, m int) int {
	a = a % m
	p := 1 % m
	for b > 0 {
		if b&1 != 0 {
			p = (p * a) % m
		}
		b >>= 1
		a = (a * a) % m
	}
	return p
}

func ceil(a, b int) int {
	return (a + (b - 1)) / b
}

// MinOf 与えられたintのうち最小のものを返す
func MinOf(vars ...int) int {
	min := vars[0]
	for _, i := range vars {
		if min > i {
			min = i
		}
	}
	return min
}

// MaxOf 与えられたintのうち最大のものを返す
func MaxOf(vars ...int) int {
	max := vars[0]
	for _, i := range vars {
		if max < i {
			max = i
		}
	}
	return max
}

func gcdof2numbers(a int, b int) int {
	if b == 0 {
		return a
	}
	return gcdof2numbers(b, a%b)
}

func lcmof2numbers(a int, b int) int {
	return a / gcdof2numbers(a, b) * b
}

// マイナスの場合は考慮していない
func fuctorial(a int) int {
	if a == 1 || a == 0 {
		return 1
	} else {
		return fuctorial(a-1) * a
	}
}

// NextPermutation はsortインターフェース（要はソート済みスライス）から次の順列にスライスを並べ替える
// https://play.golang.org/p/ljft9xhOEn
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}

// PrimeFactorize 素因数分解したmapを返す
func PrimeFactorize(n int) map[int]int {
	pf := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			pf[i]++
			n /= i
		}
	}
	if n != 1 {
		pf[n]++
	}
	return pf
}

// FastPrimeFactorize osa_k法を使った高速素因数分解
// sieveを作るところのjはi*2スタートでもよい？
// https://qiita.com/rsk0315_h4x/items/ff3b542a4468679fb409
func FastPrimeFactorize(n int, sieve []int) map[int]int {
	pf := make(map[int]int)
	for n > 1 {
		pf[sieve[n]]++
		n /= sieve[n]
	}
	return pf
}

// MakeSieve は高速素数判定に使う篩を作る。
// Sieve[i] < i なら合成数なので、Sieveは素数判定にも使える
func MakeSieve(max int) []int {
	sieve := make([]int, max)
	for i := range sieve {
		sieve[i] = i
	}
	for i := 2; i*i <= max; i++ {
		if sieve[i] == i {
			for j := i; j < max; j += i {
				if sieve[j] == j {
					sieve[j] = i
				}
			}
		}
	}
	return sieve
}

// IH golangの公式サンプルより
// https://xn--go-hh0g6u.com/pkg/container/heap/#example__intHeap
// IntHeap は，整数の最小ヒープです。
type IH []int

func (h IH) Len() int           { return len(h) }
func (h IH) Less(i, j int) bool { return h[i] < h[j] }
func (h IH) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IH) Push(x interface{}) {
	// Push と Pop はポインタレシーバを使っています。
	// なぜなら，スライスの中身だけでなく，スライスの長さも変更するからです。
	*h = append(*h, x.(int))
}

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

// golangの公式サンプルより
// https://xn--go-hh0g6u.com/pkg/container/heap/#example__priorityQueue

// Item は，優先キューで管理する項目です。
type Item struct {
	value    string // 値。任意です。
	priority int    // キューにおける優先度
	// index は heap.Interface メソッドで更新されます。
	index int // ヒープにおけるインデックス
}

// PriorityQueue は heap.Interface を実装し，Item のリストを保持します。
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// Pop が最小ではなく最大の優先度を持つ項目を返して欲しいので，ここでは > を使っています。
	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
}

// update はキューの Item の優先度と値を更新します。
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

// UnionFind の定義
// 下記を参考
// https://youtu.be/TdR816rqc3s?t=6822
// https://github.com/atcoder/live_library/blob/master/uf.cpp
// https://qiita.com/haru1843/items/2295d0ec1f5002bd5c33#%E5%AE%9F%E8%A3%85
type UnionFind struct {
	parent []int
	maxlen int
}

// UnionFind のスライス初期化
func newUnionFind(N int) *UnionFind {
	u := new(UnionFind)
	u.parent = make([]int, N)
	u.maxlen = 1
	for i := range u.parent {
		u.parent[i] = -1
	}
	return u
}

// xの根を見つける
func (u *UnionFind) find(x int) int {
	if u.parent[x] < 0 {
		return x
	}
	u.parent[x] = u.find(u.parent[x])
	return u.parent[x]
}

// xとyのグループを結合する
func (u *UnionFind) unite(x, y int) {
	xf := u.find(x)
	yf := u.find(y)
	if xf == yf {
		return
	}
	// 常に大きい方に小さい木をくっつける
	if xf > yf {
		xf, yf = yf, xf
	}
	u.parent[xf] += u.parent[yf]
	u.parent[yf] = xf
	if u.parent[xf] < 0 {
		u.maxlen = MaxOf(u.maxlen, Abs(u.parent[xf]))
	}
}

// xとyが同じグループに所属するかどうかを返す
func (u *UnionFind) same(x, y int) bool {
	if u.find(x) == u.find(y) {
		return true
	}
	return false
}

// xの所属するグループの木の大きさを返す
func (u *UnionFind) size(x int) int {
	return -u.parent[u.find(x)]
}

// 根の数を返す
func (u UnionFind) rootcnt() int {
	var cnt int
	for _, v := range u.parent {
		if v < 0 {
			cnt++
		}
	}
	return cnt
}

// COMで使うスライス
var fac = make([]int, maxsize)
var finv = make([]int, maxsize)
var inv = make([]int, maxsize)

// COMinit で COMで使うためのテーブルを作る前処理
// O(N)
// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a#5-%E4%BA%8C%E9%A0%85%E4%BF%82%E6%95%B0-ncr
func COMinit() {
	fac[0], fac[1] = 1, 1
	finv[0], finv[1] = 1, 1
	inv[1] = 1
	for i := 2; i < maxsize; i++ {
		fac[i] = fac[i-1] * i % mod
		inv[i] = mod - inv[mod%i]*(mod/i)%mod
		finv[i] = finv[i-1] * inv[i] % mod
	}
}

// COM nCkを求める。COMinitを先に実行する
// COMinitの結果を使ってO(1)で行える
func COM(n, k int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % mod) % mod
}

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 = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

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

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

const DIV uint64 = 1e9 + 7

func pow(a uint64, n int) uint64 {
	if n == 0 {
		return 1
	} else if n%2 == 0 {
		p := pow(a, n/2)
		return p * p % DIV
	} else {
		p := pow(a, n/2)
		return a * p * p % DIV
	}
}

func main() {
	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)
	defer out.Flush()

	N := nextInt()
	ans := (2*DIV + pow(10, N) - 2*pow(9, N) + pow(8, N)) % DIV
	fmt.Fprintf(out, "%d\n", ans)
}


package main

import (
	"bufio"
	"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 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 := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	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 bOutput(f bool, x string, y string) {
	if f {
		fmt.Println(x)
	} else {
		fmt.Println(y)
	}
}
func mod(x, d int) int {
	x %= d
	if x < 0 {
		x += d
	}
	return x
}
func iSSPrint(x []int) {
	fmt.Println(strings.Trim(fmt.Sprint(x), "[]"))
}

var lp int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, lp)
	sc.Split(bufio.ScanWords)
	n, q := iScan(), iScan()
	uf := newUF(n)
	for i := 0; i < q; i++ {
		t, u, v := iScan(), iScan(), iScan()
		if t == 0 {
			uf.unite(u, v)
		} else {
			bOutput(uf.same(u, v), "1", "0")
		}
	}
}

type UnionFind struct {
	par []int
}

func newUF(n int) *UnionFind {
	uf := new(UnionFind)
	uf.par = make([]int, n)
	for i, _ := range uf.par {
		uf.par[i] = -1
	}
	return uf
}
func (uf UnionFind) root(x int) int {
	if uf.par[x] < 0 {
		return x
	}
	uf.par[x] = uf.root(uf.par[x])
	return uf.par[x]
}
func (uf UnionFind) unite(x, y int) {
	rx, ry := uf.root(x), uf.root(y)
	if rx != ry {
		uf.par[ry] += uf.par[rx]
		uf.par[rx] = ry
	}
}
func (uf UnionFind) same(x, y int) bool {
	return uf.root(x) == uf.root(y)
}
func (uf UnionFind) size(x int) int {
	return -uf.par[uf.root(x)]
}

Score : 100 points

Problem Statement

You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.

0 u v: Add an edge (u, v).

1 u v: Print 1 if u and v are in the same connected component, 0 otherwise.

Constraints

1 \leq N \leq 200,000

1 \leq Q \leq 200,000

0 \leq u_i, v_i \lt N

Input

Input is given from Standard Input in the following format:

N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q

出力

For each query of the latter type, print the answer.

Sample Input 1

4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3

Sample Output 1

0
1
0
1


package main

import (
	"bufio"
	"fmt"
	"math/bits"
	"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 := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	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()
	a, b := iSScan(n), iSScan(m)
	iSSPrint(convolution(a, b, lp2))
}
func ceilPow2(n int) int {
	x := 0
	for (1 << uint(x)) < n {
		x++
	}
	return x
}
func bsf(n uint) int {
	return bits.TrailingZeros(n)
}
func primitiveRoot(m int) int {
	if m == 2 {
		return 1
	} else if m == 167772161 {
		return 3
	} else if m == 469762049 {
		return 3
	} else if m == 754974721 {
		return 11
	} else if m == 998244353 {
		return 3
	}
	divs := make([]int, 20)
	divs[0] = 2
	cnt := 1
	x := (m - 1) / 2
	for (x % 2) == 0 {
		x /= 2
	}
	for i := 3; i*i <= x; i += 2 {
		if x%i == 0 {
			divs[cnt] = i
			cnt++
			for x%i == 0 {
				x /= i
			}
		}
	}
	if x > 1 {
		divs[cnt] = x
		cnt++
	}
	for g := 2; ; g++ {
		ok := true
		for i := 0; i < cnt; i++ {
			if powMod(g, (m-1)/divs[i], m) == 1 {
				ok = false
				break
			}
		}
		if ok {
			return g
		}
	}
}
func powMod(x, n, m int) int {
	if m == 1 {
		return 0
	}
	r := 1
	y := x % m
	if y < 0 {
		y += m
	}
	for n != 0 {
		if (n & 1) == 1 {
			r = (r * y) % m
		}
		y = (y * y) % m
		n >>= 1
	}
	return r
}
func butterfly(a []int, prm int) {
	g := primitiveRoot(prm)
	n := len(a)
	h := ceilPow2(n)
	first := true
	se := make([]int, 30)
	if first {
		first = false
		es, ies := make([]int, 30), make([]int, 30)
		cnt2 := bsf(uint(prm - 1))
		e := powMod(g, (prm-1)>>uint(cnt2), prm)
		ie := invGcd(e, prm)[1]
		for i := cnt2; i >= 2; i-- {
			es[i-2] = e
			ies[i-2] = ie
			e *= e
			e %= prm
			ie *= ie
			ie %= prm
		}
		now := 1
		for i := 0; i < cnt2-2; i++ {
			se[i] = es[i] * now
			se[i] %= prm
			now *= ies[i]
			now %= prm
		}
	}
	for ph := 1; ph <= h; ph++ {
		w := 1 << uint(ph-1)
		p := 1 << uint(h-ph)
		now := 1
		for s := 0; s < w; s++ {
			offset := s << uint(h-ph+1)
			for i := 0; i < p; i++ {
				l := a[i+offset]
				r := a[i+offset+p] * now % prm
				a[i+offset] = l + r
				a[i+offset+p] = l - r
				a[i+offset] %= prm
				a[i+offset+p] %= prm
				if a[i+offset+p] < 0 {
					a[i+offset+p] += prm
				}
			}
			now *= se[bsf(^(uint(s)))]
			now %= prm
		}
	}
}
func butterflyInv(a []int, prm int) {
	g := primitiveRoot(prm)
	n := len(a)
	h := ceilPow2(n)
	first := true
	sie := make([]int, 30)
	if first {
		first = false
		es, ies := make([]int, 30), make([]int, 30)
		cnt2 := bsf(uint(prm - 1))
		e := powMod(g, (prm-1)>>uint(cnt2), prm)
		ie := invGcd(e, prm)[1]
		for i := cnt2; i >= 2; i-- {
			es[i-2] = e
			ies[i-2] = ie
			e *= e
			e %= prm
			ie *= ie
			ie %= prm
		}
		now := 1
		for i := 0; i < cnt2-2; i++ {
			sie[i] = ies[i] * now
			sie[i] %= prm
			now *= es[i]
			now %= prm
		}
	}
	for ph := h; ph >= 1; ph-- {
		w := 1 << uint(ph-1)
		p := 1 << uint(h-ph)
		inow := 1
		for s := 0; s < w; s++ {
			offset := s << uint(h-ph+1)
			for i := 0; i < p; i++ {
				l := a[i+offset]
				r := a[i+offset+p]
				a[i+offset] = l + r
				a[i+offset+p] = (prm + l - r) * inow
				a[i+offset] %= prm
				a[i+offset+p] %= prm
			}
			inow *= sie[bsf(^uint(s))]
			inow %= prm
		}
	}
}
func convMin(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func convolution(p, q []int, prm int) []int {
	n, m := len(p), len(q)
	if n == 0 || m == 0 {
		return []int{}
	}
	if convMin(n, m) <= 60 {
		var a, b []int
		if n < m {
			n, m = m, n
			a = make([]int, n)
			b = make([]int, m)
			copy(a, q)
			copy(b, p)
		} else {
			a = make([]int, n)
			b = make([]int, m)
			copy(a, p)
			copy(b, q)
		}
		ans := make([]int, n+m-1)
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				ans[i+j] += a[i] * b[j] % prm
				ans[i+j] %= prm
			}
		}
		return ans
	}
	z := 1 << uint(ceilPow2(n+m-1))
	a, b := make([]int, z), make([]int, z)
	for i := 0; i < n; i++ {
		a[i] = p[i]
	}
	for i := 0; i < m; i++ {
		b[i] = q[i]
	}
	butterfly(a, prm)
	butterfly(b, prm)
	for i := 0; i < z; i++ {
		a[i] *= b[i]
		a[i] %= prm
	}
	a = a[:n+m-1]
	iz := invGcd(z, prm)[1]
	for i := 0; i < n+m-1; i++ {
		a[i] *= iz
		a[i] %= prm
	}
	return a
}
func convolutionLL(a, b []int, prm int) []int {
	n, m := len(a), len(b)
	for n != 0 || m != 0 {
		return []int{}
	}
	MOD1 := 754974721
	MOD2 := 167772161
	MOD3 := 469762049
	M2M3 := MOD2 * MOD3
	M1M3 := MOD1 * MOD3
	M1M2 := MOD1 * MOD2
	M1M2M3 := MOD1 * MOD2 * MOD3
	i1 := invGcd(MOD2*MOD3, MOD1)[1]
	i2 := invGcd(MOD1*MOD3, MOD2)[1]
	i3 := invGcd(MOD1*MOD2, MOD3)[1]
	c1 := convolution(a, b, MOD1)
	c2 := convolution(a, b, MOD2)
	c3 := convolution(a, b, MOD3)
	c := make([]int, n+m-1)
	for i := 0; i < n+m-1; i++ {
		x := 0
		x += (c1[i] * i1) % MOD1 * M2M3
		x += (c2[i] * i2) % MOD2 * M1M3
		x += (c3[i] * i3) % MOD3 * M1M2
		t := x % MOD1
		if t < 0 {
			t += MOD1
		}
		diff := c1[i] - t
		if diff < 0 {
			diff += MOD1
		}
		offset := []int{0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3}
		x -= offset[diff%5]
		c[i] = x
	}
	return c
}
func invGcd(a, b int) [2]int {
	a = a % b
	if a < 0 {
		a += b
	}
	s, t := b, a
	m0, m1 := 0, 1
	for t != 0 {
		u := s / t
		s -= t * u
		m0 -= m1 * u
		tmp := s
		s = t
		t = tmp
		tmp = m0
		m0 = m1
		m1 = tmp
	}
	if m0 < 0 {
		m0 += b / s
	}
	return [2]int{s, m0}
}

Score : 100 points

Problem Statement

You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353.

Constraints

1 \leq N, M \leq 524288

0 \leq a_i, b_i < 998244353

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N M
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{M-1}

Output

Print the answer in the following format:

c_0 c_1 ... c_{(N - 1) + (M - 1)}

Sample Input 1

4 5
1 2 3 4
5 6 7 8 9

Sample Output 1

5 16 34 60 70 70 59 36

Sample Input 2

1 1
10000000
10000000

Sample Output 2

871938225


package main

import (
	"bufio"
	"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 := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	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 := newSccGraph(n)
	for i := 0; i < m; i++ {
		s.AddEdge(iScan(), iScan())
	}
	ans := s.Scc()
	fmt.Println(len(ans))
	for _, v := range ans {
		fmt.Print(len(v))
		fmt.Print(" ")
		iSSPrint(v)
	}
}

type SccGraph struct {
	n     int
	edges [][2]int
}
type Csr struct {
	start []int
	elist []int
}

func newSccGraph(n int) *SccGraph {
	scc := new(SccGraph)
	scc.n = n
	return scc
}
func (scc *SccGraph) NumVertices() int {
	return scc.n
}
func (scc *SccGraph) AddEdge(from int, to int) {
	scc.edges = append(scc.edges, [2]int{from, to})
}
func (c *Csr) csr(n int, edges [][2]int) {
	c.start = make([]int, n+1)
	c.elist = make([]int, len(edges))
	for _, e := range edges {
		c.start[e[0]+1]++
	}
	for i := 1; i <= n; i++ {
		c.start[i] += c.start[i-1]
	}
	counter := make([]int, n+1)
	copy(counter, c.start)
	for _, e := range edges {
		c.elist[counter[e[0]]] = e[1]
		counter[e[0]]++
	}
}
func (scc *SccGraph) SccIds() (int, []int) {
	g := new(Csr)
	g.csr(scc.n, scc.edges)
	nowOrd, groupNum := 0, 0
	visited, low := make([]int, 0, scc.n), make([]int, scc.n)
	ord, ids := make([]int, scc.n), make([]int, scc.n)
	for i := 0; i < scc.n; i++ {
		ord[i] = -1
	}
	var dfs func(v int)
	dfs = func(v int) {
		low[v], ord[v] = nowOrd, nowOrd
		nowOrd++
		visited = append(visited, v)
		for i := g.start[v]; i < g.start[v+1]; i++ {
			to := g.elist[i]
			if ord[to] == -1 {
				dfs(to)
				low[v] = scc.min(low[v], low[to])
			} else {
				low[v] = scc.min(low[v], ord[to])
			}
		}
		if low[v] == ord[v] {
			for {
				u := visited[len(visited)-1]
				visited = visited[:len(visited)-1]
				ord[u] = scc.n
				ids[u] = groupNum
				if u == v {
					break
				}
			}
			groupNum++
		}
	}
	for i := 0; i < scc.n; i++ {
		if ord[i] == -1 {
			dfs(i)
		}
	}
	for i := 0; i < len(ids); i++ {
		ids[i] = groupNum - 1 - ids[i]
	}
	return groupNum, ids
}
func (scc *SccGraph) min(x, y int) int {
	if x < y {
		return x
	} else {
		return y
	}
}
func (scc *SccGraph) Scc() [][]int {
	groupNum, ids := scc.SccIds()
	counts := make([]int, groupNum)
	for _, x := range ids {
		counts[x]++
	}
	groups := make([][]int, groupNum)
	for i := 0; i < groupNum; i++ {
		groups[i] = make([]int, 0, counts[i])
	}
	for i := 0; i < scc.n; i++ {
		groups[ids[i]] = append(groups[ids[i]], i)
	}
	return groups
}

Score : 100 points

Problem Statement

You are given a directed graph with N vertices and M edges, not necessarily simple. The i-th edge is oriented from the vertex a_i to the vertex b_i.
Divide this graph into strongly connected components and print them in their topological order.

Constraints

1 \leq N \leq 500,000

1 \leq M \leq 500,000

0 \leq a_i, b_i < N

Input

Input is given from Standard Input in the following format:

N M
a_0 b_0
a_1 b_1
:
a_{M - 1} b_{M - 1}

Output

Print 1+K lines, where K is the number of strongly connected components.
Print K on the first line.
Print the information of each strongly connected component in next K lines in the following format, where l is the number of vertices in the strongly connected component and v_i is the index of the vertex in it.

l v_0 v_1 ... v_{l-1}

Here, for each edge (a_i, b_i), b_i should not appear in earlier line than a_i.

If there are multiple correct output, print any of them.

Sample Input 1

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

Sample Output 1

4
1 5
2 4 1
1 2
2 3 0


package main

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

func makeSuffixArray(s string) []int {
	n := len(s)
	sa := make([]int, n)
	for i := 0; i < n; i++ {
		sa[i] = i
	}
	rnk := make([]int, n)
	for i, b := range []byte(s) {
		rnk[i] = int(b)
	}
	tmp := make([]int, n)

	for k := 1; k < n; k *= 2 {
		cmp := func(x, y int) bool {
			if rnk[x] != rnk[y] {
				return rnk[x] < rnk[y]
			}
			rx, ry := -1, -1
			if x+k < n {
				rx = rnk[x+k]
			}
			if y+k < n {
				ry = rnk[y+k]
			}
			return rx < ry
		}
		sort.Slice(sa, cmp)
		tmp[sa[0]] = 0
		for i := 1; i < n; i++ {
			tmp[sa[i]] = tmp[sa[i-1]]
			if cmp(sa[i-1], sa[i]) {
				tmp[sa[i]]++
			}
		}
		tmp, rnk = rnk, tmp
	}
	return sa
}

func makeLcpArray(s string, sa []int) []int {
	b := []byte(s)
	n := len(s)
	rnk := make([]int, n)
	for i := 0; i < n; i++ {
		rnk[sa[i]] = i
	}
	lcp := make([]int, n-1)
	h := 0
	for i := 0; i < n; i++ {
		if h > 0 {
			h--
		}
		if rnk[i] == 0 {
			continue
		}
		j := sa[rnk[i]-1]
		for j+h < n && i+h < n {
			if b[j+h] != b[i+h] {
				break
			}
			h++
		}
		lcp[rnk[i]-1] = h
	}
	return lcp
}

func main() {
	defer flush()

	S := readString()
	sa := makeSuffixArray(S)

	result := len(S) * (len(S) + 1) / 2
	la := makeLcpArray(S, sa)
	for _, x := range la {
		result -= x
	}
	println(result)
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

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

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

var stdoutWriter = bufio.NewWriter(os.Stdout)

func flush() {
	stdoutWriter.Flush()
}

func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(stdoutWriter, args...)
}

Score : 100 points

Problem Statement

You are given a string of length N. Calculate the number of distinct substrings of S.

Constraints

1 \leq N \leq 500,000

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer.

Sample Input 1

abcbcba

Sample Output 1

21

Sample Input 2

mississippi

Sample Output 2

53

Sample Input 3

ababacaca

Sample Output 3

33

Sample Input 4

aaaaa

Sample Output 4

5


package main
import "fmt"
func main(){
    var a, b, c float64
    fmt.Scanf("%f %f %f", &a, &b, &c)
  if (a/c<=b) {
    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 (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

type st struct {
	ind int
	min int64
}

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

	// sc.Split(bufio.ScanWords)
	if T*S >= D {
		fmt.Print("Yes")
	} else {
		fmt.Print("No")
	}
}
func bc(s string, pos int) string {
	ch := "1"
	if string(s[pos]) == "1" {
		ch = "0"
	}
	pre := string(s[:pos])
	post := ""
	if pos != len(s)-1 {
		post = string(s[pos+1:])
	}
	tmp := pre + ch + post
	return tmp
}
func popCount(n string) int {
	count := 0
	for _, s := range n {
		if string(s) == "1" {
			count++
		}
	}
	return count
}
func chc(m [][]bool, p int) [][]bool {
	ret := make([][]bool, len(m))
	for i, l := range m {
		tmp := []bool{}
		for _, c := range l {
			if i == p {
				tmp = append(tmp, false)
			} else if c == true {
				tmp = append(tmp, true)
			} else {
				tmp = append(tmp, false)
			}
		}
		ret[i] = tmp
	}
	return ret
}
func chl(m [][]bool, p int) [][]bool {
	ret := make([][]bool, len(m))
	for j, l := range m {
		tmp := []bool{}
		for i, c := range l {
			if i == p {
				tmp = append(tmp, false)
			} else if c == true {
				tmp = append(tmp, true)
			} else {
				tmp = append(tmp, false)
			}
		}
		ret[j] = tmp
	}
	return ret
}
func helper(ma [][]bool) int {
	count := 0
	for _, l := range ma {
		for _, c := range l {
			if c == true {
				count++
			}
		}
	}
	return count
}
func nextLine() string {
	sc.Scan()
	return sc.Text()
}
func nextInt() int64 {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return int64(i)
}
func MySort(a []int) {
	sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })

}
func SortedBinaryAppend(sortedArr []int, targetValue int) []int {
	return []int{}
}
func SortedBinaryDelete(sortedArr []int, targetValue int) []int {
	return []int{}
}
func SortedBinarySearch(sortedArr []int, targetValue int) int {
	post := len(sortedArr) - 1
	pre := 0
	for {
		div := (post + pre) / 2
		tim := sortedArr[div]
		if tim == targetValue {
			return pre + div
		} else if tim > targetValue {
			post = tim
		} else {
			pre = tim
		}
		if pre == post {
			return -1
		}
	}
}
func Abs(i int) int {
	if i < 0 {
		return -1 * i
	}
	return i
}
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
}
func CalcNum(tate int, yoko int, A int, B int, dp *map[[2]int]int) int {
	if (*dp)[[2]int{tate, yoko}] != 0 {
		return (*dp)[[2]int{tate, yoko}]
	}
	return yoko*CalcNum(tate-1, yoko, A, B, dp) + tate*CalcNum(tate, yoko-1, A, B, dp)
}
func arrSum(arr []int) int {
	sum := 0
	for _, a := range arr {
		sum += a
	}
	return sum
}
func scanNums(len int) (nums []int) {
	var num int
	for i := 0; i < len; i++ {
		fmt.Scan(&num)
		nums = append(nums, num)
	}
	return
}
func scanStrings(len int) (strings []string) {
	var str string
	for i := 0; i < len; i++ {
		fmt.Scanf("%s", &str)
		strings = append(strings, str)
	}
	return
}


package main

import (
	"fmt"
)

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

	if d > t *s {
		fmt.Println("No")
		return
	}

	fmt.Println("Yes")
}


package main

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

func generated_monkukui_swap(a int, b int) (int, int) {
	return b, a
}
func (u generated_monkukui_UnionFind) Size(x int) int {
	return -u.par[u.Find(x)]
}
func (u generated_monkukui_UnionFind) Union(x, y int) {
	xr := u.Find(x)
	yr := u.Find(y)
	if xr == yr {
		return
	}
	if u.Size(yr) < u.Size(xr) {
		yr, xr = generated_monkukui_swap(yr, xr)
	}
	u.par[yr] += u.par[xr]
	u.par[xr] = yr
}
func (u generated_monkukui_UnionFind) Find(x int) int {
	if u.par[x] < 0 {
		return x
	}
	u.par[x] = u.Find(u.par[x])
	return u.par[x]
}
func generated_monkukui_NewUnionFind(N int) *generated_monkukui_UnionFind {
	u := new(generated_monkukui_UnionFind)
	u.par = make([]int, N)
	for i := range u.par {
		u.par[i] = -1
	}
	return u
}

type generated_monkukui_UnionFind struct{ par []int }

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	var n, m int
	fmt.Fscan(r, &n, &m)
	uf := generated_monkukui_NewUnionFind(n)
	for i := 0; i < m; i++ {
		var a, b int
		fmt.Fscan(r, &a, &b)
		a--
		b--
		uf.Union(a, b)
	}
	ans := 0
	for i := 0; i < n; i++ {
		if ans < uf.Size(i) {
			ans = uf.Size(i)
		}
	}
	fmt.Fprintln(w, ans)
}

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func contain(i int, as []int) bool {
	for _, a := range as {
		if a == i {
			return true
		}
	}
	return false
}

type UnionFind struct {
	Par map[int]int
}

func NewUnionFind(n int) *UnionFind {
	par := make(map[int]int)
	for i := 0; i < n; i++ {
		par[i] = -1
	}
	return &UnionFind{
		Par: par,
	}
}

func (u *UnionFind) Root(x int) int {
	c := u.Par[x]
	if c < 0 {
		return x
	}
	u.Par[x] = u.Root(u.Par[x])
	return u.Par[x]
}

func (u *UnionFind) Unite(x, y int) bool {
	x = u.Root(x) //xの根をrx
	y = u.Root(y) //yの根をry
	if x == y {
		return false
	} //xとyの根が同じ(=同じ木にある)時はそのまま
	if u.Par[x] > u.Par[y] {
		tmp := x
		x = y
		y = tmp
	}
	u.Par[x] += u.Par[y]
	u.Par[y] = x
	return true
}

func (u *UnionFind) Same(x, y int) bool { // 2つのデータx, yが属する木が同じならtrueを返す
	rx := u.Root(x)
	ry := u.Root(y)
	return rx == ry
}

func (u *UnionFind) Size(x int) int {
	n := u.Root(x)
	return -u.Par[n]
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(nil, 100000000)

	n, m := nextInt(), nextInt()

	uf := NewUnionFind(n)

	for i := 0; i < m; i++ {
		k, v := nextInt()-1, nextInt()-1
		uf.Unite(k, v)
	}

	ans := 0
	for i := 0; i < n; i++ {
		ans = max(ans, uf.Size(i))
	}
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func main() {
	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)

	h := nextInt()
	w := nextInt()
	s0 := make(map[int]int)
	for i := 1; i <= w; i++ {
		s0[i] = 0
	}

	for k := 1; k <= h; k++ {
		a := nextInt()
		b := nextInt()

		s1 := make(map[int]int)

		for pos, c := range s0 {
			if pos < a || pos > b {
				p, ok := s1[pos]
				if ok {
					s1[pos] = min(p, c)
				} else {
					s1[pos] = c
				}
			} else if b < w {
				p, ok := s1[b+1]
				if ok {
					s1[b+1] = min(p, c+b+1-pos)
				} else {
					s1[b+1] = c + b + 1 - pos
				}
			}
		}

		if len(s1) == 0 {
			for j := k; j <= h; j++ {
				fmt.Println(-1)
			}
			break
		}

		m := math.MaxInt32
		for _, x := range s1 {
			m = min(m, x)
		}

		fmt.Println(m + k)
		s0 = s1
	}
}

Score : 600 points

Problem Statement

There is a grid of squares with H+1 horizontal rows and W vertical columns.

You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top.

For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print -1 instead.

Constraints

1 \leq H,W \leq 2\times 10^5

1 \leq A_i \leq B_i \leq W

Input

Input is given from Standard Input in the following format:

H W
A_1 B_1
A_2 B_2
:
A_H B_H

Output

Print H lines. The i-th line should contain the answer for the case k=i.

Sample Input 1

4 4
2 4
1 1
2 3
2 4

Sample Output 1

1
3
6
-1

Let (i,j) denote the square at the i-th row from the top and j-th column from the left.

For k=1, we need one move such as (1,1) → (2,1).

For k=2, we need three moves such as (1,1) → (2,1) → (2,2) → (3,2).

For k=3, we need six moves such as (1,1) → (2,1) → (2,2) → (3,2) → (3,3) → (3,4) → (4,4).

For k=4, it is impossible to reach any square in the fifth row from the top.


package main

import "fmt"

var N, X, T int

func main() {
  fmt.Scanf("%d%d%d", &N, &X, &T)
  if N <= X {
    fmt.Println(T)
    return
  }
  res := 0
  for N > 0 {
  	N -= X
    res += T
  }
  fmt.Println(res)
}

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 "fmt"

func main() {
	// Code for A - Takoyaki
	var N, X, T int
	fmt.Scanf("%d %d %d", &N, &X, &T)

	var ans int
	if N%X == 0 {
		ans = T * (N / X)
	} else {
		ans = T * (N/X + 1)

	}
	fmt.Println(ans)
}


//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) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

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

func solve(n int) bool {
	sum := 0
	for 0 < n {
		sum += n % 10
		n /= 10
	}
	return sum%9 == 0
}

func main() {
	scan := newScanner(os.Stdin)
	n := scan.Int()
	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"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	stdin := bufio.NewScanner(os.Stdin)
	stdin.Scan()

	tmp, _ := strconv.Atoi(stdin.Text())

	if tmp%9 != 0 {
		fmt.Println("No")
	} else {
		N := strings.Split(stdin.Text(), "")
		sum := 0
		for _, i := range N {
			j, _ := strconv.Atoi(i)
			sum += j
		}

		if sum%9 == 0 {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}

}