// ProblemURL : https://atcoder.jp/contests/abc120/tasks/abc120_d
// ---------------------------------------------
package main

import "fmt"

type djSet struct{ p []int }

func newDj(size int) *djSet {
	dj := &djSet{}
	dj.initDjSet(size)
	return dj
}
func (dj *djSet) initDjSet(size int) {
	dj.p = make([]int, size)
	for i := 0; i < size; i++ {
		dj.p[i] = -1
	}
	return
}
func (dj *djSet) unite(x, y int) bool {
	xr, yr := dj.find(x), dj.find(y)
	if xr != yr {
		if dj.p[yr] < dj.p[xr] {
			x, y = y, x
			xr, yr = yr, xr
		}
		dj.p[xr] += dj.p[yr]
		dj.p[yr] = x
	}
	return xr != yr
}
func (dj *djSet) find(x int) int {
	if dj.p[x] < 0 {
		return x
	}
	dj.p[x] = dj.find(dj.p[x])
	return dj.p[x]
}
func (dj *djSet) isSame(x, y int) bool { return dj.find(x) == dj.find(y) }
func (dj *djSet) size(x int) int       { return -dj.p[dj.find(x)] }

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	as := make([]int, m)
	bs := make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Scan(&as[i], &bs[i])
		as[i]--
		bs[i]--
	}

	convenience := 0
	conveniences := make([]int, m)
	dj := newDj(n)
	for i := m - 1; i >= 0; i-- {
		if !dj.isSame(as[i], bs[i]) {
			convenience += dj.size(as[i]) * dj.size(bs[i])
			dj.unite(as[i], bs[i])
		}
		conveniences[i] = convenience
	}

	conveniences = append(conveniences, 0)
	inconvenience := 0
	for i := 1; i < len(conveniences); i++ {
		inconvenience += conveniences[i-1] - conveniences[i]
		fmt.Println(inconvenience)
	}
}

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

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1

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

func main() {
	// Code for A - Still TBD
	var S string
	fmt.Scanf("%s", &S)

	yyyy, _ := strconv.Atoi(S[0:4])
	mm, _ := strconv.Atoi(S[5:7])
	if yyyy <= 2018 {
		fmt.Println("Heisei")
	} else if yyyy == 2019 && mm <= 4 {
		fmt.Println("Heisei")
	} else {
		fmt.Println("TBD")
	}
}

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func nextInts(n int) []int {
	slice := make([]int, n)
	for i := 0; i < n; i++ {
		slice[i] = nextInt()
	}
	return slice
}

func main() {
	sc.Split(bufio.ScanWords)
	s := strings.Split(next(), "/")
	y, _ := strconv.Atoi(s[0])
	m, _ := strconv.Atoi(s[1])
	d, _ := strconv.Atoi(s[2])
	h := false
	if y < 2019 {
		h = true
	} else if y == 2019 && m < 4 {
		h = true
	} else if y == 2019 && m == 4 && d <= 30 {
		h = true
	}
	if h {
		fmt.Println("Heisei")
	} else {
		fmt.Println("TBD")
	}
}


package main

import (
	"fmt"
	"strconv"
	"strings"
)

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

	fmt.Println(logic(s))
}

func logic(s string) string {
	a := strings.Replace(s, "/", "", -1)
	b, _ := strconv.Atoi(a)

	if b < 20190501 {
		return "Heisei"
	}
	return "TBD"
}


package main

import "fmt"

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

	sumJPY := 0
	sumBTC := 0.0
	var (
		x float64
		u string
	)
	for i := 0; i < n; i++ {
		fmt.Scan(&x, &u)
		if u == "JPY" {
			sumJPY += int(x)
		} else {
			sumBTC += x
		}
	}

	fmt.Println(float64(sumJPY) + sumBTC*380000.0)
}

Score : 200 points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.

If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

Output will be judged correct when the absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func min(a ...int) int {
	min := 1000000000
	for _, x := range a {
		if min > x {
			min = x
		}
	}
	return min
}

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

	n, A, B, C := nextInt(), nextInt(), nextInt(), nextInt()
	l := make([]int, n)
	for i := 0; i < n; i++ {
		l[i] = nextInt()
	}

	var dfs func(cur, a, b, c int) int
	dfs = func(cur, a, b, c int) int {
		if cur == n {
			if min(a, b, c) == 0 {
				return 1000000000
			}
			return abs(A-a) + abs(B-b) + abs(C-c) - 30
		}

		cand1 := dfs(cur+1, a, b, c)
		cand2 := dfs(cur+1, a+l[cur], b, c) + 10
		cand3 := dfs(cur+1, a, b+l[cur], c) + 10
		cand4 := dfs(cur+1, a, b, c+l[cur]) + 10
		return min(cand1, cand2, cand3, cand4)
	}

	fmt.Println(dfs(0, 0, 0, 0))
}

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


package main

import (
	"fmt"
	"math"
)

var N, A, B, C int
var Flag []int
var MP []int

func longer(i int, x int) {
	MP[i] += int(math.Abs(float64(x)))
}

func main() {

	fmt.Scan(&N, &A, &B, &C)
	Kadomatsu := []int{A, B, C}
	L := make([]int, N)
	KFlag := []int{0, 0, 0}
	TFlag := make([]int, N)
	for j := 0; j < N; j++ {
		TFlag[j] = 0
	}
	MP = []int{0, 0, 0}

	for j := 0; j < N; j++ {
		fmt.Scan(&L[j])
		// 竹が、門松の長さを満たしていないかチェック
		// 竹と門松の差分が１０以内の場合、延長短縮を用いてアジャストさせる
		for i := 0; i < 3; i++ {
			if math.Abs(float64(L[j]-Kadomatsu[i])) < 10 && KFlag[i] == 0 {
				KFlag[i] = 1
				TFlag[j] = 1
				MP[i] += int(math.Abs(float64(L[j] - Kadomatsu[i])))
			}
		}
	}
	// 長さを満たしていない門松に対して
	//for i := 0; i < 3; i++ {
	//	if Flag[i] == 0 {

	//	}
	//}
	fmt.Println(MP[0] + MP[1] + MP[2])

}


package main

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

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

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

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

	ss := make([]int, a)
	ts := make([]int, b)
	xs := make([]int, q)

	sc := scanner()
	for i := range ss {
		ss[i] = get_int(sc)
	}
	ss = append(ss, -100000000000)
	ss = append(ss, 100000000000)
	for i := range ts {
		ts[i] = get_int(sc)
	}
	ts = append(ts, -100000000000)
	ts = append(ts, 100000000000)
	for i := range xs {
		xs[i] = get_int(sc)
	}

	sort.Ints(ss)
	sort.Ints(ts)

	for _, x := range xs {
		si := sort.SearchInts(ss, x)
		ti := sort.SearchInts(ts, x)
		v0 := s1(ss[si], ts[ti], x)
		v1 := s1(ss[si-1], ts[ti-1], x)
		v2 := s2(ss[si-1], ts[ti], x)
		v3 := s2(ss[si], ts[ti-1], x)

		min := 100000000000
		for _, v := range []int{v0, v1, v2, v3} {
			if min > v {
				min = v
			}
		}
		fmt.Println(min)
	}
}

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

func s1(a, b, x int) int {
	return max(diff(a, x), diff(b, x))
}

func s2(a, b, x int) int {
	d1 := diff(a, x)
	d2 := diff(x, b)
	return d1 + d2 + min(d1, d2)
}

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

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

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


package main

import "fmt"

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

  if b%a == 0 {
    fmt.Println(a+b)
  } else {
    fmt.Println(b-a)
  }
}

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


package main

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

func main() {
	io, flush := NewIO()
	defer flush()

	n, _ := io.ScanInt2()
	likedFoodCountMap := map[int]int{}
	for i := 0; i < n; i++ {
		k := io.ScanInt()
		likedFoods := io.ScanInts(k)
		for _, food := range likedFoods {
			likedFoodCountMap[food] += 1
		}
	}

	var allLikedFoodNum int
	for _, count := range likedFoodCountMap {
		if count == n {
			allLikedFoodNum++
		}
	}
	fmt.Println(allLikedFoodNum)
}

type IO struct {
	scanner *bufio.Scanner
	writer  *bufio.Writer
}

func NewIO() (*IO, func()) {
	io := &IO{
		scanner: newScanner(),
		writer:  newWriter(),
	}
	return io, func() { io.writer.Flush() }
}

func newScanner() *bufio.Scanner {
	s := bufio.NewScanner(os.Stdin)
	s.Buffer(make([]byte, 10000000), 10000000)
	s.Split(bufio.ScanWords)
	return s
}

func newWriter() *bufio.Writer {
	return bufio.NewWriter(os.Stdout)
}

func (io *IO) ScanBytes() []byte {
	if !io.scanner.Scan() {
		panic("scan string failed")
	}
	return io.scanner.Bytes()
}

func (io *IO) ScanString() string {
	if !io.scanner.Scan() {
		panic("scan string failed")
	}
	return io.scanner.Text()
}

func (io *IO) ScanStrings(n int) []string {
	strs := make([]string, n)
	for i := 0; i < n; i++ {
		strs[i] = io.ScanString()
	}
	return strs
}

func (io *IO) Scan2DStrings(y, x int) [][]string {
	strings := make([][]string, y)
	for i := 0; i < y; i++ {
		strings[i] = io.ScanStrings(x)
	}
	return strings
}

func (io *IO) Scan2DGraph(y int) [][]string {
	strs := make([][]string, y)
	for i := 0; i < y; i++ {
		strs[i] = strings.Split(io.ScanString(), "")
	}
	return strs
}

func (io *IO) ScanInt() int {
	return int(io.ScanInt64())
}

func (io *IO) ScanInt2() (int, int) {
	return int(io.ScanInt64()), int(io.ScanInt64())
}

func (io *IO) ScanInt3() (int, int, int) {
	return int(io.ScanInt64()), int(io.ScanInt64()), int(io.ScanInt64())
}

func (io *IO) ScanInt4() (int, int, int, int) {
	return int(io.ScanInt64()), int(io.ScanInt64()), int(io.ScanInt64()), int(io.ScanInt64())
}

func (io *IO) ScanInts(n int) []int {
	ints := make([]int, n)
	for i := 0; i < n; i++ {
		ints[i] = io.ScanInt()
	}
	return ints
}

func (io *IO) Scan2DInts(y, x int) [][]int {
	ints := make([][]int, y)
	for i := 0; i < y; i++ {
		ints[i] = io.ScanInts(x)
	}
	return ints
}

func (io *IO) ScanInt64() int64 {
	i, err := strconv.ParseInt(io.ScanString(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func (io *IO) ScanFloat64() float64 {
	i, _ := strconv.ParseFloat(io.ScanString(), 64)
	return i
}

func (io *IO) ScanFloat64s(n int) []float64 {
	floats := make([]float64, n)
	for i := 0; i < n; i++ {
		floats[i] = io.ScanFloat64()
	}
	return floats
}

func (io *IO) Println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


package main

import "fmt"

func main() {
	var n, m, k, a, ans int
	fmt.Scan(&n, &m)
	f := make(map[int]int)
	for i := 0; i < n; i++ {
		fmt.Scan(&k)
		for j := 0; j < k; j++ {
			fmt.Scan(&a)
			f[a]++
		}
	}
	for _, v := range f {
		if v == n {
			ans++
		}
	}
	fmt.Println(ans)
}


package main

import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		var k int
		fmt.Scan(&k)
		for i := 0; i < k; i++ {
			var tmp int
			fmt.Scan(&tmp)
			v, ok := mp[tmp]
			if ok {
				mp[tmp] = v + 1
			} else {
				mp[tmp] = 1
			}
		}
	}
	count := 0
	for _, v := range mp {
		if v == n {
			count++
		}
	}
	fmt.Println(count)
}


package main
import "fmt"

func main() {
    ints := scanNums(2)
    N := ints[0]
    M := ints[1]
    var popularities [30]int
    for i := 0; i < N; i++ {
        K := scanNum()
        for j := 0; j < K; j++ {
            A := scanNum()
            popularities[A - 1] += 1
        }
    }
    var result int
    for i := 0; i < M; i++ {
        if popularities[i] == N {
            result += 1
        }
    }
    fmt.Println(result)
}

func scanNum() (num int) {
    fmt.Scan(&num)
    return
}

func scanString() (str string) {
    fmt.Scanf("%s", str)
    return
}

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"
	"sort"
)

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

	aSlice := make([]int, n)
	for i := range aSlice {
		fmt.Scan(&aSlice[i])
	}

	sort.Ints(aSlice)

	a := aSlice[0]
	for i := 1; i < n; i++ {
		b := aSlice[i]
		r := b % a
		for r != 0 {
			b = a
			a = r
			r = b % a
		}
	}
	fmt.Println(a)
}

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


package main

import (
  "fmt"
  "strconv"
)

func max(A string, B string) string {
  if len(A) > len(B) || (len(A) == len(B) && A > B){
    return A
  }
  return B
}

func main() {
  var N, M int
  fmt.Scan(&N, &M)
  A := make([][]int, M)
  B := []int{0, 2, 5, 5, 4, 5, 6, 3, 7, 6}
  DP := make([]string, N + 1)
  var x int
  for i, _ := range A {
    fmt.Scan(&x)
    A[i] = []int{B[x], x}
    if B[x] <= N {
      DP[B[x]] = max(DP[B[x]], strconv.Itoa(x))
    }
  }
  for i, _ := range DP {
    for _, a := range A {
      if i > a[0] && len(DP[i - a[0]]) >= 1 {
        b := DP[i - a[0]] + strconv.Itoa(a[1])
        DP[i] = max(DP[i], b)
      }
    }
  }
  fmt.Println(DP[N])
}

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a 64-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654


package main

import (
	"fmt"
	"math"
)

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

	var bis int
	if b%a != 0 {
		if k-(a-2)%3 == 0 {
			fmt.Println("A")
			bis = ((k - a + 2) / 3 * b)
		} else {
			fmt.Println("B")
			bis = (k-a+2)/3*b + ((k - a + 2) % 3)
		}
	} else {
		if (k-a+2)%2 == 0 {
			fmt.Println("C")
			bis = (k-a+2)/3*b + 1
		} else {
			fmt.Println("D")
			//bis = ((k-a+2)/3 + 1) * b
			bis = a * int(math.Pow(float64(3), float64((k-a+2)/3+1)))
		}
	}
	fmt.Println(bis)
}

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

1 \leq K,A,B \leq 10^9

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


package main

import "fmt"

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

	c := b / a
	bis := 1
	for i := 1; i <= k; i++ {
		if c == 0 || c == 1 {
			bis++
		} else if c > 0 {
			if i == k {
				bis++
				break
			}
			if bis%a == 0 {
				bis *= c
				i++
			} else {
				bis++
			}
		}
	}
	fmt.Println(bis)
}


package main

import (
	"fmt"
)

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

func sum(nums []int) int {
	sum := 0
	for _, v := range nums {
		sum += v
	}
	return sum
}

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

	nums := make([]int, n)
	for i := range nums {
		fmt.Scan(&nums[i])
	}

	max := max(nums)
	sum := sum(nums) - max

	if max < sum {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


package main

import (
	"fmt"
	"sort"
)

func main() {
	var N, M, answer, jumpLimit int
	fmt.Scan(&N, &M)
	numList := make([]int, M)
	for i := 0; i < M; i++ {
		fmt.Scan(&numList[i])
	}
	sort.Sort(sort.IntSlice(numList))

	if M <= N {
		fmt.Println(0)
	} else {
		dList := make([]int, M-1)
		for i := 0; i < M-1; i++ {
			dList[i] = numList[i+1] - numList[i]
		}
		sort.Sort(sort.IntSlice(dList))

		jumpLimit = N - 1
		if jumpLimit != 0 {
			for i := 0; i < jumpLimit; i++ {
				dList[M-2-i] = 0
			}
		}
		answer = Sum(dList)
		fmt.Println(answer)
	}

}

func Sum(a []int) int {
	s := 0
	for _, n := range a {
		s = s + n
	}
	return s
}

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


package main

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

var in = bufio.NewScanner(os.Stdin)

func NextSlice(n int) []int {
	var mat []int
	in.Scan()
	temp := strings.Split(in.Text(), " ")
	for i := 0; i < n; i++ {
		li, _ := strconv.Atoi(temp[i])
		mat = append(mat, li)
	}
	return mat
}
func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)

	rep := NextSlice(m)
	sort.Ints(rep)

	var deff []int
	for i := 0; i < len(rep)-1; i++ {
		deff = append(deff, int(math.Abs(float64(rep[i]-rep[i+1]))))
	}
	sort.Ints(deff)

	ans := 0
	for i := 0; i <= len(deff)-n; i++ {
		ans += deff[i]
	}
	fmt.Println(ans)
}


package main

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

func main() {
    var n int
    fmt.Scan(&n)
    a := scanPairs(n)
    By(cmp).Sort(a)
    ans := int64(0)
    for i:=0;i<n;i++{
        if i%2==0{
            ans += a[i].first
        } else {
            ans -= a[i].second
        }
    }
    fmt.Println(ans)
}

// Pairsort
type Pair struct {
    first,second int64
}

type By func(p1, p2 *Pair) bool

func (by By) Sort(pairs []Pair) {
    ps := &pairSorter{
            pairs : pairs,
            by: by,
    }
    sort.Sort(ps)
}

type pairSorter struct {
    pairs []Pair
    by func(p1, p2 *Pair) bool
}

func (s *pairSorter) Len() int {
    return len(s.pairs)
}

func (s *pairSorter) Swap(i, j int) {
    s.pairs[i], s.pairs[j] = s.pairs[j], s.pairs[i]
}

func (s *pairSorter) Less(i, j int) bool {
    return s.by(&s.pairs[i], &s.pairs[j])
}

func first (p1, p2 *Pair) bool {
    return p1.first < p2.first
}

func second (p1, p2 *Pair) bool {
    return p1.second < p2.second
}

func cmp (p1, p2 *Pair) bool {
    return p1.first+p1.second > p2.first+p2.second
}
// end

func scanPairs(len int) []Pair{
    Pairs := make([]Pair, len)
    for i:=0; i<len; i++{
        fmt.Scan(&Pairs[i].first,&Pairs[i].second)
    }
    return Pairs
}

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

func abs64(a int64) int64 {
    if a<0{
        return -a
    }
    return a
}

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

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

func min64(a, b int64) int64 {
    if a >= b {
        return b
    }
    return a
}

func max64(a, b int64) int64 {
    if a >= b {
        return a
    }
    return b
}

func gcd64(a, b int64) int64 {
    if a % b == 0 {
        return b
    } else {
        return gcd64(b, a%b)
    }
}

func lcm64(a, b int64) int64 {
    return a / gcd64(a, b) * b
}

// 入力処理
var sc = bufio.NewScanner(os.Stdin)
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
}

func readLineNums(len int) (nums []int){
    for i:=0; i<len; i++{
        tmp,_ := strconv.Atoi(nextLine())
        nums = append(nums,tmp)
    }
    return
}

func readLineNumSlices(n,m int) (nums [][]int){
    for i:=0; i<n; i++{
        tmp := strings.Split(nextLine()," ")
        a := make([]int, m)
        for j:=0;j<m;j++{
            a[j],_ = strconv.Atoi(tmp[j])
        }
        nums = append(nums,a)
    }
    return
}

func readOneLineNums(len int) []int{
    nums := make([]int, 0, len+10)
    var num int
    sc.Split(bufio.ScanWords)
    for i:=0; i<len; i++{
        num = nextInt()
        nums = append(nums,num)
    }
    return nums
}

func scanNums(len int) []int{
    nums := make([]int, 0, len+10)
    var num int
    for i:=0; i<len; i++{
        fmt.Scan(&num)
        nums = append(nums,num)
    }
    return nums
}

func scanNums64(len int) []int64{
    nums := make([]int64, 0, len+10)
    var num int64
    for i:=0; i<len; i++{
        fmt.Scan(&num)
        nums = append(nums,num)
    }
    return nums
}

func scanString(len int) (str []string){
    var s string
    for i:=0; i<len; i++{
        fmt.Scan(&s)
        str = append(str,s)
    }
    return
}

func makeTwoNums(n,m,k int) ([][]int){
    Nums := make([][]int, n)
    for i:=0; i<n; i++{
        tmp := make([]int, m)
        for j:=0;j<m;j++{
            tmp[j] = k
        }
        Nums[i] = tmp
    }
    return Nums
}

func makeTwoNums64(n,m int, k int64) ([][]int64){
    Nums := make([][]int64, n)
    for i:=0; i<n; i++{
        tmp := make([]int64, m)
        for j:=0;j<m;j++{
            tmp[j] = k
        }
        Nums[i] = tmp
    }
    return Nums
}

func sortString(s string) string{
    t := strings.Split(s, "")
    sort.Strings(t)
    return strings.Join(t, "")
}

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

func stringRev(s []byte,l int,r int) []byte{
    for i:=0;i<(r-l+1)/2;i++{
        s[l-1+i], s[r-1-i] = s[r-1-i], s[l-1+i]
    }
    return s
}

func inside(h,w,H,W int) bool{
    if h>=0 && h<H && w>=0 && w<W{
        return true
    }
    return false
}

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

Note that the answer may not fit into a 32-bit integer.


// Package main provides
//
// File:  c.go
// Author: ymiyamoto
//
// Created on Sun Jan 27 21:06:32 2019
//
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"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
}

type pair struct {
	a, b int
}

type pairs []pair

func (ps pairs) Len() int {
	return len(ps)
}
func (ps pairs) Swap(i, j int) {
	ps[i], ps[j] = ps[j], ps[i]
}

func (ps pairs) Less(i, j int) bool {
	return ps[i].a+ps[i].b > ps[i].a+ps[i].b
}

func main() {
	sc.Split(bufio.ScanWords)
	N := nextInt()

	ps := make(pairs, N)
	for i := range ps {
		fmt.Scan(&ps[i].a, &ps[i].b)
	}
	sort.Sort(ps)

	takahashi := 0
	aoki := 0
	for i := range ps {
		if i%2 == 0 {
			takahashi += ps[i].a
		} else {
			aoki += ps[i].b
		}
	}
	fmt.Println(takahashi - aoki)
}


package main

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

func main() {
	N := nextInt()
	A := make([]int, N)
	B := make([]int, N)
	ac := make([]pair, N)
	bc := make([]pair, N)
	for i := 0; i < N; i++ {
		A[i] = nextInt()
		B[i] = nextInt()
		ac[i] = pair{A[i] - B[i], i}
		bc[i] = pair{B[i] - A[i], i}
	}
	// sort.Sort(pairs(C))
	sort.Sort(pairs(ac))
	sort.Sort(pairs(bc))
	// log.Println(ac)
	// log.Println(bc)
	acIdx := 0
	bcIdx := 0
	used := make([]bool, N)
	t := 0
	a := 0
	for i := 0; i < N; i++ {
		if i%2 == 0 {
			for used[acIdx] {
				acIdx++
			}
			// log.Println("takahasi selected ", ac[acIdx].b)
			t += A[ac[acIdx].b]
			used[ac[acIdx].b] = true
		} else {
			for used[bcIdx] {
				bcIdx++
			}
			// log.Println("aoki selected ", bc[acIdx].b)
			a += B[bc[bcIdx].b]
			used[bc[bcIdx].b] = true
		}
	}
	fmt.Println(t - a)
	// var dp [100000][100000]int
	// dp[0][0]=A[0]
	// dp[0][1]=B[0]
	// for i := 0; i < N; i++ {
	// 	dp[
	// }
}

var dy = []int{1, 0, -1, 0, 0}
var dx = []int{0, 1, 0, -1, 0}
var intmax = int(1e9)

func pow(a, b int) int {
	return int(math.Pow(float64(a), float64(b)))
}

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func max(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}
func min(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}
func sum(a []int) (r int) {
	for i := range a {
		r += a[i]
	}
	return r
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

type pair struct {
	a, b int
}

type pairs []pair

func (p pairs) Len() int {
	return len(p)
}
func (p pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (p pairs) Less(i, j int) bool {
	return p[i].a > p[j].a
}

var nextReader func() string

func init() {
	nextReader = newScanner()
	log.SetFlags(log.Lshortfile)
}

func newScanner() func() string {
	r := bufio.NewScanner(os.Stdin)
	r.Buffer(make([]byte, 1024), int(1e+11))
	r.Split(bufio.ScanWords)
	return func() string {
		r.Scan()
		return r.Text()
	}
}
func nextString() string {
	return nextReader()
}
func nextInt64() int64 {
	v, _ := strconv.ParseInt(nextReader(), 10, 64)
	return v
}
func nextInt() int {
	v, _ := strconv.Atoi(nextReader())
	return v
}
func nextInts(n int) []int {
	r := make([]int, n)
	for i := 0; i < n; i++ {
		r[i] = nextInt()
	}
	return r
}
func nextFloat64() float64 {
	f, _ := strconv.ParseFloat(nextReader(), 64)
	return f
}


// Package main provides
//
// File:  main.go
// Author: ymiyamoto
//
// Created on Sun Jan 27 21:14:46 2019
//
package main

import "fmt"

type graph [][]int

func (g graph) dfs(n int, visited []bool) {
	for i := range g[n] {
		visited[g[n][i]] = true
		g.dfs(g[n][i], visited)
	}
}

func (g graph) root() int {
	roots := make([]bool, len(g))
	for i := range g {
		g.dfs(i, roots)
	}

	for i := range roots {
		if !roots[i] {
			return i
		}
	}
	return -1
}

func (g graph) depthDFS(n int, d int, depths []int) {
	if depths[n] < d {
		depths[n] = d
	}

	for i := range g[n] {
		g.depthDFS(g[n][i], d+1, depths)
	}
}

func (g graph) depth(n int) []int {
	dep := make([]int, len(g))
	dep[n] = 0
	for i := range g[n] {
		to := g[n][i]
		g.depthDFS(to, 1, dep)
	}
	return dep
}

func (g graph) parentsDFS(parent int, parents []int) {
	for i := range g[parent] {
		to := g[parent][i]
		if to != -1 {
			parents[to] = parent + 1
			g.parentsDFS(to, parents)
		}
	}
}

func (g graph) parents(root int) []int {
	parents := make([]int, len(g))
	parents[root] = 0
	g.parentsDFS(root, parents)
	return parents
}

func main() {
	var N, M int
	fmt.Scan(&N, &M)

	g := make(graph, N)
	for i := 0; i < N+M-1; i++ {
		var A, B int
		fmt.Scan(&A, &B)
		g[A-1] = append(g[A-1], B-1)
	}

	root := g.root()
	depths := g.depth(root)
	for i := range g {
		for j := range g[i] {
			if depths[i]+1 != depths[g[i][j]] {
				g[i][j] = -1
			}
		}
	}

	for _, p := range g.parents(root) {
		fmt.Println(p)
	}
}

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	log.SetFlags(log.Lshortfile)
	e := make([]int, 3)
	e[0] = nextInt()
	e[1] = nextInt()
	e[2] = nextInt()
	sort.Ints(e)
	fmt.Println(e[0] * e[1] / 2)
}

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

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

var dy = []int{0, 1, 0, -1}
var dx = []int{1, 0, -1, 0}
var MAX = math.MaxInt32

func pow(a, b int) int {
	return int(math.Pow(float64(a), float64(b)))
}

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func max(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}
func min(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}
func sum(a []int) (r int) {
	for i := range a {
		r += a[i]
	}
	return r
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

type Pair struct {
	a, b int
}

type Pairs []Pair

func (p Pairs) Len() int {
	return len(p)
}
func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (p Pairs) Less(i, j int) bool {
	if p[i].a == p[j].a {
		return p[i].b < p[j].b
	}
	return p[i].a < p[j].a
}

Score : 100 points

Problem Statement

There is a right triangle ABC with ∠ABC=90°.

Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.

It is guaranteed that the area of the triangle ABC is an integer.

Constraints

1 \leq |AB|,|BC|,|CA| \leq 100

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


package main

import (
	"bufio"
	"fmt"
	"strings"

	"os"
	"sort"
	"strconv"
)

//scanで一行づつ読み込む
var sc = bufio.NewScanner(os.Stdin)
var wtr = bufio.NewWriter(os.Stdout)

//sort
// array := []int{5, 1, 4, 2, 3}
// sort.Sort(sort.IntSlice(array))

func main() {
	// a := make([]int, n)
	n := nextLine()
	n2 := strings.Split(n, " ")
	arr := []int{}
	for _, i := range n2 {
		j, _ := strconv.Atoi(i)
		arr = append(arr, j)
	}
	sort.Sort(sort.IntSlice(arr))
	a, b := arr[0], arr[1]

	fmt.Fprintln(wtr, (a*b)/2)
	_ = wtr.Flush()
}

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
}

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

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

func main() {
	n := nextInt()

	nn := make([]int, 10000, 10000)
	mm := map[int]int{}

	nn[0] = n
	mm[n]++

	i := 1
	for {
		var re int
		v := nn[i-1]
		if v%2 == 0 {
			nn[i] = v / 2
			re = v / 2
		} else {
			nn[i] = 3*v + 1
			re = 3*v + 1
		}

		mm[re]++
		if mm[re] > 1 {
			fmt.Println(i + 1)
			return
		}
		i++
	}
}

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


package main

import "fmt"

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

	h := make([]int, n)
	for i:=range h {
		fmt.Scan(&h[i])
	}
	g := make([]int, n-1)
	if n == 1 {
		fmt.Println(h[0])
		return
	}

	for i:=1;i<n;i++ {
		if h[i-1] <= h[i] {
			g[i-1] = 1
		} else {
			g[i-1] = -1
		}
	}
	var ans int
	if g[0] == -1 {
		ans = h[0]
	} else {
		ans = 0
	}
	for i:=1;i<n-1;i++ {
		if g[i-1] == -1 && g[i] == 1 {
			ans -=  h[i]
		} else if g[i-1] == 1 && g[i] == -1 {
			ans += h[i]
		}
		if g[i] == 1 && i == n-2 {
			ans += h[n-1]
		}
	}

	fmt.Println(ans)
}

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


package main

import "fmt"

func main() {
	var n int
	_, _ = fmt.Scan(&n)
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		var tmp int
		_, _ = fmt.Scan(&tmp)
		arr[i] = tmp
	}
	count := 0
	for {
		sum := 0
		flg := false
		for i := 0; i < n; i++ {
			if arr[i] > 0 {
				arr[i]--
				if !flg {
					count++
				}
				flg = true
			} else {
				flg = false
			}
			sum += arr[i]
		}
		if sum == 0 {
			break
		}
	}
	fmt.Println(count)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	// "regexp"
)

/* sort */
type pair struct {
	index  int64
	p1, p2 interface{}
}
type pairs []pair

func (slice pairs) Len() int {
	return len(slice)
}

func (slice pairs) Less(i, j int) bool {
	return slice[i].index < slice[j].index
}

func (slice pairs) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

/* sort */
type Int64Slice []int64

func (slice Int64Slice) Len() int {
	return len(slice)
}

func (slice Int64Slice) Less(i, j int) bool {
	return slice[i] < slice[j]
}

func (slice Int64Slice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}
func Int64s(a []int64)                    { sort.Sort(Int64Slice(a)) }
func Int64sSliceAreSorted(a []int64) bool { return sort.IsSorted(Int64Slice(a)) }

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
	INF            = 1e8
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	di      = []int64{-1, 0, 1, 0}
	dj      = []int64{0, -1, 0, 1}
	di8     = []int64{-1, -1, 0, 1, 1, 1, 0, -1}
	dj8     = []int64{0, -1, -1, -1, 0, 1, 1, 1}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	correct := []int64{1, 4, 7, 9}
	N1, N2, N3, N4 := readInt(), readInt(), readInt(), readInt()
	a := []int64{N1, N2, N3, N4}
	Int64s(correct)
	Int64s(a)
	if aryEq(correct, a) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

/*==========================================
 *             Library
 *==========================================*/
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
}
func doubleAry(h int64, w int64, init int64) (res [][]int64) {
	res = make([][]int64, h)
	for i := int64(0); i < h; i++ {
		res[i] = make([]int64, w)
		for j := int64(0); j < w; j++ {
			res[i][j] = init
		}
	}
	return
}

func aryEq(a []int64, b []int64) bool {
	return reflect.DeepEqual(a, b)
}

func clone(n []int64) (r []int64) {
	r = make([]int64, len(n))
	for i := 0; i < len(n); i++ {
		r[i] = n[i]
	}
	return
}
func write(s string) {
	writer.WriteString(s)
}

func print() {
	writer.Flush()
}

// scanner.Split(bufio.ScanWords) をコメントアウトしないと使用不可
func readLine() (s string) {
	if scanner.Scan() {
		s = scanner.Text()
	}
	return s
}

func readInt() (read int64) {
	scanner.Scan()
	read, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func readFloat() (read float64) {
	scanner.Scan()
	read, err := strconv.ParseFloat(scanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return
}

func readRunes() (read []rune) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, v)
	}
	return
}

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

func readStrings() (read []string) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, string(v))
	}
	return
}

func s2i(s string) int64 {
	var intVal, e = strconv.ParseInt(s, 10, 64)
	if e != nil {
		panic(e)
	}
	return intVal
}

func i2s(i int64) string {
	var strVal = strconv.FormatInt(i, 10)
	return strVal
}

func s2f(s string) float64 {
	var floatVal, e = strconv.ParseFloat(s, 64)
	if e != nil {
		panic(e)
	}
	return floatVal
}

func abs(i int64) int64 {
	return int64(math.Abs(float64(i)))
}

func max(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans < v {
			ans = v
		}
	}
	return ans
}
func min(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans > v {
			ans = v
		}
	}
	return ans
}

func sum(i []int64) int64 {
	sum := int64(0)
	for _, val := range i {
		sum += val
	}
	return sum
}

func split(s string) []string {
	return strings.Fields(s)
}

func strAry2intAry(strs []string) []int64 {
	var ret = make([]int64, 0, len(strs))
	for _, str := range strs {
		var intVal = s2i(str)
		ret = append(ret, intVal)
	}
	return ret
}

func intAry2strAry(nums []int64) []string {
	var ret = make([]string, 0, len(nums))
	for _, num := range nums {
		var strVal = i2s(num)
		ret = append(ret, strVal)
	}
	return ret
}

func ary2str(strs []string) string {
	return strings.Join(strs, " ")
}

func reverse(res []int64) []int64 {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
func reverseStr(res []string) []string {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}

func ini(res []int, init int) {
	if len(res) == 0 {
		return
	}
	res[0] = init
	for i := 0; i < len(res); i++ {
		copy(res[i:], res[:i])
	}
}

//
// func regexpExample() {
//     // Your code here!
//     var str = "13:20"
//     r := regexp.MustCompile(`(\d+):(\d+)`)
//     fmt.Println(r.FindStringSubmatch(str))
// }

// type Country struct {
//     gold int
//     silver int
//     blonze int
// }

// // 複数ソートのサンプル
// func stableSortExample() []Country{
//     var country = []Country {
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:3, blonze:2},
//         {gold:1, silver:3, blonze:3},
//     }
//     sort.SliceStable(country, func(i, j int) bool { return country[i].blonze > country[j].blonze })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].silver > country[j].silver })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].gold > country[j].gold })
//     return country
// }

Score : 100 points

Problem Statement

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

0 \leq N_1, N_2, N_3, N_4 \leq 9

N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get 1974 by swapping N_2 and N_3.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have 1974 before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO


// ProblemURL : https://atcoder.jp/contests/keyence2019/tasks/keyence2019_b
// ---------------------------------------------
package main

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

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func diff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}
func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func smaller(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func largest(a, b, c int) (lgst int) {
	if a > b {
		lgst = a
	} else {
		lgst = b
	}
	if c > lgst {
		lgst = c
	}
	return
}
func smallest(a, b, c int) (slst int) {
	if a < b {
		slst = a
	} else {
		slst = b
	}
	if c < slst {
		slst = c
	}
	return
}
func intsMax(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func max: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa > val {
			idx, val = i, aa
		}
	}
	return
}
func intsMin(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func min: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa < val {
			idx, val = i, aa
		}
	}
	return
}
func intsSum(a []int) int {
	res := 0
	for _, v := range a {
		res += v
	}
	return res
}
func isEven(n int) bool            { return n&1 == 0 }
func isOdd(n int) bool             { return n&1 == 1 }
func swap(a int, b int) (int, int) { return b, a }
func calcMod(n int) int            { return n % mod }
func ceil(x float64) int           { return int(math.Ceil(x)) }
func pow(x, y int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z *= x
		}
		x *= x
	}
	return z
}
func powMod(x, y int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z = (z * x) % mod
		}
		x = (x * x) % mod
	}
	return z
}
func sigmaK(n int) int          { return n * (n + 1) / 2 }
func sigmaKK(n int) int         { return (n * (n + 1) / 2) * (2*n + 1) / 3 }
func intsJoin(a, b []int) []int { return append(a, b...) }
func intsClear(a []int) []int   { return a[:0] }
func intsCopy(a []int) []int    { return append([]int(nil), a...) }
func intsSorted(a []int) []int {
	s := intsCopy(a)
	sort.Ints(s)
	return s
}
func intsReverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func intsFill(a []int, val int) {
	for i := 0; i < len(a); i++ {
		a[i] = val
	}
	return
}
func intsPeekBack(a []int) int {
	if len(a) == 0 {
		panic("func peekBack: zero length slice")
	}
	return a[len(a)-1]
}
func intsPeekFront(a []int) int {
	if len(a) == 0 {
		panic("func peekFront: zero length slice")
	}
	return a[0]
}
func intsPopBack(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popBack: zero length slice")
	}
	return a[len(a)-1], a[:len(a)-1]
}
func intsPopFront(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popFront: zero length slice")
	}
	return a[0], a[1:]
}
func intsPushBack(a []int, x int) []int  { return append(a, x) }
func intsPushFront(a []int, x int) []int { return append([]int{x}, a...) }
func chmax(a *int, b int) {
	if *a < b {
		*a = b
	}
}
func chmin(a *int, b int) {
	if *a > b {
		*a = b
	}
}
func strUpperCase(s string) string { return strings.ToUpper(s) }
func strLowerCase(s string) string { return strings.ToLower(s) }

var (
	sc = bufio.NewScanner(os.Stdin)
	bw = bufio.NewWriterSize(os.Stdout, maxBufSize)
)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1e7), 1e7)
}
func ru() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}
func ri() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func ri64() (n int64) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int64(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func rf64() float64 {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}
func rs() string {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Text()
}
func rb() []byte {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Bytes()
}
func rr() []rune {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return []rune(sc.Text())
}
func ris(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri()
	}
	return s
}
func risZeroBased(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri() - 1
	}
	return s
}
func ri64s(n int) []int64 {
	s := make([]int64, n)
	for i := range s {
		s[i] = ri64()
	}
	return s
}
func rss(n int) []string {
	s := make([]string, n)
	for i := range s {
		s[i] = rs()
	}
	return s
}
func pf(format string, a ...interface{}) {
	if _, err := fmt.Fprintf(bw, format, a...); err != nil {
		panic(err)
	}
}
func pln(a ...interface{}) {
	if _, err := fmt.Fprintln(bw, a...); err != nil {
		panic(err)
	}
}
func pall(a []int) {
	for _, v := range a {
		fmt.Fprintln(bw, v)
	}
}
func pallol(a []int) {
	s := fmt.Sprint(a)
	if _, err := fmt.Fprintln(bw, s[1:len(s)-1]); err != nil {
		panic(err)
	}
}
func dbg(a ...interface{}) {
	if _, err := fmt.Fprintln(os.Stderr, a...); err != nil {
		panic(err)
	}
}
func YESorNO(b bool) string {
	if b {
		return "YES"
	} else {
		return "NO"
	}
}
func YesOrNo(b bool) string {
	if b {
		return "Yes"
	} else {
		return "No"
	}
}
func main() {
	solve()
	bw.Flush()
}

const (
	maxBufSize = 1e6

	alphabetUpper = "abcdefghijklmnopqrstuvwxyz"
	alphabetLower = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// maxInt64  = 9223372036854775807  // 9e18
	// maxInt32  = 2147483647           // 2e9
	// maxUint64 = 18446744073709551615 // 1e19
	inf = 1 << 60
	mod = 1e9 + 7
)

type pair struct{ a, b int }
type point struct{ x, y int }

func solve() {
	s := rs()

	t := "keyence"
	ok := false
	for i := 0; i <= 7; i++ {
		j := 7 - i
		if s[:i]+s[len(s)-j:] == t {
			ok = true
		}
	}

	if ok {
		pln("YES")
	} else {
		pln("NO")
	}
}

Score : 200 points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string.

Constraints

The length of S is between 7 and 100 (inclusive).

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


package main

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

var in = bufio.NewScanner(os.Stdin)

func main() {
	n := atoi()
	slice := atoiSlice()
	a, b := slice[0], slice[1]
	p := make([]int, n)
	slice = atoiSlice()
	for i := 0; i < n; i++ {
		p[i] = slice[i]
	}

	var cnt int
	var state int
	enc := map[int]bool{}
	for {
		for i := 0; i < n; i++ {
			if enc[i] {
				continue
			}

			if state == 0 && p[i] <= a {
				enc[i] = true
				state++
				continue
			}
			if state == 1 && p[i] > a && p[i] <= b {
				enc[i] = true
				state++
				continue
			}
			if state == 2 && p[i] > b {
				enc[i] = true
				state = 0
				cnt++
				break
			}
		}
		if state == 0 {
			break
		}
	}

	fmt.Println(cnt)
}

func atoi() int {
	if !in.Scan() {
		panic("eof")
	}
	s := in.Text()
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return i
}

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

func atoiSlice() []int {
	if !in.Scan() {
		panic("eof")
	}
	s := in.Text()
	sp := strings.Split(s, " ")
	e := make([]int, len(sp))
	for i, s := range sp {
		e[i] = atoiStr(s)
	}
	return e
}

Score : 200 points

Problem Statement

You have written N problems to hold programming contests.
The i-th problem will have a score of P_i points if used in a contest.

With these problems, you would like to hold as many contests as possible under the following condition:

A contest has three problems. The first problem has a score not greater than A points, the second has a score between A + 1 and B points (inclusive), and the third has a score not less than B + 1 points.

The same problem should not be used in multiple contests.
At most how many contests can be held?

Constraints

3 \leq N \leq 100

1 \leq P_i \leq 20 (1 \leq i \leq N)

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

Two contests can be held by putting the first, second, third problems and the fourth, fifth, sixth problems together.

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

No contest can be held, because there is no problem with a score of A = 3 or less.

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1


package main

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

var H, W int
var S []string

var dy = []int{1, 0, -1, 0}
var dx = []int{0, 1, 0, -1}

var cnt int

func main() {
	log.SetFlags(log.Lshortfile)
	H = nextInt()
	W = nextInt()
	S = make([]string, H)
	for i := 0; i < H; i++ {
		S[i] = nextString()
	}
	for i := 0; i < H; i++ {
		for j := 0; j < W; j++ {
			if S[i][j] == '#' {
				check := make([]int, H*W)
				check[i*W+j]++
				s(i, j, check)
			}
		}
	}
	fmt.Println(cnt)
}
func s(h int, w int, check []int) {
	check[h*W+w]++
	for d := 0; d < 4; d++ {
		ny := h + dy[d]
		nx := w + dx[d]
		if ny >= 0 && ny < H && nx >= 0 && nx < W {
			if check[ny*W+nx] > 0 {
				continue
			}
			if S[ny][nx] != S[h][w] {
				if S[ny][nx] == '.' {
					cnt++
				}
				check[ny*W+nx]++
				s(ny, nx, check)
			}
		}
	}
}

func intPow(a, b int) int {
	return int(math.Pow(float64(a), float64(b)))
}

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func intMax(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}
func intMin(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}
func intSum(a []int) (r int) {
	for i := range a {
		r += a[i]
	}
	return r
}
func intAbs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

type pair struct {
	a, b int
}

type pairs []pair

func (p pairs) Len() int {
	return len(p)
}
func (p pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (p pairs) Less(i, j int) bool {
	return p[i].b < p[j].b
}

var nextReader func() string

func init() {
	nextReader = newScanner()
}

func newScanner() func() string {
	r := bufio.NewScanner(os.Stdin)
	r.Buffer(make([]byte, 1024), int(1e+11))
	r.Split(bufio.ScanWords)
	return func() string {
		r.Scan()
		return r.Text()
	}
}
func nextString() string {
	return nextReader()
}
func nextInt64() int64 {
	v, _ := strconv.ParseInt(nextReader(), 10, 64)
	return v
}
func nextInt() int {
	v, _ := strconv.Atoi(nextReader())
	return v
}
func nextInts(n int) []int {
	r := make([]int, n)
	for i := 0; i < n; i++ {
		r[i] = nextInt()
	}
	return r
}
func nextFloat64() float64 {
	f, _ := strconv.ParseFloat(nextReader(), 64)
	return f
}

Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6


// Package main provides
//
// File:  c.go
// Author: ymiyamoto
//
// Created on Sat Jan 12 21:05:35 2019
//
package main

import "fmt"

const (
	WHITE = '.'
	BLACK = '#'
)

func dfs(visited [][]bool, board []string, x, y int, color rune) int {
	visited[x][y] = true

	ret := 0
	if rune(board[x][y]) == color {
		if color == WHITE {
			ret++
		}
		for _, d := range [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} {
			dx := x + d[0]
			dy := y + d[1]

			nextColor := WHITE
			if color == nextColor {
				nextColor = BLACK
			}

			if 0 <= dx && dx < len(board) && 0 <= dy && dy < len(board[0]) && visited[dx][dy] == false {
				ret += dfs(visited, board, dx, dy, nextColor)
			}
		}
	}

	return ret
}

func routes(board []string, x, y int, color rune) int {
	visited := make([][]bool, len(board))
	for i := range visited {
		visited[i] = make([]bool, len(board[0]))
	}

	return dfs(visited, board, x, y, color)
}

type pair struct {
	x, y int
}

func main() {
	var H, W int
	fmt.Scan(&H, &W)
	board := make([]string, H)
	for i := range board {
		fmt.Scan(&board[i])
	}

	blacks := make([]pair, 0)
	for i := 0; i < H; i++ {
		for j := 0; j < W; j++ {
			if board[i][j] == BLACK {
				blacks = append(blacks, pair{x: i, y: j})
			}
		}
	}

	ans := 0
	for _, b := range blacks {
		ans += routes(board, b.x, b.y, BLACK)
	}

	fmt.Println(ans)
}


package main

import "fmt"

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

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

func maxs(xs []int) int {
	var ans int
	for _, x := range xs {
		if ans < x {
			ans = x
		}
	}
	return ans
}

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

func main() {
	var n int
	fmt.Scanf("%d", &n)

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

	dp := make([][]int, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int, 3)
	}
	dp[0] = []int{a[0], b[0], c[0]}

	for i := 1; i < n; i++ {
		// aを選んだ場合
		dp[i][0] = max(dp[i][0], dp[i-1][1]+a[i]) // 1つ前でbを選んだ場合
		dp[i][0] = max(dp[i][0], dp[i-1][2]+a[i]) // 1つ前でcを選んだ場合
		// bを選んだ場合
		dp[i][1] = max(dp[i][1], dp[i-1][0]+b[i]) // 1つ前でaを選んだ場合
		dp[i][1] = max(dp[i][1], dp[i-1][2]+b[i]) // 1つ前でcを選んだ場合
		// cを選んだ場合
		dp[i][2] = max(dp[i][2], dp[i-1][0]+c[i]) // 1つ前でaを選んだ場合
		dp[i][2] = max(dp[i][2], dp[i-1][1]+c[i]) // 1つ前でbを選んだ場合
	}

	fmt.Println(maxs(dp[len(dp)-1]))
}

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func max(v1, v2 int) int {
	if v1 > v2 {
		return v1
	}
	return v2
}

func main() {
	var dp [100005][3]int
	sc.Split(bufio.ScanWords)
	n := nextInt()
	var abc [3][]int
	for i := 0; i < n; i++ {
		abc[0] = append(abc[0], nextInt())
		abc[1] = append(abc[1], nextInt())
		abc[2] = append(abc[2], nextInt())
	}

	for j := 0; j < 3; j++ {
		dp[0][j] = abc[j][0]
	}

	for i := 1; i < n; i++ {
		dp[i][0] = max(dp[i-1][1]+abc[0][i], dp[i-1][2]+abc[0][i])
		dp[i][1] = max(dp[i-1][0]+abc[1][i], dp[i-1][2]+abc[1][i])
		dp[i][2] = max(dp[i-1][0]+abc[2][i], dp[i-1][1]+abc[2][i])
	}

	ans := max(max(dp[n-1][0], dp[n-1][1]), dp[n-1][2])
	fmt.Println(ans)
}


// Package main provides
//
// File:  c.go
// Author: ymiyamoto
//
// Created on Wed Jan  9 23:27:55 2019
//
package main

import (
	"fmt"
	"sort"
)

func max(slice ...int) int {
	sort.Ints(slice)
	return slice[len(slice)-1]
}

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

	a, b, c := make([]int, N), make([]int, N), make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scan(&a[i], &b[i], &c[i])
	}

	dp := make([][3]int, N+1)
	for i := 1; i <= N; i++ {
		dp[i][0] = a[i-1] + max(dp[i-1][1], dp[i-1][2])
		dp[i][1] = b[i-1] + max(dp[i-1][2], dp[i-1][0])
		dp[i][2] = c[i-1] + max(dp[i-1][0], dp[i-1][1])
	}

	fmt.Println(max(dp[N][0], dp[N][1], dp[N][2]))
}


package main

import (
	"fmt"
	"math"
)

type Item struct {
	Value  int
	Weight int
}

func main() {
	var ItemNumber int
	var MaxWeight int
	const maxW = 100000

	sack := []Item{}

	fmt.Scanln(&ItemNumber, &MaxWeight)

	dp := make([]int, maxW+1)
	fill(dp, math.MaxInt64)
	dp[0] = 0

	for i := 0; i < ItemNumber; i++ {
		X := Item{}
		fmt.Scanln(&X.Weight, &X.Value)
		sack = append(sack, X)
	}
	value := Knapsack(sack, dp,ItemNumber,MaxWeight)
	fmt.Print(value)
}

func Knapsack(sacks []Item,dp []int, N int, W int) int{
	const maxW = 100000
	for i := 0; i < N; i++ {
		w := sacks[i].Weight
		v := sacks[i].Value
		for j := maxW - v; j >= 0; j-- {
			if dp[j] == math.MaxInt64  {
				continue
			}

			if dp[j]+w <= W {
				dp[j+v] = min(dp[j+v], dp[j]+w)
			}
		}
	}
	i := maxW
	for dp[i] == math.MaxInt64 {
		i--
	}
	return i
}

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

func fill(a []int, x int) {
	for i := 0; i < len(a); i++ {
		a[i] = x
	}
}

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


package main

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

var N int
var a, s []int

func main() {
	N = ReadInt()
	a = ReadInts(N)
	s = make([]int, N+1)
	for i := 0; i < N; i++ {
		s[i+1] = s[i] + a[i]
	}
	memo = make([][]int, N)
	for i := 0; i < N; i++ {
		memo[i] = make([]int, N)
	}
	fmt.Println(f(0, N-1))
}

var memo [][]int

func f(i, j int) int {
	if i == j {
		return 0
	}
	if j-1 == i {
		return a[i] + a[j]
	}
	if memo[i][j] > 0 {
		return memo[i][j]
	}
	v := Min(
		f(i, j-1)+s[j+1]-s[i],
		f(i, j-2)+a[j-1]+a[j]+s[j+1]-s[i],
		f(i+1, j)+s[j+1]-s[i],
		f(i+2, j)+a[i]+a[i+1]+s[j+1]-s[i],
	)
	memo[i][j] = v
	return v
}

func Min(xs ...int) int {
	min := xs[0]
	for _, x := range xs[1:] {
		if min > x {
			min = x
		}
	}
	return min
}

var reader = bufio.NewReader(os.Stdin)

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

Score : 100 points

Problem Statement

There are N slimes lining up in a row.
Initially, the i-th slime from the left has a size of a_i.

Taro is trying to combine all the slimes into a larger slime.
He will perform the following operation repeatedly until there is only one slime:

Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of x + y, where x and y are the sizes of the slimes before combining them. Here, a cost of x + y is incurred. The positional relationship of the slimes does not change while combining slimes.

Find the minimum possible total cost incurred.

Constraints

All values in input are integers.

2 \leq N \leq 400

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 20 30 40

Sample Output 1

190

Taro should do as follows (slimes being combined are shown in bold):

(10, 20, 30, 40) → (30, 30, 40)

(30, 30, 40) → (60, 40)

(60, 40) → (100)

Sample Input 2

5
10 10 10 10 10

Sample Output 2

120

Taro should do, for example, as follows:

(10, 10, 10, 10, 10) → (20, 10, 10, 10)

(20, 10, 10, 10) → (20, 20, 10)

(20, 20, 10) → (20, 30)

(20, 30) → (50)

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

6
7 6 8 6 1 1

Sample Output 4

68

Taro should do, for example, as follows:

(7, 6, 8, 6, 1, 1) → (7, 6, 8, 6, 2)

(7, 6, 8, 6, 2) → (7, 6, 8, 8)

(7, 6, 8, 8) → (13, 8, 8)

(13, 8, 8) → (13, 16)

(13, 16) → (29)


package main

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

var (
	N    int
	h, a [212345]int
)

func readVariables() {
	N = nextInt()
	for i := 0; i < N; i++ {
		h[i] = nextInt()
	}
	for i := 0; i < N; i++ {
		a[i] = nextInt()
	}
}

func main() {
	readVariables()
	bit := NewBIT(N)
	answer := 0
	for i := 0; i < N; i++ {
		v := a[i] + bit.Accumulate(h[i]-1)
		bit.Add(h[i], v)
		// fmt.Println(bit.Nodes)
		answer = MaxInt(v, answer)
	}
	fmt.Println(answer)
}

/* 以下、テンプレート*/

var scanner *bufio.Scanner

func init() {
	Max := 1001001
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 0, Max), Max)
	scanner.Split(bufio.ScanWords)
}

//nextInt converts next token from stdin and returns integer value.
//nextInt panics when conversion into an integer fails.
func nextInt() int {
	if !scanner.Scan() {
		panic("No more token.")
	}
	num, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic("nextInt(): cannot convert to int: " + scanner.Text())
	}
	return num
}

func nextStr() string {
	if !scanner.Scan() {
		panic("No more token.")
	}
	return scanner.Text()
}

// MinInt は、2つの整数を受け取り、最小値を返します。
func MinInt(x, y int) int {
	if x < y {
		return x
	} else {
		return y
	}
}

//MaxInt は、2つの整数を受け取り、最大値を返します。
func MaxInt(x, y int) int {
	if x < y {
		return y
	} else {
		return x
	}
}

//AbsInt は、整数の絶対値を返します。
func AbsInt(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

//ModPow は整数の累乗関数で、剰余もサポートします。
//base^exponentの値をmoduleで割った余りを返します。
//moduloが1以下の場合には、剰余演算をしません。
//baseが負の値である場合には、返す値が負になることがあります。
func ModPow(base, exponent, modulo int) (result int) {
	result = 1
	for exponent > 0 {
		if exponent%2 == 1 {
			result *= base
			if modulo > 1 {
				result %= modulo
			}
		}
		base *= base
		if modulo > 1 {
			base %= modulo
		}
		exponent /= 2
	}
	return
}

//Gcd は、引数の整数全ての最大公約数を返します。
func Gcd(vals ...int) (result int) {
	if len(vals) == 0 {
		return
	}
	result = vals[0]
	for i := 1; i < len(vals); i++ {
		result = gcd(result, vals[i])
	}
	return
}

func gcd(x, y int) int {
	x, y = AbsInt(x), AbsInt(y)
	for y > 0 {
		x, y = y, x%y
	}
	return x
}

//Lcm は、与えられた整数の最小公倍数を返します。
func Lcm(vals ...int) (result int) {
	if len(vals) == 0 {
		return
	}
	result = vals[0]
	for i := 1; i < len(vals); i++ {
		result = lcm(result, vals[i])
	}
	return
}

func lcm(x, y int) int {
	return x * y / gcd(x, y)
}

type BIT struct {
	Nodes []int
	Size  int
}

func NewBIT(size int) *BIT {
	bit := new(BIT)
	bit.Size = size
	bit.Nodes = make([]int, size+1)
	return bit
}

func (bit *BIT) Add(location, value int) {
	for i := location + 1; i <= bit.Size; i += (i & -i) {
		bit.Nodes[i] = MaxInt(bit.Nodes[i], value)
	}
}

func (bit *BIT) Sum(start, end int) int {
	return bit.Accumulate(end) - bit.Accumulate(start-1)
}

func (bit *BIT) Accumulate(end int) (result int) {
	result = -1234567890
	if end >= bit.Size {
		end = bit.Size - 1
	}
	for i := end + 1; i > 0; i -= i & -i {
		result = MaxInt(bit.Nodes[i], result)
	}
	return
}

Score : 100 points

Problem Statement

There are N flowers arranged in a row.
For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively.
Here, h_1, h_2, \ldots, h_N are all distinct.

Taro is pulling out some flowers so that the following condition is met:

The heights of the remaining flowers are monotonically increasing from left to right.

Find the maximum possible sum of the beauties of the remaining flowers.

Constraints

All values in input are integers.

1 \leq N \leq 2 × 10^5

1 \leq h_i \leq N

h_1, h_2, \ldots, h_N are all distinct.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N
a_1 a_2 \ldots a_N

Output

Print the maximum possible sum of the beauties of the remaining flowers.

Sample Input 1

4
3 1 4 2
10 20 30 40

Sample Output 1

60

We should keep the second and fourth flowers from the left.
Then, the heights would be 1, 2 from left to right, which is monotonically increasing, and the sum of the beauties would be 20 + 40 = 60.

Sample Input 2

1
1
10

Sample Output 2

10

The condition is met already at the beginning.

Sample Input 3

5
1 2 3 4 5
1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

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

Sample Output 4

31

We should keep the second, third, sixth, eighth and ninth flowers from the left.


package main

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

const Mod = int(1e9) + 7

func main() {
	N, K := ReadInt(), ReadInt()
	a := make([][]int, N)
	for i := 0; i < N; i++ {
		a[i] = ReadInts(N)
	}

	g := Pow(a, K)
	ans := 0
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			ans += g[i][j]
			ans %= Mod
		}
	}
	fmt.Println(ans)
}

// 行列の積
func Mul(A [][]int, B [][]int) [][]int {
	C := make([][]int, len(A))
	for i := 0; i < len(A); i++ {
		C[i] = make([]int, len(B))
	}
	for i := 0; i < len(A); i++ {
		for k := 0; k < len(B); k++ {
			for j := 0; j < len(B[0]); j++ {
				C[i][j] += +A[i][k] * B[k][j]
				C[i][j] %= Mod
			}
		}
	}
	return C
}

// 行列の累乗
func Pow(A [][]int, n int) [][]int {
	B := make([][]int, len(A))
	for i := 0; i < len(A); i++ {
		B[i] = make([]int, len(A))
		B[i][i] = 1 // 単位行列にする
	}
	for n > 0 {
		if n&1 == 1 {
			B = Mul(B, A)
		}
		A = Mul(A, A)
		n >>= 1
	}
	return B
}

var reader = bufio.NewReader(os.Stdin)

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

Score : 100 points

Problem Statement

There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N.

For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j.
If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not.

Find the number of different directed paths of length K in G, modulo 10^9 + 7.
We will also count a path that traverses the same edge multiple times.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 10^{18}

a_{i, j} is 0 or 1.

a_{i, i} = 0

Input

Input is given from Standard Input in the following format:

N K
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print the number of different directed paths of length K in G, modulo 10^9 + 7.

Sample Input 1

4 2
0 1 0 0
0 0 1 1
0 0 0 1
1 0 0 0

Sample Output 1

6

G is drawn in the figure below:

There are six directed paths of length 2:

1 → 2 → 3

1 → 2 → 4

2 → 3 → 4

2 → 4 → 1

3 → 4 → 1

4 → 1 → 2

Sample Input 2

3 3
0 1 0
1 0 1
0 0 0

Sample Output 2

3

G is drawn in the figure below:

There are three directed paths of length 3:

1 → 2 → 1 → 2

2 → 1 → 2 → 1

2 → 1 → 2 → 3

Sample Input 3

6 2
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0

Sample Output 3

1

G is drawn in the figure below:

There is one directed path of length 2:

4 → 5 → 6

Sample Input 4

1 1
0

Sample Output 4

0

Sample Input 5

10 1000000000000000000
0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 0 1 0 1
1 1 1 0 1 1 0 1 1 0
0 1 1 1 0 1 0 1 1 1
0 0 0 1 0 0 1 0 1 0
0 0 0 1 1 0 0 1 0 1
1 0 0 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
1 0 1 1 1 0 1 1 1 0

Sample Output 5

957538352

Be sure to print the count modulo 10^9 + 7.


package main

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

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 scanStrings(len int) (strings []string) {
	var str string
	for i := 0; i < len; i++ {
		fmt.Scanf("%s", &str)
		strings = append(strings, str)
	}
	return
}

func main() {
	count := 0

	var str string
	fmt.Scanf("%s", &str)
	for {
		if strings.Contains(str, "BW") {
			str2 := strings.Replace(str, "BW", "WB", -1)
			for i := 0; i < len(str2); i++ {
				if str[i] != str2[i] {
					count++
				}
			}
			str = str2
			str = strings.Replace(str, "BBB", "BB", -1)
			str = strings.Replace(str, "WWW", "WW", -1)
		} else {
			break
		}
	}
	fmt.Println(count / 2)
}

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

1 \leq |S| \leq 2\times 10^5

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	sum, max := 0, 0
	for i := 0; i < n; i++ {
		var tmp int
		fmt.Scan(&tmp)
		sum += tmp
		if max < tmp {
			max = tmp
		}
	}
	fmt.Println(sum - (max / 2))
}

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


// B - Christmas Eve Eve
// https://atcoder.jp/contests/abc115/tasks/abc115_b
// +build ignore

package main

import (
	"fmt"
)

func main() {
	var n, tmp, ans int
	fmt.Scan(&n)
	p := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&p[i])
		ans += p[i]
		if p[i] > tmp {
			tmp = p[i]
		}
	}
	ans = ans - (tmp / 2)
	fmt.Println(ans)
}


package main

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

func main() {
	sc := NewScanner()

	n := sc.NextInt()
	ans := 0
	mx := 0
	for i := 0; i < n; i++ {
		tmp := sc.NextInt()
		ans += tmp
		if mx < tmp {
			mx = tmp
		}
	}
	ans -= (mx / 2)
	fmt.Printf("%+v\n", ans) // output for debug

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			result = append(result, v)
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	result = append(result, v)

	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
}

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

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

func main() {
	n := nextInt()
	k := nextInt()

	h := make([]int, 0, n)
	for i := 0; i < n; i++ {
		h = append(h, nextInt())
	}

	IntReverse(h)

	re := 1000000000
	r := k - 1
	for index := 0; r < n; index++ {
		if h[r]-h[index] < re {
			re = h[r] - h[index]
		}
		r += k - 1
	}

	fmt.Println(re)
}

func IntReverse(vv []int) {
	sort.Sort(sort.IntSlice(vv))
}

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


package main

import "fmt"

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

  if x == 3 || x == 5 || x == 7 {
    fmt.Println("YES")
  } else {
    fmt.Println("NO")
  }
}

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


package main

import "fmt"

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

	if x == 3 || x == 5 || x == 7 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


// Package main provides
//
// File:  a.go
// Author: ymiyamoto
//
// Created on Sun Dec  2 20:57:55 2018
//
package main

import "fmt"

var x int

func main() {
	fmt.Scan(&x)
	if x == 7 || x == 5 || x == 3 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}