Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:  Include a person to the chat ('Add' command).  Remove a person from the chat ('Remove' command).  Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.

Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:   +<name> for 'Add' command.  -<name> for 'Remove' command.  <sender_name>:<message_text> for 'Send' command.  <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.

Print a single number — answer to the problem.

+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

+Mike
-Mike
+Mike
Mike:Hi   I am here
-Mike
+Kate
-Kate

package main

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

var cs map[int]int = make(map[int]int)

func Init() {}
func Solve(io *FastIO) {
	var s string
	c := 0
	o := 0
	for i := 0; i < 100; i++ {
		s = io.NextLine()
		if s == "" {
			break
		}
		if s[0] == '+' {
			c++
		} else if s[0] == '-' {
			c--
		} else {
			o += c * (len(s) - 1 - strings.Index(s, ":"))
		}
	}
	io.Println(o)
}

type FastIO struct {
	//by megaspazz
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}
func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = res*10 + int(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = int64(-1)
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = res*10 + int64(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}
func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextInt()
	}
	return arr
}
func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}
func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextLong()
	}
	return arr
}
func (io *FastIO) NextString() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) NextLine() string {
	c := io.NextChar()
	if IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}
func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}
func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}
func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}
func IsLineBreakChar(c byte) bool {
	switch c {
	case 0, '\n', '\r':
		return true
	default:
		return false
	}
}
func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	users := map[string]int{}
	bs, _ := ioutil.ReadAll(os.Stdin)

	commands := bytes.Split(bs, []byte("\r\n"))
	result := 0
	for i := 0; i < len(commands); i++ {
		c := commands[i]
		if len(c) == 0 {
			continue
		}
		if c[0] == '+' {
			users[string(c[1:])] = 0
		} else if c[0] == '-' {
			delete(users, string(c[1:]))
		} else {
			keypair := bytes.Split(c, []byte(":"))
			result += (len(keypair[1]) * len(users))
		}
	}
	fmt.Printf("%d", result)
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	//"strconv"
	//"sort"
	//"unicode/utf8"
)

func main() {
	var a, b, pos int
	var err error
	var s string
	input := bufio.NewScanner(os.Stdin)
	//input.Split(bufio.ScanWords)

	for input.Scan() {
		if err == io.EOF {
			break
		}
		//input.Scan()
		s = input.Text()
		//fmt.Println(s)
		if s[0] == '+' {
			a++
		} else if s[0] == '-' {
			a--
		} else {
			for i, v := range s {
				if v == ':' {
					pos = i
				}
			}
			b += a * (int(len(s)) - pos - 1)
		}
	}
	fmt.Println(b)
}

package main

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

func main() {
	chatMembers := make(map[string]interface{})
	totalBytesSent := 0

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()
		line = strings.TrimSpace(line)

		if line[0] == '+' {
			name := line[1:]
			chatMembers[name] = struct{}{}
		} else if line[0] == '-' {
			name := line[1:]
			delete(chatMembers, name)
		} else {
			parts := strings.Split(line, ":")
			if len(parts) != 2 {
				fmt.Println("Invalid send message format")
				os.Exit(1)
			}

			_, message := parts[0], parts[1]
			messageBytes := []byte(message)
			totalBytesSent += len(messageBytes) * len(chatMembers)
		}
	}

	fmt.Println(totalBytesSent)
}

package main

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

var scanner *bufio.Scanner

func solve() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanLines)

	sent := 0
	perps := make(map[string]bool)
	for scanner.Scan() {
		line := scanner.Text()
		switch line[0] {
		case '-':
			delete(perps, line[1:])
			break
		case '+':
			perps[line[1:]] = true
			break
		default:
			idx := strings.Index(line, ":")
			sent += len(perps) * len(line[idx+1:])
		}
	}
	fmt.Println(sent)
}

func main() {
	solve()
}

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

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

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

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

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

  chatSize := 0
  result := 0
  for {
    line, err := reader.ReadString('\n')
    if err != nil {
      break
    }
    s := strings.TrimSpace(line)
    if s[0] == '+' {
      chatSize++
    } else if s[0] == '-' {
      chatSize--
    } else {
      parts := strings.Split(s, ":")
      result += chatSize * len(parts[1])
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

/*

A. Исходящий трафик чата
ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Последнее время Поликарп много трудится над новым проектом "Поличат". Следуя современным тенденциям IT индустрии, Поликарп решил, что в этом проекте непременно должен быть чат. Проведя пару часов за компьютером, Поликарп написал чат-сервер, который может выполнять три типа команд:

Добавить человека в чат (команда 'Добавить').
Удалить человека из чата (команда 'Удалить').
Отправить сообщение от кого-либо всем участникам чата, включая отправителя сообщения (команда 'Отправить').
Сейчас Поликарп хочет узнать, какое количество исходящего трафика пошлет его сервер при обработке набора команд.

Поликарп выяснил, что при обработке команды 'Добавить' или 'Удалить' сервер не посылает трафика вовсе, а при обработке команды 'Отправить' каждому из участников чата посылается l байт, где l — длина рассылаемого сообщения.

Так как у Поликарпа совсем нет свободного времени, он просит вас помочь с решением этой задачи.

Входные данные
	Входной файл будет содержать не более 100 команд. Каждая команда будет располагаться на своей строке и иметь длину не более 100 символов. Форматы команд будут следующими:

	+<имя> для команды 'Добавить'.
	-<имя> для команды 'Удалить'.
	<имя_отправителя>:<текст_сообщения> для команды 'Отправить'.
	<имя> и <имя_отправителя> — непустая последовательность латинских букв или цифр. <текст_сообщения> может содержать латинские буквы, цифры и пробелы, но не может начинаться или оканчиваться пробелом. <текст_сообщения> может быть пустой строкой.

Гарантируется, что входные данные корректны, то есть человек не будет добавлен в чат, если он там уже присутствует, не будет команды 'Удалить', если человека с таким именем нет в чате и тому подобное.

Имена, различающиеся исключительно регистром букв следует считать различными.

*/

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

type Command interface {
	cmd()
}

type Add string
type Remove string
type Message struct {
	from, text string
}

func (_ Add) cmd() {}
func (_ Remove) cmd() {}
func (_ Message) cmd() {}

func solve(cmds []Command) int {
	invited := map[string]bool{}

	bytes := 0
	for _, cmd := range cmds {
		switch val := cmd.(type) {
		case Add:
			invited[string(val)] = true
		case Remove:
			delete(invited, string(val))
		case Message:
			msg := Message(val)
			if invited[msg.from] {
				bytes += len(msg.text)*len(invited)
			}
		}
	}
	return bytes
}

func main() {
	cmds := []Command{}

	reader := bufio.NewReader(os.Stdin)
	for {
		bytes, _, err := reader.ReadLine()
		s := string(bytes)

		if len(s) == 0 || err != nil {
			break
		}

		switch s[0] {
		case '+':
			cmds = append(cmds, Add(s[1:]))
		case '-':
			cmds = append(cmds, Remove(s[1:]))
		default:
			i := strings.IndexByte(s, ':')
			cmds = append(cmds, Message{from: s[:i], text: s[i+1:]})
		}
	}
	fmt.Printf("%d\n", solve(cmds))
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    cnt, ans := 0, 0
    for scanner.Scan() {
        if scanner.Text()[0] == '+' {
            cnt++
        } else if scanner.Text()[0] == '-' {
            cnt--
        } else {
            for k, v := range scanner.Text() {
                if v == ':' {
                    ans += (len(scanner.Text())-k-1)*cnt
                    break
                }
            }
        }
    }
    fmt.Println(ans)
}

package main

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

func main() {
	z := bufio.NewScanner(os.Stdin)
	p, r := 0,0
	for z.Scan() {
		s := z.Text()
		switch s[0] {
			case '+': p++; break
			case '-': p--; break
			default:
				ss := strings.SplitN(s,":",2)
				r += p*len(strings.TrimSpace(ss[1]))
				break
		}
	}
	fmt.Println(r)
}

package main

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

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

	addPattern, _ := regexp.Compile("\\+([a-zA-Z0-9]*)")
	removePattern, _ := regexp.Compile("-([a-zA-Z0-9]*)")
	messagePattern, _ := regexp.Compile("([a-zA-Z0-9]*):(.*)")

	userDb := make(map[string]bool)
	totalSize := 0
	for scanner.Scan() {
		line := scanner.Text()
		if addPattern.MatchString(line) {
			match := addPattern.FindStringSubmatch(line)
			user := match[1]
			userDb[user] = true
		} else if removePattern.MatchString(line) {
			match := removePattern.FindStringSubmatch(line)
			user := match[1]
			delete(userDb, user)
		} else if messagePattern.MatchString(line) {
			match := messagePattern.FindStringSubmatch(line)
			_, message := match[1], match[2]
			totalSize += len(userDb) * len(message)
		}
	}
	fmt.Println(totalSize)
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int
	var err error

	scan := bufio.NewScanner(os.Stdin)

	for scan.Scan() {
		if err == io.EOF || scan.Err() != nil {
			break
		}
		ln := scan.Text()
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}
	}

	// fmt.Println(traffic)
	fmt.Printf("%d\n", traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var traffic, count int
	var cmd string
	for scanner.Scan() {
		cmd = scanner.Text()
		if cmd == "" {
			break
		}
		if string(cmd[0]) == "+" {
			count += 1
			continue
		}
		if string(cmd[0]) == "-" {
			count -= 1
			continue
		}
		traffic += count * len(strings.Split(cmd, ":")[1])
	}
	fmt.Fprintln(writer, traffic)
}

package main

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

func main() {
	room := make(map[string]bool)
	rdr := bufio.NewReader(os.Stdin)
	z := 0
	for {
		if cmd, _, e := rdr.ReadLine(); e != nil {
			break
		} else {
			switch cmd[0] {
			case '+':
				room[string(cmd[1:])] = true
			case '-':
				delete(room, string(cmd[1:]))
			default:
				l := len(cmd) - strings.Index(string(cmd), ":") - 1
				z += l * len(room)
			}

		}
	}
	fmt.Println(z)
}

package main

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

func main() {
	count := 0
	traffic := 0
	line, err := nextLine()
	for err == nil {
		if len(line) == 0 {

		} else if strings.HasPrefix(line, "+") {
			count++
		} else if strings.HasPrefix(line, "-") {
			count--
		} else {
			c := strings.Split(line, ":")
			traffic += count * len(c[1])
		}
		line, err = nextLine()
	}
	printf("%d\n", traffic)
}

var lineScanner *bufio.Scanner
var wordScanner *bufio.Scanner

func init() {
	lineScanner = bufio.NewScanner(os.Stdin)
	wordScanner = bufio.NewScanner(strings.NewReader(""))
	wordScanner.Split(bufio.ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = bufio.NewScanner(strings.NewReader(line))
		wordScanner.Split(bufio.ScanWords)
	}
	return wordScanner.Text()
}

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

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

package main

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

func main() {
	var users, count uint
	reader := bufio.NewReader(os.Stdin)

	for {
		str, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}

		switch str[0] {
		case '+':
			users++
		case '-':
			users--
		default:
			//msg := str[strings.Index(str, ":"):]
			msg := strings.Split(string(str), ":")[1]
			count += uint(len(msg)) * users
		}
	}
	fmt.Println(count)
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	users := map[string]int{}
	bs, _ := ioutil.ReadAll(os.Stdin)

	commands := bytes.Split(bs, []byte("\n"))
	result := 0

	for i := 0; i < len(commands); i++ {
		c := commands[i]
		if len(c) == 0 {
			continue
		}
		if c[0] == '+' {
			users[string(c[1:])] = 0
		} else if c[0] == '-' {
			delete(users, string(c[1:]))
		} else {
			keypair := bytes.Split(c, []byte(":"))
			result += (len(keypair[1]) * len(users))
		}
	}
	fmt.Printf("%d", result)
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	users := map[string]int{}
	bs, _ := ioutil.ReadAll(os.Stdin)

	commands := bytes.Split(bs, []byte("\n"))
	result := 0
	for i := 0; i < len(commands); i++ {
		fmt.Printf("%d %d %s\n", result, len(commands), string(commands[i]))
		c := commands[i]
		if len(c) == 0 {
			continue
		}
		if c[0] == '+' {
			users[string(c[1:])] = 0
		} else if c[0] == '-' {
			delete(users, string(c[1:]))
		} else {
			keypair := bytes.Split(c, []byte(":"))
			result += (len(keypair[1]) * len(users))
		}
	}
	fmt.Printf("%d", result)
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	users := map[string]int{}
	bs, _ := ioutil.ReadAll(os.Stdin)

	commands := bytes.Split(bs, []byte("\r\n"))
	result := 0
	for i := 0; i < len(commands); i++ {
		fmt.Printf("%d %d %s\n", result, len(commands), string(commands[i]))
		c := commands[i]
		if len(c) == 0 {
			continue
		}
		if c[0] == '+' {
			users[string(c[1:])] = 0
		} else if c[0] == '-' {
			delete(users, string(c[1:]))
		} else {
			keypair := bytes.Split(c, []byte(":"))
			result += (len(keypair[1]) * len(users))
		}
	}
	fmt.Printf("%d", result)
}

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

func main() {
	var a,b,pos int
	var s string
        for {
        	n, err := fmt.Scanf("%s", &s)
        	if n == 0 || err != nil { break }
 	        if s[0]=='+' {
 	        	a++
 	        } else if s[0]=='-' {
 	        	a--
 	        } else {
 	        	for i:=0;i<len(s);i++ {
 	        		if s[i]==':' {
 	        			pos=i
 	        		}
 	        	}
 	        	b+=a*int(len(s))-pos-1
 	        }
 	}
 	fmt.Println(b)
}

package main

import (
    //"bufio"
    "fmt"
    "io"
    //"os"
    //"strconv"
    //"sort"
    //"unicode/utf8"
)

func main() {
    var a, b, pos int
    var err error
    var s string
    //input := bufio.NewScanner(os.Stdin)
    //input.Split(bufio.ScanWords)

    for {
        if err == io.EOF {
            break
        }
        _, err = fmt.Scan(&s)
        //fmt.Println(s)
        if s[0] == '+' {
            a++
        } else if s[0] == '-' {
            a--
        } else {
            for i,v:= range s {
            	if v == ':' {
                    pos = i
                }
            }
            b += a*(int(len(s)) - pos - 1)
        }
    }
    fmt.Println(b)
}

package main

import (
    //"bufio"
    "fmt"
    "io"
    //"os"
    //"strconv"
    //"sort"
    //"unicode/utf8"
)

func main() {
    var a, b, pos int
    var err error
    var s string
    //input := bufio.NewScanner(os.Stdin)
    //input.Split(bufio.ScanWords)

    for {
        if err == io.EOF {
            break
        }
        _, err = fmt.Scan(&s)
        fmt.Println(s)
        if s[0] == '+' {
            a++
        } else if s[0] == '-' {
            a--
        } else {
            for i,v:= range s {
            	if v == ':' {
                    pos = i
                }
            }
            b += a*(int(len(s)) - pos - 1)
        }
    }
    fmt.Println(b)
}

package main

/*

A. Исходящий трафик чата
ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Последнее время Поликарп много трудится над новым проектом "Поличат". Следуя современным тенденциям IT индустрии, Поликарп решил, что в этом проекте непременно должен быть чат. Проведя пару часов за компьютером, Поликарп написал чат-сервер, который может выполнять три типа команд:

Добавить человека в чат (команда 'Добавить').
Удалить человека из чата (команда 'Удалить').
Отправить сообщение от кого-либо всем участникам чата, включая отправителя сообщения (команда 'Отправить').
Сейчас Поликарп хочет узнать, какое количество исходящего трафика пошлет его сервер при обработке набора команд.

Поликарп выяснил, что при обработке команды 'Добавить' или 'Удалить' сервер не посылает трафика вовсе, а при обработке команды 'Отправить' каждому из участников чата посылается l байт, где l — длина рассылаемого сообщения.

Так как у Поликарпа совсем нет свободного времени, он просит вас помочь с решением этой задачи.

Входные данные
	Входной файл будет содержать не более 100 команд. Каждая команда будет располагаться на своей строке и иметь длину не более 100 символов. Форматы команд будут следующими:

	+<имя> для команды 'Добавить'.
	-<имя> для команды 'Удалить'.
	<имя_отправителя>:<текст_сообщения> для команды 'Отправить'.
	<имя> и <имя_отправителя> — непустая последовательность латинских букв или цифр. <текст_сообщения> может содержать латинские буквы, цифры и пробелы, но не может начинаться или оканчиваться пробелом. <текст_сообщения> может быть пустой строкой.

Гарантируется, что входные данные корректны, то есть человек не будет добавлен в чат, если он там уже присутствует, не будет команды 'Удалить', если человека с таким именем нет в чате и тому подобное.

Имена, различающиеся исключительно регистром букв следует считать различными.

*/

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

type Command interface {
	cmd()
}

type Add string
type Remove string
type Message struct {
	from, text string
}

func (_ Add) cmd() {}
func (_ Remove) cmd() {}
func (_ Message) cmd() {}

func solve(cmds []Command) int {
	invited := map[string]bool{}

	bytes := 0
	for _, cmd := range cmds {
		switch val := cmd.(type) {
		case Add:
			invited[string(val)] = true
		case Remove:
			delete(invited, string(val))
		case Message:
			msg := Message(val)
			if invited[msg.from] {
				bytes += len(msg.text)*len(invited)
			}
		}
	}
	return bytes
}

func main() {
	cmds := []Command{}

	reader := bufio.NewReader(os.Stdin)
	for {
		s, err := reader.ReadString('\n')
		if len(s) == 0 || err != nil {
			break
		}
		s = s[:len(s)-1]

		switch s[0] {
		case '+':
			cmds = append(cmds, Add(s[1:]))
		case '-':
			cmds = append(cmds, Remove(s[1:]))
		default:
			i := strings.IndexByte(s, ':')
			cmds = append(cmds, Message{from: s[:i], text: s[i+1:]})
		}
	}
	fmt.Printf("%d\n", solve(cmds))
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int

	for i := 0; i < 7; i++ {
		// var ln string
		// fmt.Scanln(&ln)
		// scan := bufio.NewScanner(os.Stdin)
		// scan.Scan()
		// ln = scan.Text()
		reader := bufio.NewReader(os.Stdin)
		ln, _ := reader.ReadString('\n')
		ln = strings.TrimSpace(ln)
		// ln = strings.Replace(ln, "\n\r", "", -1)
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}

	}

	fmt.Println(traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int

	for {
		// var ln string
		// fmt.Scanln(&ln)
		// scan := bufio.NewScanner(os.Stdin)
		// scan.Scan()
		// ln = scan.Text()
		reader := bufio.NewReader(os.Stdin)
		bline, _, err := reader.ReadLine()
		if err != nil {
			break
		}
		ln := strings.TrimSpace(string(bline))
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}

	}

	// fmt.Println(traffic)
	fmt.Printf("%d\n", traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int

	for i := 0; i < 7; i++ {
		var ln string
		// fmt.Scanln(&ln)
		scan := bufio.NewScanner(os.Stdin)
		scan.Scan()
		ln = scan.Text()
		// reader := bufio.NewReader(os.Stdin)
		// ln, _ := reader.ReadString('\n')
		// ln = strings.Replace(ln, "\n\r", "", -1)
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}

	}

	fmt.Println(traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int

	for i := 0; i < 7; i++ {
		reader := bufio.NewReader(os.Stdin)
		ln, _ := reader.ReadString('\n')
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}

	}

	fmt.Println(traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int

	for i := 0; i < 7; i++ {
		reader := bufio.NewReader(os.Stdin)
		ln, _ := reader.ReadString('\n')
		ln = strings.Replace(ln, "\n", "", -1)
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}

	}

	fmt.Println(traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int

	for i := 0; i < 7; i++ {
		// var ln string
		// fmt.Scanln(&ln)
		reader := bufio.NewReader(os.Stdin)
		ln, _ := reader.ReadString('\n')
		ln = strings.Replace(ln, "\n\r", "", -1)
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}

	}

	fmt.Println(traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {

	personList := make([]string, 0)
	var traffic int

	for i := 0; i < 7; i++ {
		var ln string

		scanner := bufio.NewScanner(os.Stdin)
		for scanner.Scan() {
			ln = scanner.Text() // Println will add back the final '\n'
			break
		}

		// fmt.Scanln(&ln)
		// reader := bufio.NewReader(os.Stdin)
		// ln, _ := reader.ReadString('\n')
		var message string

		if strings.HasPrefix(ln, "+") {
			person := string(ln[1:])
			personList = append(personList, person)
		} else if strings.HasPrefix(ln, "-") {
			person := string(ln[1:])
			personList = removeItem(personList, person)
		} else {
			index := strings.Index(ln, ":")
			message = strings.TrimSpace(string(ln[index+1:]))
			traffic += len(message) * len(personList)
		}

	}

	fmt.Println(traffic)
}

func removeItem(arr []string, person string) []string {
	for i, p := range arr {
		if p == person {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}

	return arr
}

package main

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

func main() {
    var a, b, pos int
    var err error
    var s string
    //input := bufio.NewScanner(os.Stdin)
    //input.Split(bufio.ScanWords)

    for {
        if err == io.EOF {
            break
        }
        _, err = fmt.Scan(&s)
        //s = input.Text()
        if s[0] == '+' {
            a++
        } else if s[0] == '-' {
            a--
        } else {
            for i := 0; i < len(s); i++ {
                if s[i] == ':' {
                    pos = i
                }
            }
            b += a*int(len(s)) - pos - 1
        }
    }
    fmt.Println(b)
}

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    //"strconv"
    //"sort"
    //"unicode/utf8"
)

func main() {
    var a, b, pos int
    var err error
    var s string
    input := bufio.NewScanner(os.Stdin)
    //input.Split(bufio.ScanWords)

    for input.Scan() {
        if err == io.EOF {
            break
        }
        //input.Scan()
        s = input.Text()
        fmt.Println(s)
        if s[0] == '+' {
            a++
        } else if s[0] == '-' {
            a--
        } else {
            for i, v := range s {
                if v == ':' {
                    pos = i
                }
            }
            b += a * (int(len(s)) - pos - 1)
        }
    }
    fmt.Println(b)
}


Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:   The product of all numbers in the first set is less than zero ( < 0).  The product of all numbers in the second set is greater than zero ( > 0).  The product of all numbers in the third set is equal to zero.  Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.

The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≤ 103) — the array elements.

In the first line print integer n1 (n1 > 0) — the number of elements in the first set. Then print n1 numbers — the elements that got to the first set. In the next line print integer n2 (n2 > 0) — the number of elements in the second set. Then print n2 numbers — the elements that got to the second set. In the next line print integer n3 (n3 > 0) — the number of elements in the third set. Then print n3 numbers — the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.

// 300A-mic
package main

import (
    "fmt"
    "sort"
)

func main() {
    var n int
    fmt.Scan(&n)
    a := make([]int, n)
    for i := range a {
        fmt.Scan(&a[i])
    }
    sort.Sort(sort.IntSlice(a))
    fmt.Print("1")
    fmt.Print(" ")
    fmt.Print(a[0])
    fmt.Println()
    if a[1] == 0 {
        fmt.Print(n - 2)
        fmt.Print(" ")
        for i := 2; i < n; i++ {
            fmt.Print(a[i])
            fmt.Print(" ")
        }
        fmt.Println()
        fmt.Print("1")
        fmt.Print(" ")
        fmt.Print("0")
        fmt.Println()
    } else if a[1] < 0 && a[2] < 0 {
        fmt.Print("2")
        fmt.Print(" ")
        fmt.Print(a[1])
        fmt.Print(" ")
        fmt.Print(a[2])
        fmt.Println()
        fmt.Print(n - 3)
        fmt.Print(" ")
        for i := 3; i < n; i++ {
            fmt.Print(a[i])
            fmt.Print(" ")
        }
        fmt.Println()
    } else {
        fmt.Print("1")
        fmt.Print(" ")
        fmt.Println(a[n-1])
        fmt.Print(n - 2)
        fmt.Print(" ")
        for i := 1; i < n-1; i++ {
            fmt.Print(a[i])
            fmt.Print(" ")
        }
        fmt.Println()
    }
}

package main

import (
    "fmt"
    "sort"
)

func main() {
    var n int
    fmt.Scan(&n)
    a := make([]int,n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    sort.Ints(a)
    fmt.Println(1,a[0])
    a = a[1:]
    if a[len(a)-1] == 0 {
        fmt.Println(2,a[0],a[1])
        a = a[2:]
    } else {
        fmt.Println(1,a[len(a)-1])
        a = a[:len(a)-1]
    }
    fmt.Print(len(a))
    for i := 0; i < len(a); i++ {
        fmt.Print(" ",a[i])
    }
    fmt.Println()
}

package main

import (
	"sort"
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int,n)
	for i:=0; i<n;i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)
	fmt.Println("1 ",a[0])
	if a[n-1]>0 {
	        fmt.Printf("1 %d\n",a[n-1])
		fmt.Printf("%d",n-2)
		for i:=1;i<n-1;i++ {
			fmt.Printf(" %d",a[i])
		}
	} else {
		fmt.Printf("2 %d %d\n",a[1],a[2])
		fmt.Printf("%d",n-3)
		for i:=3;i<n;i++ {
			fmt.Printf(" %d",a[i])
		}
	}
	fmt.Println()
}

package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func display(numbers []int) {
  n := len(numbers)
  writer.WriteString(fmt.Sprintf("%d %d", n, numbers[0]))
  for i := 1; i < n; i++ {
    writer.WriteString(fmt.Sprintf(" %d", numbers[i]))
  }
  writer.WriteString("\n")
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  negative := []int{}
  positive := []int{}
  zero := []int{}
  n := getI()
  for i := 0; i < n; i++ {
    x := getI()
    if x > 0 {
      positive = append(positive, x)
    } else if x < 0 {
      negative = append(negative, x)
    } else {
      zero = append(zero, x)
    }
  }
  if len(positive) == 0 {
    positive = append(positive, negative[0])
    positive = append(positive, negative[1])
    negative = negative[2:]
  }
  if len(negative)%2 == 0 {
    zero = append(zero, negative[0])
    negative = negative[1:]
  }
  display(negative)
  display(positive)
  display(zero)
}

package main

import (
	"fmt"
)

func Ir(x []int32) {
	fmt.Print(len(x))
	for i := int32(0); i < int32(len(x)); i++ {
		fmt.Print(" ", x[i])
	}
	fmt.Println()

}

func main() {

	var (
		i, xi, n       int32
		poz, neg, zero []int32
	)

	fmt.Scan(&n)
	poz = make([]int32, 0, n)
	neg = make([]int32, 0, n)
	zero = make([]int32, 0, n)

	for i = 0; i < n; i++ {
		fmt.Scan(&xi)
		if xi < 0 {
			neg = append(neg, xi)
			continue
		}
		if xi > 0 {
			poz = append(poz, xi)
			continue
		}
		zero = append(zero, 0)
	}

	if len(neg)%2 == 0 {
		zero = append(zero, neg[0])
		neg = neg[1:]
	}

	if len(poz) == 0 {
		poz = append(poz, neg[0:2]...)
		neg = neg[2:]
	}

	Ir(neg)
	Ir(poz)
	Ir(zero)

}

package main

import (
    "fmt"
    "sort"
)

func Select(xs []int) (ns, ps, zs []int) {
    n := len(xs)
    ns = xs[:1]
    if xs[n-1] > 0 {
        ps = xs[n-1:n]
        zs = xs[1:n-1]
    } else {
        ps = xs[1:3]
        zs = xs[3:n]
    }
    return
}

func PrintSet(xs []int) {
    fmt.Printf("%d ", len(xs))
    for _, x := range xs {
        fmt.Printf("%d ", x)
    }
    fmt.Println()
}

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

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

    sort.Ints(xs)
    ns, ps, zs := Select(xs)
    PrintSet(ns)
    PrintSet(ps)
    PrintSet(zs)
}

package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	pos_count := 0
	neg_count := 0
	zero_count := 0

	array := make([]int, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < n && scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		if a < 0 {
			array[neg_count] = a
			neg_count++
		} else if a > 0 {
			array[n-pos_count-1] = a
			pos_count++
		} else {
			zero_count++
		}
	}

	if pos_count > 0 {
		if neg_count%2 != 0 {
			fmt.Printf("%d ", neg_count)
			for i := 0; i < neg_count; i++ {
				fmt.Printf("%d ", array[i])
			}
			fmt.Println()
		} else {
			fmt.Printf("%d ", neg_count-1)
			for i := 0; i < neg_count-1; i++ {
				fmt.Printf("%d ", array[i])
			}
			fmt.Println()
		}
		fmt.Printf("%d ", pos_count)
		for i := 0; i < pos_count; i++ {
			fmt.Printf("%d ", array[n-i-1])
		}
		fmt.Println()
		if neg_count%2 != 0 {
			fmt.Printf("%d ", zero_count)
			for i := 0; i < zero_count; i++ {
				fmt.Printf("0 ")
			}
			fmt.Println()
		} else {
			fmt.Printf("%d ", zero_count+1)
			for i := 0; i < zero_count; i++ {
				fmt.Printf("0 ")
			}
			fmt.Println(array[neg_count-1])
		}
	} else {
		if neg_count%2 != 0 {
			fmt.Printf("%d ", neg_count-2)
			for i := 0; i < neg_count-2; i++ {
				fmt.Printf("%d ", array[i])
			}
			fmt.Println()
		} else {
			fmt.Printf("%d ", neg_count-3)
			for i := 0; i < neg_count-3; i++ {
				fmt.Printf("%d ", array[i])
			}
			fmt.Println()
		}
		fmt.Printf("2 ")
		for i := 0; i < 2; i++ {
			fmt.Printf("%d ", array[neg_count+i-2])
		}
		fmt.Println()
		if neg_count%2 != 0 {
			fmt.Printf("%d ", zero_count)
			for i := 0; i < zero_count; i++ {
				fmt.Printf("0 ")
			}
			fmt.Println()
		} else {
			fmt.Printf("%d ", zero_count+1)
			for i := 0; i < zero_count; i++ {
				fmt.Printf("0 ")
			}
			fmt.Println(array[neg_count-3])
		}
	}
}

// 300A-mic
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int				// membuat variabel n dengan jenis int
	fmt.Scan(&n)			// mengambil input
	a := make([]int, n)		//membuat variabel a dengan jenis int yang diisi dengan array n
	for i := range a {		// looping
		fmt.Scan(&a[i])     // mengambil input kedua
	}
	sort.Sort(sort.IntSlice(a)) // untuk sort
	fmt.Print("1")			// cetak 1
	fmt.Print(" ")			// cetak spasi
	fmt.Print(a[0])			// cetak hasil array a elemen ke 0
	fmt.Println()			//cetak enter
	if a[1] == 0 {			// jika array a elemen 1 sama dengan 0
		fmt.Print(n - 2)	// cetak hasil n dikurang 2
		fmt.Print(" ")		// cetak spasi
		for i := 2; i < n; i++ {	//looping kedua
			fmt.Print(a[i])			// cetak array a elemen i
			fmt.Print(" ")			// cetak spasi
		}
		fmt.Println()				//cetak enter
		fmt.Print("1")				//cetak 1
		fmt.Print(" ")				// cetak spasi
		fmt.Print("0")				// cetak 0
		fmt.Println()				// cetak enter
	} else if a[1] < 0 && a[2] < 0 {	// jika array a elemen 1 kurang dari 0 dan array a elemen kedua kurang dari 0
		fmt.Print("2")				// cetak 2
		fmt.Print(" ")				// cetak spasi
		fmt.Print(a[1])				// cetak array a elemen pertama
		fmt.Print(" ")				// cetak spasi
		fmt.Print(a[2])				// cetak array a elemen kedua
		fmt.Println()				// cetak enter
		fmt.Print(n - 3)			// cetak hasil dari n-3
		fmt.Print(" ")				// cetak spasi
		for i := 3; i < n; i++ {	// looping ke 3
			fmt.Print(a[i])			// cetak array a elemen ke i
			fmt.Print(" ")			// cetak spasi
		}
		fmt.Println()				// cetak enter
	} else {						// lainnya
		fmt.Print("1")				// cetak 1
		fmt.Print(" ")				// cetak spasi
		fmt.Println(a[n-1])			// cetak array a elemen ke n-1
		fmt.Print(n - 2)			// cetak hasil n-2
		fmt.Print(" ")				// cetak spasi
		for i := 1; i < n-1; i++ {	// looping ketiga
			fmt.Print(a[i])			// cetak array a elemen ke i
			fmt.Print(" ")			//cetak spasi
		}
		fmt.Println()				// cetak enter
	}
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)

	lo := 0
	hi := len(a)

	// Negative product.
	fmt.Printf("1 %d\n", a[0])
	lo = 1

	// Positive product.
	back := a[len(a) - 1]
	if back > 0 {
		fmt.Printf("1 %d\n", back)
		hi = len(a) - 1
	} else {
		fmt.Printf("2 %d %d\n", a[1], a[2])
		lo = 3
	}

	// Zero product.
	fmt.Printf("%d", hi - lo);
	for i := lo; i < hi; i++ {
		fmt.Printf(" %d", a[i])
	}
	fmt.Println();
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var n1, n2, n3 []int
	for i := 0; i < n; i++ {
		var i int
		fmt.Scan(&i)
		if i < 0 {
			n1 = append(n1, i)
		} else if i == 0 {
			n3 = append(n3, i)
		} else {
			n2 = append(n2, i)
		}
	}
	if len(n2) == 0 {
		n2 = append(n2, n1[:2]...)
		n1 = n1[2:]
	}
	if len(n1)%2 == 0 {
		n3 = append(n3, n1[0])
		n1 = n1[1:]
	}
	printArray(n1)
	printArray(n2)
	printArray(n3)
}

func printArray(n []int) {
	fmt.Print(len(n), " ")
	for _, i := range n {
		fmt.Print(i, " ")
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&arr[i])
	}
	sort.Ints(arr)
	var index int
	for index = range arr {
		if arr[index] == 0 {
			break
		}
	}
	fmt.Printf("1 %d\n", arr[0])
	if index == n-1 {
		fmt.Printf("2 %d %d\n", arr[1], arr[2])
		fmt.Printf("%d ", n-3)
		for i := 3; i < n; i++ {
			fmt.Printf("%d ", arr[i])
		}

	} else if index < n-1 {
		fmt.Printf("1 %d\n", arr[n-1])
		fmt.Printf("%d ", n-2)
		for i := 1; i < n-1; i++ {
			fmt.Printf("%d ", arr[i])
		}
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(reader, &n)

	var ng, ps, zr []int
	for i := 0; i < n; i++ {
		var x int
		fmt.Fscan(reader, &x)

		if x == 0 {
			zr = append(zr, 0)
		} else if x > 0 {
			ps = append(ps, x)
		} else if x < 0 {
			ng = append(ng, x)
		}
	}
	if len(ps) == 0 && len(ng) > 2 {
		ps = append(ps, ng[:2]...)
		ng = append(ng[:0], ng[2:]...)
	}

	if len(ng)%2 == 0 {
		zr = append(zr, ng[:1]...)
		ng = append(ng[:0], ng[1:]...)
	}

	fmt.Print(len(ng), " ")
	for _, vl := range ng {
		fmt.Print(vl, " ")
	}
	fmt.Println()
	fmt.Print(len(ps), " ")
	for _, vl := range ps {
		fmt.Print(vl, " ")
	}
	fmt.Println()

	fmt.Print(len(zr), " ")
	for _, vl := range zr {
		fmt.Print(vl, " ")
	}
}

package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func display(numbers map[int]bool) {
  listed := []int{}
  for number := range numbers {
    listed = append(listed, number)
  }
  n := len(listed)
  writer.WriteString(fmt.Sprintf("%d %d", n, listed[0]))
  for i := 1; i < n; i++ {
    writer.WriteString(fmt.Sprintf(" %d", listed[i]))
  }
  writer.WriteString("\n")
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  negative := map[int]bool{}
  positive := map[int]bool{}
  zero := map[int]bool{}
  n := getI()
  for i := 0; i < n; i++ {
    x := getI()
    if x > 0 {
      positive[x] = true
    } else if x < 0 {
      if len(negative) == 0 {
        negative[x] = true
      } else {
        positive[x] = true
      }
    } else {
      zero[x] = true
    }
  }
  display(negative)
  display(positive)
  display(zero)
}

package main

import (
	"fmt"
	"sort"
)

func Select(xs []int) (ns, ps, zs []int) {
	n := len(xs)
	ns = xs[:1]
	if xs[n-1] > 0 {
		ps = xs[n-1:n]
		zs = xs[1:n-1]
	} else {
		ps = xs[1:3]
		zs = xs[3:n]
	}
	return
}

func PrintSet(xs []int) {
	fmt.Printf("%d ", len(xs))
	for _, x := range xs {
		fmt.Printf("%d ", x)
	}
	fmt.Println()
}

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

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

	sort.Ints(xs)
	ns, ps, zs := Select(xs)
	PrintSet(ns)
	PrintSet(ps)
	PrintSet(zs)
}

package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	pos_count := 0
	neg_count := 0
	zero_count := 0

	array := make([]int, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < n && scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		if a < 0 {
			array[neg_count] = a
			neg_count++
		} else if a > 0 {
			array[n-pos_count-1] = a
			pos_count++
		} else {
			zero_count++
		}
	}

	fmt.Println("1", array[0])
	fmt.Printf("%d ", pos_count+neg_count-1)
	for i := 1; i < neg_count; i++ {
		fmt.Printf("%d ", array[i])
	}
	for i := 0; i < pos_count; i++ {
		fmt.Printf("%d ", array[n-i-1])
	}
	fmt.Println()
	fmt.Printf("%d ", zero_count)
	for i := 0; i < zero_count; i++ {
		fmt.Printf("0")
	}
	fmt.Println()
}

package main

import (
    "fmt"
    "sort"
)

func main() {
    var n int
    fmt.Scan(&n)
    a := make([]int,n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    sort.Ints(a)
    fmt.Println(1,a[0])
    a = a[1:]
    if a[len(a)-1] == 0 {
        fmt.Println(1,a[0],a[1])
        a = a[2:]
    } else {
        fmt.Println(1,a[len(a)-1])
        a = a[:len(a)-1]
    }
    fmt.Print(len(a))
    for i := 0; i < len(a); i++ {
        fmt.Print(" ",a[i])
    }
    fmt.Println()
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&arr[i])
	}
	sort.Ints(arr)
	var index int
	for index = range arr {
		if arr[index] == 0 {
			break
		}
	}
	fmt.Printf("1: %d\n", arr[0])
	if index == n-1 {
		fmt.Printf("2: %d %d\n", arr[1], arr[2])
		fmt.Printf("%d:", n-3)
		for i := 3; i < n; i++ {
			fmt.Printf("%d", arr[i])
		}

	} else if index < n-1 {
		fmt.Printf("1: %d\n", arr[n-1])
		fmt.Printf("%d:", n-2)
		for i := 1; i < n-1; i++ {
			fmt.Printf("%d", arr[i])
		}
	}
}


Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:  Walk up or down one unit on a tree.  Eat a nut on the top of the current tree.  Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > hi + 1. Compute the minimal time (in seconds) required to eat all nuts.

The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.

Print a single integer — the minimal time required to eat all nuts in seconds.

package main

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

func main() {
	var i,n,h,o,t,d int64
	o=-1
	t=0
	input := bufio.NewScanner(os.Stdin)
    	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	for i=0;i<n;i++ {
		input.Scan()
		aa, _ := strconv.Atoi(input.Text())
		h=int64(aa)
		if t-h<0 {
			d=(t-h)*(-1)
		} else {
			d=t-h
		}
		o+=(d+2)
		t=h
	}
	fmt.Println(o)

}

package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  pos := getI()
  result := n+pos
  for i := 1; i < n; i++ {
    tree := getI()
    if tree < pos {
      result += pos-tree
      pos = tree
    }
    result++
    if tree > pos {
      result += tree-pos
      pos = tree
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    var n int
    fmt.Scan(&n)
    ans, prev := 0, 1
    for i := 0; i < n; i++ {
        scanner.Scan()
        a, _ := strconv.Atoi(scanner.Text())
        ans += abs(prev-a)+2
        prev = a
    }
    fmt.Println(ans)
}

package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	h := make([]int, n)

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < n && scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		h[i] = a
	}

	time := h[0] + 1
	height := h[0]
	for i := 1; i < n; i++ {
		if height < h[i] {
			time += 1               // Jump
			time += (h[i] - height) // Climb Up
			height = h[i]           // At the Top
			time += 1               // Eat
		} else if height >= h[i] {
			time += (height - h[i]) // Climb Down
			height = h[i]           // At the Top
			time += 2               // Jump, Eat
		}
	}

	fmt.Println(time)
}

package main

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

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

	hn := make([]int, n, n)
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		hn[i], _ = strconv.Atoi(bs.Text())
	}

	var ans uint64
	ans = uint64(hn[0]) + 1

	for i := 1; i < n; i++ {
		if hn[i] < hn[i-1] {
			ans += uint64(hn[i-1] - hn[i])
		}
		ans++

		if hn[i] > hn[i-1] {
			ans += uint64(hn[i] - hn[i-1])
		}
		ans++
	}

	fmt.Println(ans)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var tr int
	fmt.Fscan(reader, &tr)

	trs := make([]int, tr)
	for i := 0; i < tr; i++ {
		fmt.Fscan(reader, &trs[i])
	}

	count := trs[0] + 1
	for i := 1; i < tr; i++ {
		count++
		if trs[i] < trs[i-1] {
			count += trs[i-1] - trs[i] + 1
		} else {
			count += trs[i] - trs[i-1] + 1
		}
	}

	fmt.Println(count)
}

package main

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

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

	hn := make([]int, n, n)
	bs := bufio.NewScanner(os.Stdin)
	for i := 0; i < n; i++ {
		bs.Scan()
		hn[i], _ = strconv.Atoi(bs.Text())
	}

	var ans uint64
	ans = 0

	pre := 0
	for i := 0; i < n; i++ {
		ans += uint64(hn[i] - pre) // up
		ans += 1                   // eat
		pre = hn[i]
		if i != n-1 && hn[i] > hn[i+1] {
			ans += uint64(hn[i] - hn[i+1]) // down
			pre = hn[i+1]
		}

		if i != n-1 {
			ans += 1 // jump
		}
	}

	fmt.Println(ans)
}

package main

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

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

	hn := make([]int, n, n)
	bs := bufio.NewScanner(os.Stdin)
	for i := 0; i < n; i++ {
		bs.Scan()
		hn[i], _ = strconv.Atoi(bs.Text())
	}

	var ans uint64
	ans = uint64(hn[0]) + 1

	for i := 1; i < n; i++ {
		if hn[i] < hn[i-1] {
			ans += uint64(hn[i-1] - hn[i])
		}
		ans++

		if hn[i] > hn[i-1] {
			ans += uint64(hn[i] - hn[i-1])
		}
		ans++
	}

	fmt.Println(ans)
}


There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.

The first line contains three integers n, k and p (1 ≤ n ≤ 1 000, n ≤ k ≤ 2 000, 1 ≤ p ≤ 109) — the number of people, the number of keys and the office location. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — positions in which people are located initially. The positions are given in arbitrary order. The third line contains k distinct integers b1, b2, ..., bk (1 ≤ bj ≤ 109) — positions of the keys. The positions are given in arbitrary order. Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point.

Print the minimum time (in seconds) needed for all n to reach the office with keys.

NoteIn the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.

package main

import (
	"fmt"
	"sort"
)

var n, k, p int

func main() {
	var ans int64 = 1e18
	fmt.Scan(&n, &k, &p)
	a := make([]int, n)
	b := make([]int, k)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	for i := 0; i < k; i++ {
		fmt.Scan(&b[i])
	}
	sort.Ints(a)
	sort.Ints(b)
	for i := 0; i+n <= k; i++ {
		var tmp int64 = 0
		for j := 0; j < n; j++ {
			tmp1 := func(x, y, z int) (res int64) {
				if x >= y {
					res += int64(x - y)
				} else {
					res += int64(y - x)
				}
				if y >= z {
					res += int64(y - z)
				} else {
					res += int64(z - y)
				}
				return
			}(a[j], b[i+j], p)
			tmp = func(x, y int64) int64 {
				if x >= y {
					return x
				} else {
					return y
				}
			}(tmp, tmp1)
		}
		ans = func(x, y int64) int64 {
			if x <= y {
				return x
			} else {
				return y
			}
		}(tmp, ans)
	}
	fmt.Println(ans)
}

package main

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

func solve() {
	n := readInt()
	k := readInt()
	p := readInt()
	a := readIntArray(n)
	b := readIntArray(k)
	sort.Ints(a)
	sort.Ints(b)
	mini := math.MaxInt32
	for i := 0; i <= k-n; i++ {
		x := 0
		for j := 0; j < n; j++ {
			x = max(x, abs(a[j]-b[i+j])+abs(b[i+j]-p))
		}
		mini = min(mini, x)
	}
	fmt.Println(mini)
}

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

var scanner *bufio.Scanner

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

// IO

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

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

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

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

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

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

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

package main

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

func solve(val int64, A, B []int, G int) bool {
	visited := map[int]bool{}
	for _, pos := range A {
		suc := false
		for i, tar := range B {
			if _, ok := visited[i]; ok {
				continue
			}
			cost := 0
			if pos > tar {
				cost = pos - tar
			} else {
				cost = tar - pos
			}
			if tar > G {
				cost += tar - G
			} else {
				cost += G - tar
			}
			if val-int64(cost) >= 0 {
				suc = true
				visited[i] = true
				break
			}
		}
		if !suc {
			return false
		}
	}

	return true
}

func main() {
	fsc := NewFastScanner()
	N, K, G := fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
	A := make([]int, 0)
	for i := 0; i < N; i++ {
		A = append(A, fsc.NextInt())
	}
	B := make([]int, 0)
	for i := 0; i < K; i++ {
		B = append(B, fsc.NextInt())
	}
	sort.Ints(A)
	sort.Ints(B)
	var left, right int64
	left = -1
	right = 1152921504606846976
	for right-left > 1 {
		med := (right + left) / 2
		if solve(med, A, B, G) {
			right = med
		} else {
			left = med
		}
	}
	fmt.Println(right)
}

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

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

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

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

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

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

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

package main

import (
	. "fmt"
	"sort"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	type pair struct{ l, r int }
	var n, m, o int
	Scan(&n, &m, &o)
	a := make([]int, n)
	for i := range a {
		Scan(&a[i])
	}
	sort.Ints(a)
	k := make([]int, m)
	for i := range k {
		Scan(&k[i])
	}
	ans := sort.Search(2e9, func(t int) bool {
		ps := []pair{}
		for _, p := range k {
			q := p - o
			if q < 0 {
				q = -q
			}
			if d := t - q; d >= 0 {
				ps = append(ps, pair{p - d, p + d})
			}
		}
		sort.Slice(ps, func(i, j int) bool { a, b := ps[i], ps[j]; return a.r < b.r || a.r == b.r && a.l < b.l })
		i := -1
		for _, p := range a {
			for i++; i < len(ps) && ps[i].r < p; i++ {
			}
			if i == len(ps) || p < ps[i].l {
				return false
			}
		}
		return true
	})
	Print(ans)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF830A(_r io.Reader, out io.Writer) {
	abs := func(x int) int {
		if x < 0 {
			return -x
		}
		return x
	}
	type pair struct{ l, r int }
	in := bufio.NewReader(_r)
	var n, m, o int
	Fscan(in, &n, &m, &o)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	sort.Ints(a)
	k := make([]int, m)
	for i := range k {
		Fscan(in, &k[i])
	}
	sort.Ints(k)
	ans := sort.Search(2e9, func(t int) bool {
		ps := []pair{}
		for _, p := range k {
			if d := t - abs(p-o); d >= 0 {
				ps = append(ps, pair{p - d, p + d})
			}
		}
		sort.Slice(ps, func(i, j int) bool { a, b := ps[i], ps[j]; return a.r < b.r || a.r == b.r && a.l < b.l })
		i := -1
		for _, p := range a {
			for i++; i < len(ps) && ps[i].r < p; i++ {
			}
			if i == len(ps) || p < ps[i].l {
				return false
			}
		}
		return true
	})
	Fprint(out, ans)
}

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

package main

import (
	"fmt"
	"sort"
)

var n, k, p int

func main() {
	var ans int64 = 1e18
	fmt.Scan(&n, &k, &p)
	a := make([]int, n)
	b := make([]int, k)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	for i := 0; i < k; i++ {
		fmt.Scan(&b[i])
	}
	sort.Ints(b)
	for i := 0; i+n <= k; i++ {
		var tmp int64 = 0
		for j := 0; j < n; j++ {
			tmp1 := func(x, y, z int) (res int64) {
				if x >= y {
					res += int64(x - y)
				} else {
					res += int64(y - x)
				}
				if y >= z {
					res += int64(y - z)
				} else {
					res += int64(z - y)
				}
				return
			}(a[j], b[i+j], p)
			tmp = func(x, y int64) int64 {
				if x >= y {
					return x
				} else {
					return y
				}
			}(tmp, tmp1)
		}
		ans = func(x, y int64) int64 {
			if x <= y {
				return x
			} else {
				return y
			}
		}(tmp, ans)
	}
	fmt.Println(ans)
}

package main

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

func solve() {
	n := readInt()
	k := readInt()
	p := readInt()
	a := readIntArray(n)
	b := readIntArray(k)
	maxHeaps := make([]*MinHeap, n)
	for i := 0; i < n; i++ {
		cur := a[i]
		maxHeaps[i] = NewMinHeap(k)
		for j := 0; j < k; j++ {
			pos := b[j]
			dist := abs(cur-pos) + abs(pos-p)
			maxHeaps[i].Add(j, dist)
		}
	}
	best := 0
	for {
		maxValue := 0
		maxIndex := -1
		maxKeyIndex := 0
		for i := 0; i < n; i++ {
			if maxHeaps[i] == nil {
				continue
			}
			v := maxHeaps[i].Min()
			if v > maxValue {
				maxValue = v
				maxIndex = i
				maxKeyIndex = maxHeaps[i].ArgMin()
			}
		}
		if maxIndex == -1 {
			fmt.Println(best)
			return
		}

		best = max(best, maxValue)
		maxHeaps[maxIndex] = nil
		for i := 0; i < n; i++ {
			if maxHeaps[i] != nil {
				maxHeaps[i].Remove(maxKeyIndex)
			}
		}
	}
}

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

type MinHeap struct {
	a    []int
	vmap []int
	imap []int
	n    int
	pos  int
}

const INF = math.MaxInt32

func NewMinHeap(m int) *MinHeap {
	heap := &MinHeap{}
	m += 2
	heap.n = m
	heap.a = make([]int, heap.n)
	heap.vmap = make([]int, heap.n)
	heap.imap = make([]int, heap.n)
	heap.pos = 1
	for i := 0; i < heap.n; i++ {
		heap.a[i] = INF
		heap.vmap[i] = -1
		heap.imap[i] = -1
	}
	return heap
}

func (h *MinHeap) Add(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	}
	if ret != -1 {
		return h.a[ret]
	}
	return x
}

func (h *MinHeap) Update(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	} else {
		h.a[ret] = x
		h.up(ret)
		h.down(ret)
	}
	return x
}

func (h *MinHeap) Remove(ind int) int {
	if h.pos == 1 {
		return INF
	}
	if h.imap[ind] == -1 {
		return INF
	}

	h.pos--
	rem := h.imap[ind]
	ret := h.a[rem]
	h.vmap[rem] = h.vmap[h.pos]
	h.imap[h.vmap[h.pos]] = rem
	h.imap[ind] = -1
	h.a[rem] = h.a[h.pos]
	h.a[h.pos] = INF
	h.vmap[h.pos] = -1

	h.up(rem)
	h.down(rem)
	return ret
}

func (h *MinHeap) Min() int {
	return h.a[1]
}

func (h *MinHeap) ArgMin() int {
	return h.vmap[1]
}

func (h *MinHeap) Size() int {
	return h.pos - 1
}

func (h *MinHeap) up(cur int) {
	for c, p := cur, cur>>1; p >= 1 && h.a[p] > h.a[c]; c, p = c>>1, p>>1 {
		h.a[p], h.a[c] = h.a[c], h.a[p]
		h.imap[h.vmap[p]], h.imap[h.vmap[c]] = h.imap[h.vmap[c]], h.imap[h.vmap[p]]
		h.vmap[p], h.vmap[c] = h.vmap[c], h.vmap[p]
	}
}

func (h *MinHeap) down(cur int) {
	for c := cur; 2*c < h.pos; {
		b := 0
		if h.a[2*c] < h.a[2*c+1] {
			b = 2 * c
		} else {
			b = 2*c + 1
		}
		if h.a[b] < h.a[c] {
			h.a[c], h.a[b] = h.a[b], h.a[c]
			h.imap[h.vmap[c]], h.imap[h.vmap[b]] = h.imap[h.vmap[b]], h.imap[h.vmap[c]]
			h.vmap[c], h.vmap[b] = h.vmap[b], h.vmap[c]
			c = b
		} else {
			break
		}
	}
}

var scanner *bufio.Scanner

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

// IO

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

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

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

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

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

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

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

package main

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

func solve(val int64, A, B []int, G int) bool {
	visited := map[int]bool{}
	for _, pos := range A {
		suc := false
		for i, tar := range B {
			if _, ok := visited[i]; ok {
				continue
			}
			cost := 0
			if pos > tar {
				cost = pos - tar
			} else {
				cost = tar - pos
			}
			if tar > G {
				cost += tar - G
			} else {
				cost += G - tar
			}
			if val-int64(cost) >= 0 {
				suc = true
				break
			}
		}
		if !suc {
			return false
		}
	}

	return true
}

func main() {
	fsc := NewFastScanner()
	N, K, G := fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
	A := make([]int, 0)
	for i := 0; i < N; i++ {
		A = append(A, fsc.NextInt())
	}
	B := make([]int, 0)
	for i := 0; i < K; i++ {
		B = append(B, fsc.NextInt())
	}
	sort.Ints(A)
	sort.Ints(B)
	var left, right int64
	left = 0
	right = 1152921504606846976
	for right-left > 1 {
		med := (right + left) / 2
		if solve(med, A, B, G) {
			right = med
		} else {
			left = med
		}
	}
	fmt.Println(right)
}

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

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

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

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

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

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

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

package main

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

func solve(val int64, A, B []int, G int) bool {
	visited := map[int]bool{}
	for _, pos := range A {
		suc := false
		for i, tar := range B {
			if _, ok := visited[i]; ok {
				continue
			}
			cost := 0
			if pos > tar {
				cost = pos - tar
			} else {
				cost = tar - pos
			}
			if tar > G {
				cost += tar - G
			} else {
				cost += G - tar
			}
			if val-int64(cost) >= 0 {
				suc = true
				visited[i] = true
				break
			}
		}
		if !suc {
			return false
		}
	}

	return true
}

func main() {
	fsc := NewFastScanner()
	N, K, G := fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
	A := make([]int, 0)
	for i := 0; i < N; i++ {
		A = append(A, fsc.NextInt())
	}
	B := make([]int, 0)
	for i := 0; i < K; i++ {
		B = append(B, fsc.NextInt())
	}
	sort.Ints(A)
	sort.Ints(B)
	var left, right int64
	left = 0
	right = 1152921504606846976
	for right-left > 1 {
		med := (right + left) / 2
		if solve(med, A, B, G) {
			right = med
		} else {
			left = med
		}
	}
	fmt.Println(right)
}

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

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

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

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

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

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF830A(_r io.Reader, out io.Writer) {
	abs := func(x int) int {
		if x < 0 {
			return -x
		}
		return x
	}
	type pair struct{ l, r int }
	in := bufio.NewReader(_r)
	var n, m, o int
	Fscan(in, &n, &m, &o)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	sort.Ints(a)
	k := make([]int, m)
	for i := range k {
		Fscan(in, &k[i])
	}
	sort.Ints(k)
	ans := sort.Search(2e9, func(t int) bool {
		ps := []pair{}
		for _, p := range k {
			if d := t - abs(p-o); d >= 0 {
				ps = append(ps, pair{p - d, p + d})
			}
		}
		sort.Slice(ps, func(i, j int) bool { a, b := ps[i], ps[j]; return a.r < b.r || a.r == b.r && a.l < b.l })
		i := 0
		for _, p := range a {
			for ; i < len(ps) && ps[i].r < p; i++ {
			}
			if i == len(ps) || p < ps[i].l {
				return false
			}
		}
		return true
	})
	Fprint(out, ans)
}

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


A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences $$$[3, 1, 4, 2]$$$, [$$$1$$$] and $$$[2,1]$$$ are permutations, but $$$[1,2,1]$$$, $$$[0,1]$$$ and $$$[1,3,4]$$$ are not.For a given number $$$n$$$ you need to make a permutation $$$p$$$ such that two requirements are satisfied at the same time:  For each element $$$p_i$$$, at least one of its neighbors has a value that differs from the value of $$$p_i$$$ by one. That is, for each element $$$p_i$$$ ($$$1 \le i \le n$$$), at least one of its neighboring elements (standing to the left or right of $$$p_i$$$) must be $$$p_i + 1$$$, or $$$p_i - 1$$$.  the permutation must have no fixed points. That is, for every $$$i$$$ ($$$1 \le i \le n$$$), $$$p_i \neq i$$$ must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let $$$n = 4$$$. Then [$$$4, 3, 1, 2$$$] is a funny permutation, since:   to the right of $$$p_1=4$$$ is $$$p_2=p_1-1=4-1=3$$$;  to the left of $$$p_2=3$$$ is $$$p_1=p_2+1=3+1=4$$$;  to the right of $$$p_3=1$$$ is $$$p_4=p_3+1=1+1=2$$$;  to the left of $$$p_4=2$$$ is $$$p_3=p_4-1=2-1=1$$$.  for all $$$i$$$ is $$$p_i \ne i$$$. For a given positive integer $$$n$$$, output any funny permutation of length $$$n$$$, or output -1 if funny permutation of length $$$n$$$ does not exist.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of the test cases follows. Each test case consists of f single line containing one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print on a separate line:    any funny permutation $$$p$$$ of length $$$n$$$;  or the number -1 if the permutation you are looking for does not exist.

NoteThe first test case is explained in the problem statement.In the second test case, it is not possible to make the required permutation: permutations $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[3, 2, 1]$$$ have fixed points, and in $$$[2, 3, 1]$$$ and $$$[3, 1, 2]$$$ the first condition is met not for all positions.

package main

import (
	"fmt"
)

func main() {
	var num int
	fmt.Scan(&num)
	for i := 0; i < num; i++ {

		var num1 int
		fmt.Scan(&num1)
		var arr []int
		arr = sec(num1)
		for i := 0; i < len(arr); i++ {
			fmt.Printf("%d ", arr[i])
		}
		fmt.Println()
	}

}
func sec(num int) []int {
	var arr []int
	if num == 3 {
		arr = append(arr, -1)
		return arr
	}
	if num == 2 {
		arr = append(arr, 2, 1)
		return arr
	}
	if num == 5 {
		arr = append(arr, 4, 5, 1, 2, 3)
		return arr
	}
	for i := num; i > 0; i-- {
		arr = append(arr, i)
	}
	if num > 5 && num%2 != 0 {
		mid := (num / 2)
		arr[mid] += 1
		arr[mid-1] -= 1
	}

	return arr
}

package main

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

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

func solve() string {
	var n int
	fmt.Fscan(in, &n)

	if n == 2 {
		return "2 1"
	}

	if n == 3 {
		return "-1"
	}

	var sb strings.Builder
	sb.WriteString(strconv.Itoa(n-1) + " " + strconv.Itoa(n))
	if n%2 == 0 {
		for i := n - 2; i > 0; i-- {
			sb.WriteString(" " + strconv.Itoa(i))
		}
	} else {
		for i := 1; i <= n-2; i++ {
			sb.WriteString(" " + strconv.Itoa(i))
		}
	}

	return sb.String()
}

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

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

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

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

func makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}

package main

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

func solve(_r io.Reader, _w io.Writer) {

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)

	defer out.Flush()

	var T int
	Fscan(in, &T)
	for ; T > 0; T-- {
		var n int
		Fscan(in, &n)
		if n == 3 {
			Fprintln(out, "-1")
			continue
		}
		if n%2 == 0 {
			for i := 1; i <= n; i += 2 {
				Fprint(out, i+1, " ", i, " ")
			}
			Fprintln(out)
			continue
		} else {
			for i := 4; i <= n; i += 2 {
				Fprint(out, i+1, " ", i, " ")
			}
			for i := 1; i <= 3; i++ {
				Fprint(out, i, " ")
			}

			Fprintln(out)
			continue
		}
	}

}

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

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

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

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

package main

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

const mod = 998244353
const mx = int64(1e9 + 7)

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	Fscan(in, &n)
	if n == 1 || n == 3 {
		Fprintln(out, "-1")
		return
	}
	if n == 5 {
		Fprintln(out, "3 4 5 1 2")
		return
	}
	for i := n; i >= 1; i-- {
		if n%2 == 1 && n/2 == i {
			Fprintf(out, "%d ", i+1)
			continue
		}
		if n%2 == 1 && (n+1)/2 == i {
			Fprintf(out, "%d ", i-1)
			continue
		}
		Fprintf(out, "%d ", i)
	}
	Fprintln(out)
}

func abs(a int64) int64 {
	if a > 0 {
		return a
	}
	return -a
}
func sum(a, b int64) int64 {
	return (b + a) * (b - a + 1) / 2
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

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

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

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

		if n != 3 {
			fmt.Fprintf(w, "%d %d ", n, n-1)
			for i := 1; i <= n-2; i++ {
				fmt.Fprintf(w, "%d ", i)
			}
			fmt.Fprintln(w, "")
		} else {
			fmt.Fprintln(w, -1)
		}

	}

}

package main

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

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

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

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

		l := n/2
		if n != 3 {
			for i := 0; i < n; i++ {
				if i < l {
					fmt.Fprintf(w, "%d ", n-l + i+1)
				} else {
					fmt.Fprintf(w, "%d ", i-l + 1)
				}
			}
			fmt.Fprintln(w, "")
		} else {
			fmt.Fprintln(w, -1)
		}

	}

}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		if n == 3 {
			fmt.Fprintln(out,-1)
			continue
		}
		for j:=n/2+1;j<=n;j++{
			fmt.Fprintf(out,"%v ",j)
		}
		for j:=1;j<=n/2;j++{
			fmt.Fprintf(out,"%v ",j)
		}
		fmt.Fprintln(out,)
	}
}

package main

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

type CF1741B struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1741B) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1741B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1741B) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1741B) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1741B) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1741B
Date: 10/28/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1741/B
Problem: CF1741B
**/
func (in *CF1741B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		if n == 3 {
			fmt.Println(-1)
		} else {
			for i := 3; i <= n; i++ {
				fmt.Print(i, " ")
			}
			fmt.Println(2, 1)
		}
	}
}

func NewCF1741B(r *bufio.Reader) *CF1741B {
	return &CF1741B{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1741B(bufio.NewReader(os.Stdin)).Run()
}

/*
	A template for Go on codeforces.com
	Author: Yakov, frvr.ru
*/

package main

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

func main() {
	t := readInt()
	for j := 0; j < t; j++ {
		n := readInt()
		if n == 3 {
			writeLine(-1)
		} else {
			Solve(n)
		}
	}
}
func Solve(n int) {
	for i := 3; i <= n; i++ {
		fmt.Printf("%v ", i)
	}
	fmt.Printf("2 1\n")
}

/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */

var in = bufio.NewReader(os.Stdin)

type float = float32
type double = float64
type long = int64
type ulong = uint64

func typeOf(arg interface{}) string {
	switch reflect.TypeOf(arg).Kind() {
	case reflect.Int:
		return "int"
	case reflect.Int8:
		return "int8"
	case reflect.Int16:
		return "int16"
	case reflect.Int32:
		return "int32"
	case reflect.Int64:
		return "int64"
	case reflect.Uint:
		return "uint"
	case reflect.Uint8:
		return "uint8"
	case reflect.Uint16:
		return "uint16"
	case reflect.Uint32:
		return "uint32"
	case reflect.Uint64:
		return "uint64"
	case reflect.Float32:
		return "float32"
	case reflect.Float64:
		return "float64"
	case reflect.Complex64:
		return "complex64"
	case reflect.Complex128:
		return "complex128"
	case reflect.Bool:
		return "bool"
	case reflect.String:
		return "string"
	case reflect.Chan:
		return "chan"
	case reflect.Ptr:
		return "ptr"
	case reflect.Uintptr:
		return "uintptr"
	case reflect.UnsafePointer:
		return "unsafeptr"
	case reflect.Interface:
		return "interface"
	case reflect.Array:
		return "array"
	case reflect.Slice:
		return "slice"
	case reflect.Map:
		return "map"
	case reflect.Struct:
		return "struct"
	case reflect.Func:
		return "func"
	case reflect.Invalid:
		return "invalid"
	default:
		return "nil"
	}
}

/* ~~~~~~~~~~ */

func _scln() string {
	ln, _ := in.ReadString('\n')
	return strings.Trim(ln, " \r\n")
}
func _sc(s []string) string {
	if len(s) == 0 {
		return _scln()
	}
	return s[0]
}

func readLine() string              { return _scln() }
func readString() string            { return _scln() }
func readStrings() []string         { return strings.Split(_scln(), " ") }
func readBool(s ...string) bool     { t, _ := strconv.ParseBool(_sc(s)); return t }
func readByte(s ...string) byte     { t, _ := strconv.ParseUint(_sc(s), 10, 8); return byte(t) }
func readDouble(s ...string) double { t, _ := strconv.ParseFloat(_sc(s), 64); return t }
func readFloat(s ...string) float   { t, _ := strconv.ParseFloat(_sc(s), 32); return float32(t) }
func readInt(s ...string) int       { t, _ := strconv.Atoi(_sc(s)); return t }
func readLong(s ...string) long     { t, _ := strconv.ParseInt(_sc(s), 10, 64); return t }
func readULong(s ...string) ulong   { t, _ := strconv.ParseUint(_sc(s), 10, 64); return t }

/* ~~~~~~~~~~ */

// Too much overhead with universal method using interface{}, wait for the generics,
// but for now — just don't look at the redundancy of the code after that commentary :)

func readBools() []bool {
	strs := readStrings()
	arr := make([]bool, len(strs))
	for i, s := range strs {
		arr[i] = readBool(s)
	}
	return arr
}
func readBytes() []byte {
	strs := readStrings()
	arr := make([]byte, len(strs))
	for i, s := range strs {
		arr[i] = readByte(s)
	}
	return arr
}
func readDoubles() []double {
	strs := readStrings()
	arr := make([]double, len(strs))
	for i, s := range strs {
		arr[i] = readDouble(s)
	}
	return arr
}
func readFloats() []float {
	strs := readStrings()
	arr := make([]float, len(strs))
	for i, s := range strs {
		arr[i] = readFloat(s)
	}
	return arr
}
func readInts() []int {
	strs := readStrings()
	arr := make([]int, len(strs))
	for i, s := range strs {
		arr[i] = readInt(s)
	}
	return arr
}
func readLongs() []long {
	strs := readStrings()
	arr := make([]long, len(strs))
	for i, s := range strs {
		arr[i] = readLong(s)
	}
	return arr
}
func readULongs() []ulong {
	strs := readStrings()
	arr := make([]ulong, len(strs))
	for i, s := range strs {
		arr[i] = readULong(s)
	}
	return arr
}

/* ~~~~~~~~~~ */

func write(arg ...interface{})                 { fmt.Print(arg...) }
func writeLine(arg ...interface{})             { fmt.Println(arg...) }
func writeFormat(f string, arg ...interface{}) { fmt.Printf(f, arg...) }

package main

import (
	"fmt"
)

var t, n int

func solve() {
	if n == 3 {
		fmt.Println("-1")
	} else {
		fmt.Print(n, n-1, " ")
		for i := 1; i < n-1; i++ {
			fmt.Print(i, " ")
		}
		fmt.Println()
	}
}

func main() {
	fmt.Scan(&t)
	for ; t != 0; t-- {
		fmt.Scan(&n)
		solve()
	}
}

package main

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

var in = bufio.NewReader(os.Stdin)

func  gcd(a, b int) int {
  for b != 0 {
      a, b = b, a%b
  }
  return a
}

func pl(a ...interface{}) { fmt.Println(a...) }
func pf(format string, a ...interface{}) { fmt.Printf(format, a...) }

func main() {
	var t int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
    var n int
    fmt.Fscan(in, &n)
    if n == 3 {
      pl("-1")
      continue
    }
    pf("%d %d ", n, n-1)
    for i := 1; i<=n-2;i++ {
      pf("%d ", i)
    }
    pl("")
	}
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func solve() {
	var n int
	scanf("%d\n", &n)

	if (n == 3) {
		printf("-1\n")
		return
	}

	if n%2 == 0 {
		for i:=n; i>=1; i-- {
			printf("%d ", i)
		}
		printf("\n")
		return
	}

	j := n
	for i:=0; i<n/2; i++ {
		printf("%d ", j)
		j--
	}
	j = 1
	for i:=0; i<n/2+1; i++ {
		printf("%d ", j)
		j++
	}
	printf("\n")
}

func main() {
	defer writer.Flush()

	var T int
	scanf("%d\n", &T)
	for tt:=1; tt<=T; tt++ {
		solve()
	}
}

package main

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

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func main() {
    in := bufio.NewReader(os.Stdin)
    n := readInt(in)
    for i:=0; i<n; i++ {
        v := readInt(in)
        if v == 3 {
            fmt.Println(-1)
        } else {
            fmt.Printf("%d %d", v, v-1)
            for j:=1; j<v-1; j++ {
                fmt.Printf(" %d", j)
            }
            fmt.Printf("\n")
        }
    }
}

package main

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

const cf = true

func solve() {
	var n int
	fmt.Fscan(in, &n)
	if n == 3 {
		fmt.Fprintln(out, -1)
		return
	}
	fmt.Fprint(out, n, " ", n-1, " ")
	for i := 1; i < n-1; i++ {
		fmt.Fprint(out, i, " ")
	}
	fmt.Fprintln(out)
}

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

type SqrtInt interface {
	SignedSqrt | UnsignedSqrt
}

type SignedSqrt interface {
	~int | ~int32 | ~int64
}

type UnsignedSqrt interface {
	~uint | ~uint32 | ~uint64 | ~uintptr
}

func sqrt[T SqrtInt](x T) T {
	l, r := T(0), T(2000000123)
	for l < r {
		mid := (l + r) / 2
		if mid*mid > x {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l - 1
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

type set[T Ordered] struct {
	itms map[T]struct{}
}

func (s *set[T]) init() {
	if s.itms == nil {
		s.itms = make(map[T]struct{})
	}
}

func (s *set[T]) add(item T) *set[T] {
	s.init()
	s.itms[item] = exists
	return s
}

func (s *set[T]) remove(item T) *set[T] {
	s.init()
	delete(s.itms, item)
	return s
}

func (s *set[T]) has(item T) bool {
	s.init()
	_, c := s.itms[item]
	return c
}

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

func (s *set[T]) items() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	return items
}

func (s *set[T]) size() int {
	s.init()
	return len(s.itms)
}

var exists = struct{}{}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

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

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

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

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	scanner := bufio.NewScanner(os.Stdin)
	// mod := int64(998244353998244353)
	for i := 0; i < t; i++ {
		var s string
		var n int
		if scanner.Scan() {
			s = scanner.Text()
			n, _ = strconv.Atoi(s)
		}

		if n == 3 {
			fmt.Println(-1)
		} else {
			var arr []int = make([]int, n)
			for i := 0; i < n; i++ {
				arr[i] = i + 1
			}
			left := arr[n/2:]
			right := arr[:n/2]
			arr = append(left, right...)

			for j := 0; j < n-1; j++ {
				fmt.Printf("%d ", arr[j])
			}
			fmt.Println(arr[n-1])
		}

	}
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

const INF = 1e18
const N = 2e5 + 5

func main() {
	sc.Buffer(make([]byte, 500000*1+1), 500000)
	sc.Split(bufio.ScanWords)

	T := nextInt()
	for T > 0 {
		T--
		n := nextInt()
		if n == 3 {
			fmt.Println("-1")
			continue
		}
		if n%2 == 0 {
			for i := 0; i < n; i++ {
				fmt.Printf("%d ", n-i)
			}
			fmt.Println()
		} else {
			for i := 1; i <= n-3; i++ {
				if i%2 == 1 {
					fmt.Printf("%d ", n-i)
				} else {
					fmt.Printf("%d ", n+2-i)
				}
			}
			fmt.Println("1 2 3")
		}
	}
}

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

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

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

package main

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

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

func readInt() int {
	var i int
	fmt.Fscan(reader, &i)
	return i
}

func main(){
	defer writer.Flush()
	T := readInt()

	for ;T > 0; T-- {
		n := readInt()

		if n == 2 {
			fmt.Fprintln(writer, "2 1")
			continue
		}

		if n == 3 {
			fmt.Fprintln(writer, "-1")
			continue
		}

		fmt.Fprint(writer,  n - 1, " ", n)

		for i := 1; i <= n - 2; i++ {
			fmt.Fprint(writer, " ", i)
		}

		fmt.Fprintln(writer)
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		if n == 3 {
			fmt.Fprintln(out, -1)
			continue
		}
		for i := n/2 + 1; i <= n; i++ {
			fmt.Fprintf(out, "%d ", i)
		}
		for i := n / 2; i > 0; i-- {
			fmt.Fprintf(out, "%d ", i)
		}
		fmt.Fprintln(out)
	}
}

package main

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

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

func b1740(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T int
	var n int

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)

		ans := []int{}
		if n == 3 {
			ans = []int{-1}
		} else if n%2 == 0 {
			for i := 0; i < n; i++ {
				ans = append(ans, n-i)
			}
		} else {
			ans = append(ans, n/2 + 1)
			for i := 0; i < n/2; i++ {
				ans = append(ans, ans[0]+i+1)
			}
			for i := 0; i < n/2; i++ {
				ans = append(ans, i+1)
			}
		}

		for _, v := range ans {
			Fprintf(out, "%d ", v)
		}
		Fprintln(out, "")
	}
}

package main

import (
	"fmt"
)

func main() {
	var num int
	fmt.Scan(&num)
	for i := 0; i < num; i++ {

		var num1 int
		fmt.Scan(&num1)
		var arr []int
		arr = sec(num1)
		for i := 0; i < len(arr); i++ {
			fmt.Printf("%d ", arr[i])
		}
		fmt.Println()
	}

}
func sec(num int) []int {
	var arr []int
	if num == 3 {
		arr = append(arr, -1)
		return arr
	}
	if num == 2 {
		arr = append(arr, 2, 1)
		return arr
	}
	if num == 5 {
		arr = append(arr, 4, 5, 1, 2, 3)
		return arr
	}
	for i := num; i > 0; i-- {
		arr = append(arr, i)
	}
	if num > 5 {
		mid := (num / 2)
		arr[mid] += 1
		arr[mid-1] -= 1
	}

	return arr
}

package main

import (
	"fmt"
)

func main() {
	var num int
	fmt.Scan(&num)
	for i := 0; i < num; i++ {

		var num1 int
		fmt.Scan(&num1)
		var arr []int
		arr = sec(num1)
		for i := 0; i < len(arr); i++ {
			fmt.Printf("%d ", arr[i])
		}
		fmt.Println()
	}

}
func sec(num int) []int {
	var arr []int
	if num == 3 {
		arr = append(arr, -1)
		return arr
	}
	if num == 2 {
		arr = append(arr, 2, 1)
		return arr
	}
	if num == 5 {
		arr = append(arr, 4, 5, 3, 2, 1)
		return arr
	}
	for i := num; i > 0; i-- {
		arr = append(arr, i)
	}
	if num > 5 {
		mid := (num / 2)
		arr[mid] += 1
		arr[mid-1] -= 1
	}

	return arr
}

package main

import (
	"fmt"
)

func main() {
	var num int
	fmt.Scan(&num)
	for i := 0; i < num; i++ {

		var num1 int
		fmt.Scan(&num1)
		var arr []int
		arr = sec(num1)
		for i := 0; i < len(arr); i++ {
			fmt.Printf("%d ", arr[i])
		}
		fmt.Println()
	}

}
func sec(num int) []int {
	var arr []int
	if num == 3 {
		arr = append(arr, -1)
		return arr
	}
	if num == 2 {
		arr = append(arr, 2, 1)
		return arr
	}
	if num == 5 {
		arr = append(arr, 4, 5, 3, 2, 1)
		return arr
	}
	for i := num; i > 0; i-- {
		arr = append(arr, i)
	}
	if num > 5 {
		mid := (num / 2) + 1
		arr[mid] -= 1
		arr[mid+1] += 1
	}

	return arr
}

package main

import (
	"fmt"
)

func main() {
	var num int
	fmt.Scan(&num)
	for i := 0; i < num; i++ {

		var num1 int
		fmt.Scan(&num1)
		var arr []int
		arr = sec(num1)
		for i := 0; i < len(arr); i++ {
			fmt.Printf("%d ", arr[i])
		}
	}

}
func sec(num int) []int {
	var arr []int
	if num == 3 {
		arr = append(arr, -1)
		return arr
	}
	if num == 2 {
		arr = append(arr, 2, 1)
		return arr
	}
	if num == 5 {
		arr = append(arr, 4, 5, 3, 2, 1)
		return arr
	}
	for i := num; i > 0; i-- {
		arr = append(arr, i)
	}
	if num > 5 {
		mid := (num / 2) + 1
		arr[mid] -= 1
		arr[mid+1] += 1
	}

	return arr
}

package main

import (
	"fmt"
)

func main() {
	var num int
	fmt.Scan(&num)
	for i := 0; i < num; i++ {

		var num int
		fmt.Scan(&num)
		var arr []int
		arr = sec(num)
		fmt.Println(arr)
	}

}
func sec(num int) []int {
	var arr []int
	if num == 3 {
		arr = append(arr, -1)
		return arr
	}
	if num == 2 {
		arr = append(arr, 2, 1)
		return arr
	}
	for i := num; i > 0; i-- {
		arr = append(arr, i)
	}
	for i := 0; i < len(arr); i += 2 {
		if arr[i] == 3 || arr[i+1] == 3 {
			break
		}
		var temp int
		temp = arr[i]
		arr[i] = arr[i+1]
		arr[i+1] = temp
	}

	return arr
}

package main

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

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

func solve() string {
	var n int
	fmt.Fscan(in, &n)

	if n == 3 {
		return "-1"
	}

	res := strconv.Itoa(n-1) + " " + strconv.Itoa(n)
	if n%2 == 0 {
		for i := n - 2; i > 0; i-- {
			res += " " + strconv.Itoa(i)
		}
	} else {
		for i := 1; i <= n-2; i++ {
			res += " " + strconv.Itoa(i)
		}
	}

	return res
}

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

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

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

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

func makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}

package main

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

func solve(_r io.Reader, _w io.Writer) {

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)

	defer out.Flush()

	var T int
	Fscan(in, &T)
	for ; T > 0; T-- {
		var n int
		Fscan(in, &n)
		if n == 3 {
			Fprintln(out, "-1")
			continue
		}
		if n%2 == 0 {
			for i := 1; i <= n; i += 2 {
				Fprint(out, i+1, " ", i, " ")
			}
			Fprintln(out)
			continue
		} else {
			for i := 4; i <= n; i += 2 {
				Fprint(out, i+1, " ", i, " ")
			}
			for i := 3; i >= 1; i-- {
				Fprint(out, i, " ")
			}
			Fprintln(out)
			continue
		}
	}

}

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

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

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

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

package main

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

func solve(_r io.Reader, _w io.Writer) {

	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)

	defer out.Flush()

	var T int
	Fscan(in, &T)
	for ; T > 0; T-- {
		var n int
		Fscan(in, &n)
		if n == 3 {
			Fprintln(out, "-1")
			continue
		}
		if n%2 == 0 {
			for i := 1; i <= n; i += 2 {
				Fprint(out, i+1, " ", i, " ")
			}
			Fprintln(out)
			continue
		} else {
			for i := 3; i >= 1; i-- {
				Fprint(out, i, " ")
			}
			for i := 4; i <= n; i += 2 {
				Fprint(out, i+1, " ", i, " ")
			}
			Fprintln(out)
			continue
		}
	}

}

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

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

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

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

package main

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

const mod = 998244353
const mx = int64(1e9 + 7)

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	Fscan(in, &n)
	if n == 1 || n == 3 {
		Fprintln(out, "-1")
		return
	}
	for i := n; i >= 1; i-- {
		if n%2 == 1 && n/2 == i {
			Fprintf(out, "%d ", i+1)
			continue
		}
		if n%2 == 1 && (n+1)/2 == i {
			Fprintf(out, "%d ", i-1)
			continue
		}
		Fprintf(out, "%d ", i)
	}
	Fprintln(out)
}

func abs(a int64) int64 {
	if a > 0 {
		return a
	}
	return -a
}
func sum(a, b int64) int64 {
	return (b + a) * (b - a + 1) / 2
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}