A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.

Input will begin with a line containing N (1 ≤ N ≤ 100000), the number of engineers.  N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2·N. It is guaranteed that no two engineers sit at the same desk.

Print the number of possible assignments, modulo 1000000007 = 109 + 7.

NoteThese are the possible assignments for the first example:   1 5 3 7  1 2 3 7  5 2 3 7  1 5 7 3  1 2 7 3  5 2 7 3

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

const mod = 1000000007

func main() {
	in.Split(bufio.ScanWords)
	n := readInt()
	ans := int64(1)
	to := make([]int, 2*n+1)
	from := make([][]int, 2*n+1)
	for i := 0; i < n; i++ {
		x := readInt()
		y := readInt()
		to[x] = y
		from[y] = append(from[y], x)
	}

	var dfs func(int) int64
	dfs = func(v int) int64 {
		res := int64(1)
		for _, u := range from[v] {
			res += dfs(u)
			to[u] = 0
		}
		from[v] = nil
		return res
	}
	for i := 1; i <= 2*n; i++ {
		if to[i] == 0 && len(from) > 0 {
			ans = ans * dfs(i) % mod
		}
	}

	cyc := make([]int, 2*n+1)
	cur := 0
	for i := 1; i <= 2*n; i++ {
		if to[i] == 0 {
			continue
		}
		if cyc[i] == 0 {
			cur++
			j := i
			for ; cyc[j] == 0; j = to[j] {
				cyc[j] = cur
			}
			if cyc[j] == cur && to[j] != j {
				ans = ans * 2 % mod
			}
		}
	}
	fmt.Println(ans)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

const mod = 1000000007

func main() {
	in.Split(bufio.ScanWords)
	n := readInt()
	ans := 1
	to := make([]int, 2*n+1)
	from := make([][]int, 2*n+1)
	for i := 0; i < n; i++ {
		x := readInt()
		y := readInt()
		to[x] = y
		from[y] = append(from[y], x)
	}

	var dfs func(int) int
	dfs = func(v int) int {
		res := 1
		for _, u := range from[v] {
			res += dfs(u)
			to[u] = 0
		}
		from[v] = nil
		return res
	}
	for i := 1; i <= 2*n; i++ {
		if to[i] == 0 && len(from) > 0 {
			ans = ans * dfs(i) % mod
		}
	}

	cyc := make([]int, 2*n+1)
	cur := 0
	for i := 1; i <= 2*n; i++ {
		if to[i] == 0 {
			continue
		}
		if cyc[i] == 0 {
			cur++
			j := i
			for ; cyc[j] == 0; j = to[j] {
				cyc[j] = cur
			}
			if cyc[j] == cur && to[j] != j {
				ans = ans * 2 % mod
			}
		}
	}
	fmt.Println(ans)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

const mod = 1000000007

func main() {
	in.Split(bufio.ScanWords)
	n := readInt()
	ans := 1
	to := make([]int, 2*n+1)
	from := make([][]int, 2*n+1)
	for i := 0; i < n; i++ {
		x := readInt()
		y := readInt()
		if x == y {
			continue
		}
		to[x] = y
		from[y] = append(from[y], x)
	}

	var dfs func(int) int
	dfs = func(v int) int {
		res := 1
		for _, u := range from[v] {
			res += dfs(u)
			to[u] = 0
		}
		from[v] = nil
		return res
	}
	for i := 1; i <= 2*n; i++ {
		if to[i] == 0 && len(from) > 0 {
			ans = ans * dfs(i) % mod
		}
	}

	cyc := make([]int, 2*n+1)
	cur := 0
	for i := 1; i <= 2*n; i++ {
		if to[i] == 0 {
			continue
		}
		if cyc[i] == 0 {
			cur++
			j := i
			for ; cyc[j] == 0; j = to[j] {
				cyc[j] = cur
			}
			if cyc[j] == cur {
				ans = ans * 2 % mod
			}
		}
	}
	fmt.Println(ans)
}


You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).

The first line contains a single integer n (2 ≤ n ≤ 104) — the number of vertices in the tree. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi means that there is an edge between vertices i and pi. The third line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ n), where ci is the color you should color the i-th vertex into. It is guaranteed that the given graph is a tree.

Print a single integer — the minimum number of steps you have to perform to color the tree into given colors.

NoteThe tree from the first sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):On seond step we color all vertices in the subtree of vertex 5 into color 1:On third step we color all vertices in the subtree of vertex 2 into color 1:The tree from the second sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):On second step we color all vertices in the subtree of vertex 3 into color 1:On third step we color all vertices in the subtree of vertex 6 into color 2:On fourth step we color all vertices in the subtree of vertex 4 into color 1:On fith step we color all vertices in the subtree of vertex 7 into color 3:

package main

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

func main() {
	in := bufio.NewScanner(os.Stdin)
	in.Scan()
	input1 := in.Text()
	n, _ := strconv.Atoi(input1)
	in.Scan()
	input2 := strings.Split(in.Text(), " ")
	svyaz := make([]int, 0)
	for i := 0; i < n-1; i++ {
		dob, _ := strconv.Atoi(input2[i])
		svyaz = append(svyaz, dob)
	}
	in.Scan()
	input2 = strings.Split(in.Text(), " ")
	cvet := make([]int, 0)
	for i := 0; i < n; i++ {
		dob, _ := strconv.Atoi(input2[i])
		cvet = append(cvet, dob)
	}
	schet := 0
	for i := 1; i < n; i++ {
		if cvet[i] != cvet[svyaz[i-1]-1] {
			schet++
		}
	}
	schet++
	fmt.Println(schet)
}

package main

import (
	"fmt"
)

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

	t := make([][]int, n)
	r := make([]int, n)
	r[0] = -1
	for i := 0; i < n-1; i++ {
		var c int
		fmt.Scan(&c)
		t[c-1] = append(t[c-1], i+1)
		r[i+1] = c - 1
	}
	cs := make([]int, n)
	for i := 0; i < n; i++ {
		var c int
		fmt.Scan(&c)
		cs[i] = c - 1
	}
	ccs := make([]int, n)
	q := make([]int, 0, n)
	q = append(q, 0)
	rs := 0
	for len(q) > 0 {
		n := q[0]
		p := r[n]
		pc := -1
		if p != -1 {
			pc = ccs[p]
		}
		if pc != cs[n] {
			ccs[n] = cs[n]
			rs++
		} else {
			chs := make([]int, 0, 100)
			for _, i := range t[n] {
				if i == p {
					continue
				}
				chs = append(chs, i)
				r[i] = p
			}
			t[p] = chs
		}
		q = append(q, t[n]...)
		q = q[1:]
	}
	fmt.Println(rs)
}

package main

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

type vertex struct {
	color, wantColor int
	conns            []*vertex
}

func (v *vertex) paint(c int, p *vertex) {
	v.color = c
	for _, conn := range v.conns {
		if conn == p {
			continue
		}
		conn.paint(c, v)
	}
}

func (v *vertex) Paint(p *vertex) int {
	var ans int
	if v.color != v.wantColor {
		ans++
		v.paint(v.wantColor, p)
	}
	for _, conn := range v.conns {
		if conn == p {
			continue
		}
		ans += conn.Paint(v)
	}
	return ans
}

func read() *vertex {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(r, &n)

	vs := make([]*vertex, 0, n)
	for i := 0; i < n; i++ {
		vs = append(vs, &vertex{})
	}

	for i := 1; i < n; i++ {
		var p int
		fmt.Fscan(r, &p)
		vs[i].conns = append(vs[i].conns, vs[p-1])
		vs[p-1].conns = append(vs[p-1].conns, vs[i])
	}

	for i := 0; i < n; i++ {
		fmt.Fscan(r, &vs[i].wantColor)
	}

	return vs[0]
}

func main() {
	root := read()
	fmt.Println(root.Paint(nil))
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001]list.List // tree
	t2 [10001]list.List // rooted tree
	f [10001]bool // used
)

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i].PushBack(pi)
		t[pi].PushBack(i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

type node struct {
	index int32
	color int32
}

func buildRootedTree() {
	var q list.List
	q.PushBack(int32(1))
	f[1] = true
	for q.Len() > 0 {
		v := q.Remove(q.Front()).(int32)
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for e := t[v].Front(); e != nil; e = e.Next() {
			v2 := e.Value.(int32)
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v].PushBack(v2) // the right edge
				q.PushBack(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q list.List
	q.PushBack(int32(1))
	for q.Len() > 0 {
		v := q.Remove(q.Front()).(int32)
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for e := t2[v].Front(); e != nil; e = e.Next() {
			q.PushBack(e.Value.(int32))
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for e := t2[n].Front(); e != nil; e = e.Next() {
		colorSubTree(e.Value.(int32), c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001][]int32 // tree
	t2 [10001][]int32 // rooted tree
	f [10001]bool // used
)

func init() {
	for i := range t {
		t[i] = make([]int32, 0, 2) // 多余的内存分配也会浪费时间
	}
	for i := range t2 {
		t2[i] = make([]int32, 0, 2)
	}
}

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i] = append(t[i], pi)
		t[pi] = append(t[pi], i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

func buildRootedTree() {
	var q Queue
	q.Push(1)
	f[1] = true
	for !q.Empty() {
		v := q.Pop()
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for i := 0; i < len(t[v]); i++ {
			v2 := t[v][i]
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v] = append(t2[v], v2) // the right edge
				q.Push(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q Queue
	q.Push(1)
	for !q.Empty() {
		v := q.Pop()
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for _, v2 := range t2[v] {
			q.Push(v2)
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for _, v := range t2[n] {
		colorSubTree(v, c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

type Queue struct {
	q []int32 // elements
}

func (this *Queue) Push(v int32) { // should consider pointer
	this.q = append(this.q, v)
}

func (this *Queue) Pop() int32 {
	if len(this.q) == 0 {
		panic("")
	}
	v := this.q[0]
	this.q = this.q[1:]
	return v
}

func (this *Queue) Empty() bool {
	return len(this.q) == 0
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001][]int32 // tree
	t2 [10001][]int32 // rooted tree
	f [10001]bool // used
)

func init() {
	for i := range t {
		t[i] = make([]int32, 0, 100)
	}
	for i := range t2 {
		t2[i] = make([]int32, 0, 100)
	}
}

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i] = append(t[i], pi)
		t[pi] = append(t[pi], i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

type node struct {
	index int32
	color int32
}

func buildRootedTree() {
	var q Queue
	q.PushBack(1)
	f[1] = true
	for q.Len() > 0 {
		v := q.PopFront()
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for i := 0; i < len(t[v]); i++ {
			v2 := t[v][i]
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v] = append(t2[v], v2) // the right edge
				q.PushBack(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q Queue
	q.PushBack(1)
	for q.Len() > 0 {
		v := q.PopFront()
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for _, v2 := range t2[v] {
			q.PushBack(v2)
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for _, v := range t2[n] {
		colorSubTree(v, c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

type Queue struct {
	list []int32 // elements
	begin int // start
}

func (this *Queue) Len() int {
	return len(this.list) - this.begin
}

func (this *Queue) PushBack(v int32) { // should consider *int32
	this.list = append(this.list, v)
}

func (this *Queue) PopFront() int32 {
	end := len(this.list)
	if this.begin >= end {
		panic("")
	}
	v := this.list[this.begin]
	this.begin++
	return v
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001][]int32 // tree
	t2 [10001][]int32 // rooted tree
	f [10001]bool // used
)

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i] = append(t[i], pi)
		t[pi] = append(t[pi], i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

type node struct {
	index int32
	color int32
}

func buildRootedTree() {
	var q list.List
	q.PushBack(int32(1))
	f[1] = true
	for q.Len() > 0 {
		v := q.Remove(q.Front()).(int32)
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for i := 0; i < len(t[v]); i++ {
			v2 := t[v][i]
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v] = append(t2[v], v2) // the right edge
				q.PushBack(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q list.List
	q.PushBack(int32(1))
	for q.Len() > 0 {
		v := q.Remove(q.Front()).(int32)
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for _, v2 := range t2[v] {
			q.PushBack(v2)
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for _, v := range t2[n] {
		colorSubTree(v, c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001][]int32 // tree
	t2 [10001][]int32 // rooted tree
	f [10001]bool // used
)

func init() {
	for i := range t {
		t[i] = make([]int32, 0, 10)
	}
	for i := range t2 {
		t2[i] = make([]int32, 0, 10)
	}
}

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i] = append(t[i], pi)
		t[pi] = append(t[pi], i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

type node struct {
	index int32
	color int32
}

func buildRootedTree() {
	var q Queue
	q.PushBack(1)
	f[1] = true
	for q.Len() > 0 {
		v := q.PopFront()
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for i := 0; i < len(t[v]); i++ {
			v2 := t[v][i]
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v] = append(t2[v], v2) // the right edge
				q.PushBack(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q Queue
	q.PushBack(1)
	for q.Len() > 0 {
		v := q.PopFront()
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for _, v2 := range t2[v] {
			q.PushBack(v2)
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for _, v := range t2[n] {
		colorSubTree(v, c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

type Queue struct {
	list []int32 // elements
	begin int // start
}

func (this *Queue) Len() int {
	return len(this.list) - this.begin
}

func (this *Queue) PushBack(v int32) { // should consider *int32
	this.list = append(this.list, v)
}

func (this *Queue) PopFront() int32 {
	end := len(this.list)
	if this.begin >= end {
		panic("")
	}
	v := this.list[this.begin]
	this.begin++
	return v
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001][]int32 // tree
	t2 [10001][]int32 // rooted tree
	f [10001]bool // used
)

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i] = append(t[i], pi)
		t[pi] = append(t[pi], i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

type node struct {
	index int32
	color int32
}

func buildRootedTree() {
	var q Queue
	q.PushBack(int32(1))
	f[1] = true
	for q.Len() > 0 {
		v := q.PopFront().(int32)
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for i := 0; i < len(t[v]); i++ {
			v2 := t[v][i]
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v] = append(t2[v], v2) // the right edge
				q.PushBack(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q Queue
	q.PushBack(int32(1))
	for q.Len() > 0 {
		v := q.PopFront().(int32)
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for _, v2 := range t2[v] {
			q.PushBack(v2)
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for _, v := range t2[n] {
		colorSubTree(v, c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

type Queue struct {
	list []interface{} // elements
	begin int // start
}

func (this *Queue) Len() int {
	return len(this.list) - this.begin
}

func (this *Queue) PushBack(v interface{}) { // should consider *int32
	this.list = append(this.list, v)
}

func (this *Queue) PopFront() interface{} {
	end := len(this.list)
	if this.begin >= end {
		panic("")
	}
	v := this.list[this.begin]
	this.begin++
	return v
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001][]int32 // tree
	t2 [10001][]int32 // rooted tree
	f [10001]bool // used
)

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i] = append(t[i], pi)
		t[pi] = append(t[pi], i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

type node struct {
	index int32
	color int32
}

func buildRootedTree() {
	var q Queue
	q.PushBack(1)
	f[1] = true
	for q.Len() > 0 {
		v := q.PopFront()
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for i := 0; i < len(t[v]); i++ {
			v2 := t[v][i]
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v] = append(t2[v], v2) // the right edge
				q.PushBack(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q Queue
	q.PushBack(1)
	for q.Len() > 0 {
		v := q.PopFront()
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for _, v2 := range t2[v] {
			q.PushBack(v2)
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for _, v := range t2[n] {
		colorSubTree(v, c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

type Queue struct {
	list []int32 // elements
	begin int // start
}

func (this *Queue) Len() int {
	return len(this.list) - this.begin
}

func (this *Queue) PushBack(v int32) { // should consider *int32
	this.list = append(this.list, v)
}

func (this *Queue) PopFront() int32 {
	end := len(this.list)
	if this.begin >= end {
		panic("")
	}
	v := this.list[this.begin]
	this.begin++
	return v
}

package main

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

var (
	c2 [10001]int32 // current color
	c [10001]int32 // need color
	t [10001][]int32 // tree
	t2 [10001][]int32 // rooted tree
	f [10001]bool // used
)

func init() {
	for i := range t {
		t[i] = make([]int32, 0, 2)
	}
	for i := range t2 {
		t2[i] = make([]int32, 0, 2)
	}
}

var reader SReader

func main() {
    reader.Init()
	n := reader.ReadInt()
	for i := int32(2); i <= n; i++ {
		pi := reader.ReadInt()
		t[i] = append(t[i], pi)
		t[pi] = append(t[pi], i)
	}

	for i := int32(1); i <= n; i++ {
		c[i] = reader.ReadInt()
	}

	buildRootedTree()

	// for i := int32(0); i <= n; i++ {
	// 	fmt.Printf("%d: %#v\n", i, t2[i])
	// }

	colorTree()
}

type node struct {
	index int32
	color int32
}

func buildRootedTree() {
	var q Queue
	q.PushBack(1)
	f[1] = true
	for q.Len() > 0 {
		v := q.PopFront()
		//fmt.Println(v)
		//fmt.Printf("%d:", v)
		for i := 0; i < len(t[v]); i++ {
			v2 := t[v][i]
			if !f[v2] { // have not trip
				//fmt.Printf(" %d", v2)
				t2[v] = append(t2[v], v2) // the right edge
				q.PushBack(v2)
				f[v2] = true
			}
		}
		//fmt.Println()
	}
}

// bfs
func colorTree() {
	nSum := 0
	var q Queue
	q.PushBack(1)
	for q.Len() > 0 {
		v := q.PopFront()
		if c2[v] != c[v] {
			//fmt.Printf("----- color sub tree %d ------\n", v)
			colorSubTree(v, c[v]) // color all the sub tree
			nSum++
			//fmt.Println("    ")
		}
		for _, v2 := range t2[v] {
			q.PushBack(v2)
		}
	}

	fmt.Println(nSum)
}

// dfs
func colorSubTree(n, c int32) {
	c2[n] = c
	//fmt.Printf("%d(%d)\n", n, c)
	for _, v := range t2[n] {
		colorSubTree(v, c)
	}
}

// reader
type SReader struct {
    file *os.File
    scanner *bufio.Scanner
}

func (this *SReader) Init() {
    this.file = os.Stdin
    this.scanner = bufio.NewScanner(this.file)
    this.scanner.Split(bufio.ScanWords)
}

func (this *SReader) ReadInt() int32 {
    this.scanner.Scan()
    n, err:= strconv.ParseInt(this.scanner.Text(), 10, 0)
    if err != nil {
        panic(err)
    }
    return int32(n)
}

type Queue struct {
	list []int32 // elements
	begin int // start
}

func (this *Queue) Len() int {
	return len(this.list) - this.begin
}

func (this *Queue) PushBack(v int32) { // should consider *int32
	this.list = append(this.list, v)
}

func (this *Queue) PopFront() int32 {
	end := len(this.list)
	if this.begin >= end {
		panic("")
	}
	v := this.list[this.begin]
	this.begin++
	return v
}

package main

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

var edge [][]int
var c []int
var checked []bool

func recv(p int, color int) int {
	sum := 0
	if c[p-1] != color {
		sum++
	}
	checked[p] = true

	for i := 0; i < len(edge[p]); i++ {
		if checked[edge[p][i]] {
			continue
		}
		sum += recv(edge[p][i], c[p-1])
	}
	return sum
}

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	p := sc.NextIntArray()
	c = sc.NextIntArray()
	checked = make([]bool, N+1)

	edge = make([][]int, N+1)
	for i := 0; i < len(edge); i++ {
		edge[i] = make([]int, 0)
	}

	for i, v := range p {
		edge[i+2] = append(edge[i+2], v)
		edge[v] = append(edge[v], i+2)
	}
	fmt.Println(recv(1, 0))
}

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

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

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

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

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

	return mp
}

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

package main

import (
	"fmt"
)

type v struct {
	children []int64
	target   int64
}

func sol(vertices []v, i int64, curr int64) int64 {
	ret := int64(0)
	if curr != vertices[i].target {
		ret++
		curr = vertices[i].target
	}
	for _, child := range vertices[i].children {
		ret = ret + sol(vertices, child, curr)
	}
	return ret
}

func main() {
	var i, n int64
	fmt.Scanf("%d\n", &n)
	vertices := make([]v, n)
	for i = 0; i < n-1; i++ {
		var p int64
		if i == n-2 {
			fmt.Scanf("%d\n", &p)
		} else {
			fmt.Scanf("%d", &p)
		}
		vertices[p-1].children = append(vertices[p-1].children, i+1)
	}
	for i = 0; i < n; i++ {
		var c int64
		fmt.Scanf("%d", &c)
		vertices[i].target = c
	}
	fmt.Println(sol(vertices, 0, -1))
}

package main

import (
	"fmt"
)

type v struct {
	c      []int
	target int
}

func sol(vertices []v, i int, curr int) int {
	ret := 0
	if curr != vertices[i].target {
		ret++
		curr = vertices[i].target
	}
	for _, t := range vertices[i].c {
		ret = ret + sol(vertices, t, curr)
	}
	return ret
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	vertices := make([]v, n)
	for i := 0; i < n-1; i++ {
		var p int
		fmt.Scanf("%d", &p)
		vertices[p-1].c = append(vertices[p-1].c, i+1)
	}
	for i := 0; i < n; i++ {
		var c int
		fmt.Scanf("%d", &c)
		vertices[i].target = c
	}
	fmt.Println(sol(vertices, 0, 0))
}

package main

import (
	"fmt"
)

type v struct {
	c      []int
	target int
}

func sol(vertices []v, i int, curr int) int {
	ret := 0
	if curr != vertices[i].target {
		ret++
		curr = vertices[i].target
	}
	for _, t := range vertices[i].c {
		ret = ret + sol(vertices, t, curr)
	}
	return ret
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	vertices := []v{
		v{c: []int{}},
	}
	for i := 0; i < n-1; i++ {
		var p int
		fmt.Scanf("%d", &p)
		vertices = append(vertices, v{c: []int{}})
		vertices[p-1].c = append(vertices[p-1].c, i+1)
	}
	for i := 0; i < n; i++ {
		var c int
		fmt.Scanf("%d", &c)
		vertices[i].target = c
	}
	fmt.Println(sol(vertices, 0, 0))
}

package main

import (
	"fmt"
)

type v struct {
	children []int64
	target   int64
}

func sol(vertices []v, i int64, curr int64) int64 {
	ret := int64(0)
	if curr != vertices[i].target {
		ret++
		curr = vertices[i].target
	}
	for _, child := range vertices[i].children {
		ret = ret + sol(vertices, child, curr)
	}
	return ret
}

func main() {
	var i, n int64
	fmt.Scanf("%d\n", &n)
	vertices := make([]v, n)
	for i = 0; i < n-1; i++ {
		var p int64
		fmt.Scanf("%d", &p)
		vertices[p-1].children = append(vertices[p-1].children, i+1)
	}
	for i = 0; i < n; i++ {
		var c int64
		fmt.Scanf("%d", &c)
		vertices[i].target = c
	}
	fmt.Println(vertices)
	fmt.Println(sol(vertices, 0, -1))
}

package main

import (
	"fmt"
)

type v struct {
	children []int64
	target   int64
}

func sol(vertices []v, i int64, curr int64) int64 {
	ret := int64(0)
	if curr != vertices[i].target {
		ret++
		curr = vertices[i].target
	}
	for _, child := range vertices[i].children {
		ret = ret + sol(vertices, child, curr)
	}
	return ret
}

func main() {
	var i, n int64
	fmt.Scanf("%d\n", &n)
	vertices := make([]v, n)
	for i = 0; i < n-1; i++ {
		var p int64
		if i == n-2 {
			fmt.Scanf("%d\n", &p)
		} else {
			fmt.Scanf("%d", &p)
		}
		vertices[p-1].children = append(vertices[p-1].children, i+1)
	}
	for i = 0; i < n; i++ {
		var c int64
		fmt.Scanf("%d", &c)
		vertices[i].target = c
	}
	fmt.Println(vertices)
	fmt.Println(sol(vertices, 0, -1))
}

package main

import (
	"fmt"
)

type v struct {
	c      []int64
	target int64
}

func sol(vertices []v, i int64, curr int64) int64 {
	ret := int64(0)
	if curr != vertices[i].target {
		ret++
		curr = vertices[i].target
	}
	for _, t := range vertices[i].c {
		ret = ret + sol(vertices, t, curr)
	}
	return ret
}

func main() {
	var i, n int64
	fmt.Scanf("%d\n", &n)
	vertices := make([]v, n)
	for i = 0; i < n-1; i++ {
		var p int64
		fmt.Scanf("%d", &p)
		vertices[p-1].c = append(vertices[p-1].c, i+1)
	}
	for i = 0; i < n; i++ {
		var c int64
		fmt.Scanf("%d", &c)
		vertices[i].target = c
	}
	fmt.Println(sol(vertices, 0, 0))
}


Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.

The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.

If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes).

10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer

10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever

7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck

bcdefghijklmnopqrsatuvwxyz Impossible aghjlnopefikdmbcqrstuvwxyz acbdefhijklmnogpqrstuvwxyz

//https://codeforces.com/problemset/problem/510/C
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC01/ORANGE_L01P03/statement
package main

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

func solve(names []string, n int) string {
	relation := map[byte][]byte{}
	inDegree := make([]int, 26)

	for i := 0; i < n-1; i++ {
		minLength := min(len(names[i]), len(names[i+1]))
		for j := 0; j < minLength; j++ {
			if names[i][j] != names[i+1][j] {
				relation[names[i][j]] = append(relation[names[i][j]], names[i+1][j])
				inDegree[names[i+1][j]-'a']++
				break
			}

			if j == minLength-1 {
				if len(names[i+1]) < len(names[i]) {
					return "Impossible"
				}
			}
		}
	}

	res, isCyclic := kahn(inDegree, relation)

	if isCyclic {
		return "Impossible"
	}

	return res
}

func min(n1 int, n2 int) int {
	if n1 < n2 {
		return n1
	}

	return n2
}

func kahn(inDegree []int, relation map[byte][]byte) (string, bool) {
	zeroDegree := []byte{}
	res := []byte{}
	for i := range inDegree {
		if inDegree[i] == 0 {
			zeroDegree = append(zeroDegree, byte(i)+'a')

		}
	}

	for len(zeroDegree) > 0 {
		cur := dequeue(&zeroDegree)
		res = append(res, cur)
		for i := range relation[cur] {
			c := relation[cur][i]
			inDegree[c-'a']--
			if inDegree[c-'a'] == 0 {
				zeroDegree = append(zeroDegree, c)
			}
		}
	}

	for i := range inDegree {
		if inDegree[i] != 0 {
			return "", true
		}
	}

	return string(res), false
}

func dequeue(q *[]byte) byte {
	n := (*q)[0]
	(*q) = (*q)[1:]

	return n
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(r, "%d\n", &n)

	names := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%s\n", &names[i])
	}

	fmt.Fprintf(os.Stdout, "%s\n", solve(names, n))
}

package main

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

type graph struct {
	size     int
	edges    [][]int
	inDegree []int
}

func newGraph(size int) *graph {
	return &graph{
		size:     size,
		edges:    make([][]int, size),
		inDegree: make([]int, size),
	}
}

func (g *graph) add(from, to int) {
	g.edges[from] = append(g.edges[from], to)
	g.inDegree[to]++
}

func (g *graph) topSort() (order []int, acyclic bool) {
	queue := []int{}
	for i := 0; i < g.size; i++ {
		if g.inDegree[i] == 0 {
			queue = append(queue, i)
		}
	}
	var v int
	for len(queue) > 0 {
		v, queue = queue[0], queue[1:]
		order = append(order, v)
		for _, w := range g.edges[v] {
			g.inDegree[w]--
			if g.inDegree[w] == 0 {
				queue = append(queue, w)
			}
		}
	}
	return order, len(order) == g.size
}

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

	g := newGraph(26)
	var n int
	Fscan(in, &n)
	var prev, cur string
	for ; n > 0; n-- {
		Fscan(in, &cur)
		minL := len(prev)
		if len(cur) < minL {
			minL = len(cur)
		}
		ok := false
		for i := 0; i < minL; i++ {
			if v, w := prev[i]-'a', cur[i]-'a'; v != w {
				g.add(int(v), int(w))
				ok = true
				break
			}
		}
		if !ok && len(prev) > len(cur) {
			Fprint(out, "Impossible")
			return
		}
		prev = cur
	}

	order, acyclic := g.topSort()
	if !acyclic {
		Fprint(out, "Impossible")
		return
	}
	done := make([]bool, 26)
	for _, c := range order {
		Fprintf(out, "%c", 'a'+c)
		done[c] = true
	}
	for i, d := range done {
		if !d {
			Fprintf(out, "%c", 'a'+i)
		}
	}
}

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

package main

import "fmt"

var depends map[string][]string = make(map[string][]string)
var last string
var visited map[string]bool = make(map[string]bool)
var general string
var took map[string]bool = make(map[string]bool)

func gen(x string) bool {
  if _, ok := visited[x]; ok {
    return true
  }

  visited[x] = true
  took[x] = true

  for _, p := range depends[x] {
    if _, ok := took[p]; ok {
      fmt.Println("Impossible")
      return false
    }

    if _, ok := visited[p]; !ok {
      var v = gen(p)
      if !v {
        return false
      }
    }
  }

  delete(took, x)
  general = general + x
  return true
}

func add(name string) bool {
  var compare int
  for i := 0; i < len(name) && i < len(last); i++ {
    if name[i] != last[i] {
      compare = i
      break
    }
  }

  var a = string(last[compare])
  var b = string(name[compare])

  if a == b {
    if len(name) < len(last) {
      fmt.Println("Impossible")
      return false
    }
    return true
  }

  if _, ok := depends[b]; !ok {
    depends[b] = make([]string, 0)
  }

  depends[b] = append(depends[b], a)

  last = name
  return true
}

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

  var ok = true

  var name string
  for i := 0; i < n - 1; i++ {
    fmt.Scanf("%s\n", &name)
    if !add(name) {
      ok = false
      break
    }
  }

  if ok {
    for _, i := range "abcdefghijklmnopqrstuvwxyz" {
      if !gen(string(i)) {
        ok = false
        break
      }
    }
  }

  if ok {
    fmt.Println(general)
  }
}

// Author: sighduck
// Inspiration: https://codeforces.com/contest/510/submission/62109848
// URL: https://codeforces.com/problemset/problem/510/C

package main

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

const alphabet = "abcdefghijklmnopqrstuvwxyz"

type Graph struct {
	edges    map[string][]string
	inDegree map[string]int
}

func initGraph() Graph {
	return Graph{
		edges:    make(map[string][]string),
		inDegree: make(map[string]int),
	}
}

func add(g Graph, start string, end string) {
	g.edges[start] = append(g.edges[start], end)
	g.inDegree[end] += 1
}

func topologicalSort(g Graph) string {
	queue := []string{}
	for _, letter := range alphabet {
		s := string(letter)
		if g.inDegree[s] == 0 {
			queue = append(queue, s)
		}
	}
	path := []string{}
	for len(queue) > 0 {
		node := queue[0]
		queue = queue[1:]
		path = append(path, node)
		for _, adj := range g.edges[node] {
			g.inDegree[adj] -= 1
			if g.inDegree[adj] == 0 {
				queue = append(queue, adj)
			}
		}
	}
	return strings.Join(path, "")
}

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

func Solve(n int, names []string) string {
	g := initGraph()
	for i := 1; i < n; i++ {
		prev, curr := names[i-1], names[i]
		diffFound := false
		for j := 0; j < min(len(prev), len(curr)); j++ {
			prevChar, currChar := string(prev[j]), string(curr[j])
			if prevChar != currChar {
				diffFound = true
				add(g, prevChar, currChar)
				break
			}
		}
		if !diffFound && len(prev) > len(curr) {
			return "Impossible"
		}
	}
	path := topologicalSort(g)
	if len(path) < 26 {
		return "Impossible"
	}
	return path
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	names := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%s\n", &names[i])
	}

	fmt.Fprintf(writer, "%s\n", Solve(n, names))
}

package main

import (
	"fmt"
)

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

var order = make(map[uint8]map[uint8]bool)

func main() {
	var count int
	var prev, next string
	fmt.Scan(&count)
	fmt.Scan(&next)
	all := make(map[uint8]bool)
	for i := uint8('a'); i <= uint8('z'); i++ {
		all[i] = true
	}

	for count--; count > 0; count-- {
		prev = next
		fmt.Scan(&next)

		for i := 0; i < min(len(prev), len(next)); i++ {
			if _, ok := order[uint8(next[i])]; !ok {
				order[uint8(next[i])] = make(map[uint8]bool)
			}
			if _, ok := order[uint8(prev[i])]; !ok {
				order[uint8(prev[i])] = make(map[uint8]bool)
			}
			delete(all, uint8(next[i]))
			delete(all, uint8(prev[i]))
			if next[i] != prev[i] {
				order[uint8(next[i])][uint8(prev[i])] = true
				break
			} else {
				if i+1 >= min(len(prev), len(next)) && len(prev) > len(next) {
					fmt.Println("Impossible")
					return
				}
			}
		}
	}

	result := make([]uint8, 0)
	i := uint8('a') - 1

	for {
		i++
		if i > uint8('z') {
			break
		}

		if _, ok := order[i]; !ok {
			continue
		}

		if len(order[i]) == 0 {
			result = append(result, i)

			for j := uint8('a'); j <= uint8('z'); j++ {
				if sub, ok := order[j]; ok {
					delete(sub, i)
				}
			}
			delete(order, i)
			i = uint8('a') - 1
			continue
		}
	}
	if len(order) != 0 {
		fmt.Println("Impossible")
		return
	}

	for _, i := range result {
		fmt.Print(string(i))
	}
	for key, _ := range all {
		fmt.Print(string(key))
	}
	fmt.Println()
}

//https://codeforces.com/problemset/problem/510/C
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC01/ORANGE_L01P03/statement
package main

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

func solve(names []string, n int) string {
	relation := make([][]bool, 26)
	inDegree := make([]int, 26)

	for i := range relation {
		relation[i] = make([]bool, 26)
	}
	for i := 0; i < n-1; i++ {
		minLength := min(len(names[i]), len(names[i+1]))
		for j := 0; j < minLength; j++ {
			if names[i][j] != names[i+1][j] {
				relation[names[i][j]-'a'][names[i+1][j]-'a'] = true
				inDegree[names[i+1][j]-'a']++
				break
			}

			if j == minLength-1 {
				if len(names[i+1]) < len(names[i]) {
					return "Impossible"
				}
			}
		}
	}

	res, isCyclic := kahn(inDegree, relation)

	if isCyclic {
		return "Impossible"
	}

	return res
}

func min(n1 int, n2 int) int {
	if n1 < n2 {
		return n1
	}

	return n2
}

func kahn(inDegree []int, relation [][]bool) (string, bool) {
	zeroDegree := []byte{}
	res := []byte{}
	for i := range inDegree {
		if inDegree[i] == 0 {
			zeroDegree = append(zeroDegree, byte(i)+'a')

		}
	}

	for len(zeroDegree) > 0 {
		cur := dequeue(&zeroDegree)
		res = append(res, cur)
		for i := range relation[cur-'a'] {
			if relation[cur-'a'][i] == true {
				inDegree[i]--
				if inDegree[i] == 0 {
					zeroDegree = append(zeroDegree, byte(i)+'a')
				}
			}
		}
	}

	for i := range inDegree {
		if inDegree[i] != 0 {
			return "", true
		}
	}

	return string(res), false
}

func dequeue(q *[]byte) byte {
	n := (*q)[0]
	(*q) = (*q)[1:]

	return n
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(r, "%d\n", &n)

	names := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%s\n", &names[i])
	}

	fmt.Fprintf(os.Stdout, "%s\n", solve(names, n))
}

package main

import "fmt"

var depends map[string][]string = make(map[string][]string)
var last string
var visited map[string]bool = make(map[string]bool)
var general string

// aghjlnopefikdmbcqrstuvwxyz

func gen(x string) {
  if _, ok := visited[x]; ok {
    return
  }

  visited[x] = true

  for _, p := range depends[x] {
    if _, ok := visited[p]; !ok {
      gen(p)
    }
  }

  general = general + x
}

func add(name string) {
  var compare int
  for i := 0; i < len(name) && i < len(last); i++ {
    if name[i] != last[i] {
      compare = i
      break
    }
  }

  var a = string(last[compare])
  var b = string(name[compare])

  if _, ok := depends[b]; !ok {
    depends[b] = make([]string, 0)
  }

  depends[b] = append(depends[b], a)

  last = name
}

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

  var name string
  for i := 0; i < n; i++ {
    fmt.Scanf("%s\n", &name)
    add(name)
  }

  for _, i := range "abcdefghijklmnopqrstuvwxyz" {
    gen(string(i))
  }

  fmt.Println(general)
}

package main

import "fmt"

var depends map[string][]string = make(map[string][]string)
var last string
var visited map[string]bool = make(map[string]bool)
var general string
var took map[string]bool = make(map[string]bool)

func gen(x string) bool {
  if _, ok := visited[x]; ok {
    return true
  }

  visited[x] = true
  took[x] = true

  for _, p := range depends[x] {
    if _, ok := took[p]; ok {
      fmt.Println("Impossible")
      return false
    }

    if _, ok := visited[p]; !ok {
      var v = gen(p)
      if !v {
        return false
      }
    }
  }

  delete(took, x)
  general = general + x
  return true
}

func add(name string) {
  var compare int
  for i := 0; i < len(name) && i < len(last); i++ {
    if name[i] != last[i] {
      compare = i
      break
    }
  }

  var a = string(last[compare])
  var b = string(name[compare])

  if a == b {
    return
  }

  if _, ok := depends[b]; !ok {
    depends[b] = make([]string, 0)
  }

  depends[b] = append(depends[b], a)

  last = name
}

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

  var name string
  for i := 0; i < n - 1; i++ {
    fmt.Scanf("%s\n", &name)
    add(name)
  }

  var ok = true
  for _, i := range "abcdefghijklmnopqrstuvwxyz" {
    if !gen(string(i)) {
      ok = false
      break
    }
  }

  if ok {
    fmt.Println(general)
  }
}

package main

import "fmt"

var depends map[string][]string = make(map[string][]string)
var last string
var visited map[string]bool = make(map[string]bool)
var general string
var took map[string]bool = make(map[string]bool)

// aghjlnopefikdmbcqrstuvwxyz

func gen(x string) bool {
  if _, ok := visited[x]; ok {
    return true
  }

  visited[x] = true
  took[x] = true

  for _, p := range depends[x] {
    if v, ok := took[p]; ok && v {
      fmt.Println("Impossible")
      return false
    }

    if _, ok := visited[p]; !ok {
      var v = gen(p)
      if !v {
        return false
      }
    }
  }

  took[x] = false
  general = general + x
  return true
}

func add(name string) {
  var compare int
  for i := 0; i < len(name) && i < len(last); i++ {
    if name[i] != last[i] {
      compare = i
      break
    }
  }

  var a = string(last[compare])
  var b = string(name[compare])

  if _, ok := depends[b]; !ok {
    depends[b] = make([]string, 0)
  }

  depends[b] = append(depends[b], a)

  last = name
}

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

  var name string
  for i := 0; i < n; i++ {
    fmt.Scanf("%s\n", &name)
    add(name)
  }

  var ok = true
  for _, i := range "abcdefghijklmnopqrstuvwxyz" {
    if !gen(string(i)) {
      ok = false
      break
    }
  }

  if ok {
    fmt.Println(general)
  }
}

// Author: sighduck
// Inspiration: https://codeforces.com/contest/510/submission/62109848
// URL: https://codeforces.com/problemset/problem/510/C

package main

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

const alphabet = "abcdefghijklmnopqrstuvwxyz"

type Graph struct {
	edges    map[string][]string
	inDegree map[string]int
}

func initGraph() Graph {
	return Graph{
		edges:    make(map[string][]string),
		inDegree: make(map[string]int),
	}
}

func add(g Graph, start string, end string) {
	g.edges[start] = append(g.edges[start], end)
	g.inDegree[end] += 1
}

func topologicalSort(g Graph) string {
	queue := []string{}
	for _, letter := range alphabet {
		s := string(letter)
		if g.inDegree[s] == 0 {
			queue = append(queue, s)
		}
	}
	path := []string{}
	for len(queue) > 0 {
		node := queue[0]
		queue = queue[1:]
		path = append(path, node)
		for _, adj := range g.edges[node] {
			g.inDegree[adj] -= 1
			if g.inDegree[adj] == 0 {
				queue = append(queue, adj)
			}
		}
	}
	return strings.Join(path, "")
}

func Solve(n int, names []string) string {
	g := initGraph()
	for i := 1; i < n; i++ {
		prev, next := names[i-1], names[i]
		for j := 0; j < len(prev); j++ {
			prevChar, nextChar := string(prev[j]), string(next[j])
			if prevChar == nextChar && len(prev) > len(next) {
				return "Impossible"
			}
			if prevChar != nextChar {
				add(g, prevChar, nextChar)
				break
			}
		}
	}
	path := topologicalSort(g)
	if len(path) < 26 {
		return "Impossible"
	}
	return path
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	names := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%s\n", &names[i])
	}

	fmt.Fprintf(writer, "%s\n", Solve(n, names))
}

package main

import (
	"fmt"
)

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

var order = make(map[uint8]map[uint8]bool)

func main() {
	var count int
	var prev, next string
	fmt.Scan(&count)
	fmt.Scan(&next)
	all := make(map[uint8]bool)
	for i := uint8('a'); i <= uint8('z'); i++ {
		all[i] = true
	}

	for count--; count > 0; count-- {
		prev = next
		fmt.Scan(&next)

		for i := 0; i < min(len(prev), len(next)); i++ {
			if _, ok := order[uint8(next[i])]; !ok {
				order[uint8(next[i])] = make(map[uint8]bool)
			}
			if _, ok := order[uint8(prev[i])]; !ok {
				order[uint8(prev[i])] = make(map[uint8]bool)
			}
			delete(all, uint8(next[i]))
			delete(all, uint8(prev[i]))
			if next[i] != prev[i] {
				order[uint8(next[i])][uint8(prev[i])] = true
				break
			} else {
				if i <= min(len(prev), len(next)) && len(prev) > len(next) {
					fmt.Println("Impossible")
					return
				}
			}
		}
	}

	result := make([]uint8, 0)
	i := uint8('a') - 1

	for {
		i++
		if i > uint8('z') {
			break
		}

		if _, ok := order[i]; !ok {
			continue
		}

		if len(order[i]) == 0 {
			result = append(result, i)

			for j := uint8('a'); j <= uint8('z'); j++ {
				if sub, ok := order[j]; ok {
					delete(sub, i)
				}
			}
			delete(order, i)
			i = uint8('a') - 1
			continue
		}
	}
	if len(order) != 0 {
		fmt.Println("Impossible")
		return
	}

	for _, i := range result {
		fmt.Print(string(i))
	}
	for key, _ := range all {
		fmt.Print(string(key))
	}
	fmt.Println()
}

package main

import (
	"fmt"
)

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

var order = make(map[uint8]map[uint8]bool)

func main() {
	var count int
	var prev, next string
	fmt.Scan(&count)
	fmt.Scan(&next)
	all := make(map[uint8]bool)
	for i := uint8('a'); i <= uint8('z'); i++ {
		all[i] = true
	}

	for count--; count > 0; count-- {
		prev = next
		fmt.Scan(&next)

		for i := 0; i < min(len(prev), len(next)); i++ {
			if _, ok := order[uint8(next[i])]; !ok {
				order[uint8(next[i])] = make(map[uint8]bool)
			}
			if _, ok := order[uint8(prev[i])]; !ok {
				order[uint8(prev[i])] = make(map[uint8]bool)
			}
			delete(all, uint8(next[i]))
			delete(all, uint8(prev[i]))
			if next[i] != prev[i] {
				order[uint8(next[i])][uint8(prev[i])] = true
				break
			} else {
				if i <= min(len(prev), len(next)) && len(prev) > len(next) {
					fmt.Println(prev, next)
					return
				}
			}
		}
	}

	result := make([]uint8, 0)
	i := uint8('a') - 1

	for {
		i++
		if i > uint8('z') {
			break
		}

		if _, ok := order[i]; !ok {
			continue
		}

		if len(order[i]) == 0 {
			result = append(result, i)

			for j := uint8('a'); j <= uint8('z'); j++ {
				if sub, ok := order[j]; ok {
					delete(sub, i)
				}
			}
			delete(order, i)
			i = uint8('a') - 1
			continue
		}
	}
	if len(order) != 0 {
		fmt.Println("Impossible")
		return
	}

	for _, i := range result {
		fmt.Print(string(i))
	}
	for key, _ := range all {
		fmt.Print(string(key))
	}
	fmt.Println()
}

package main

import (
	"fmt"
)

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

var order = make(map[uint8]map[uint8]bool)

func main() {
	var count int
	var prev, next string
	fmt.Scan(&count)
	fmt.Scan(&next)
	all := make(map[uint8]bool)
	for i := uint8('a'); i <= uint8('z'); i++ {
		all[i] = true
	}

	for count--; count > 0; count-- {
		prev = next
		fmt.Scan(&next)

		for i := 0; i < min(len(prev), len(next)); i++ {
			if _, ok := order[uint8(next[i])]; !ok {
				order[uint8(next[i])] = make(map[uint8]bool)
			}
			if _, ok := order[uint8(prev[i])]; !ok {
				order[uint8(prev[i])] = make(map[uint8]bool)
			}
			delete(all, uint8(next[i]))
			delete(all, uint8(prev[i]))
			if next[i] != prev[i] {
				order[uint8(next[i])][uint8(prev[i])] = true
				break
			}
		}
	}

	result := make([]uint8, 0)
	i := uint8('a') - 1

	for {
		i++
		if i > uint8('z') {
			break
		}

		if _, ok := order[i]; !ok {
			continue
		}

		if len(order[i]) == 0 {
			result = append(result, i)

			for j := uint8('a'); j <= uint8('z'); j++ {
				if sub, ok := order[j]; ok {
					delete(sub, i)
				}
			}
			delete(order, i)
			i = uint8('a') - 1
			continue
		}
	}
	if len(order) != 0 {
		fmt.Println("Impossible")
		return
	}

	for _, i := range result {
		fmt.Print(string(i))
	}
	for key, _ := range all {
		fmt.Print(string(key))
	}
	fmt.Println()
}

package main

import (
	"fmt"
)

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

var order = make(map[uint8]map[uint8]bool)

func main() {
	var count int
	var prev, next string
	fmt.Scan(&count)
	fmt.Scan(&next)
	all := make(map[uint8]bool)
	for i := uint8('a'); i <= uint8('z'); i++ {
		all[i] = true
	}

	for count--; count > 0; count-- {
		prev = next
		fmt.Scan(&next)

		for i := 0; i < min(len(prev), len(next)); i++ {
			if _, ok := order[uint8(next[i])]; !ok {
				order[uint8(next[i])] = make(map[uint8]bool)
			}
			if _, ok := order[uint8(prev[i])]; !ok {
				order[uint8(prev[i])] = make(map[uint8]bool)
			}
			delete(all, uint8(next[i]))
			delete(all, uint8(prev[i]))
			if next[i] != prev[i] {
				order[uint8(next[i])][uint8(prev[i])] = true
				break
			} else {
				if i >= min(len(prev), len(next)) && len(prev) > len(next) {
					fmt.Println("Impossible")
					return
				}
			}
		}
	}

	result := make([]uint8, 0)
	i := uint8('a') - 1

	for {
		i++
		if i > uint8('z') {
			break
		}

		if _, ok := order[i]; !ok {
			continue
		}

		if len(order[i]) == 0 {
			result = append(result, i)

			for j := uint8('a'); j <= uint8('z'); j++ {
				if sub, ok := order[j]; ok {
					delete(sub, i)
				}
			}
			delete(order, i)
			i = uint8('a') - 1
			continue
		}
	}
	if len(order) != 0 {
		fmt.Println("Impossible")
		return
	}

	for _, i := range result {
		fmt.Print(string(i))
	}
	for key, _ := range all {
		fmt.Print(string(key))
	}
	fmt.Println()
}


As the name of the task implies, you are asked to do some work with segments and trees.Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.You are given $$$n$$$ segments $$$[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$$$, $$$l_i < r_i$$$ for every $$$i$$$. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.Let's generate a graph with $$$n$$$ vertices from these segments. Vertices $$$v$$$ and $$$u$$$ are connected by an edge if and only if segments $$$[l_v, r_v]$$$ and $$$[l_u, r_u]$$$ intersect and neither of it lies fully inside the other one.For example, pairs $$$([1, 3], [2, 4])$$$ and $$$([5, 10], [3, 7])$$$ will induce the edges but pairs $$$([1, 2], [3, 4])$$$ and $$$([5, 7], [3, 10])$$$ will not.Determine if the resulting graph is a tree or not.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of segments. The $$$i$$$-th of the next $$$n$$$ lines contain the description of the $$$i$$$-th segment — two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$). It is guaranteed that all segments borders are pairwise distinct.

Print "YES" if the resulting graph is a tree and "NO" otherwise.

NoteThe graph corresponding to the first example:The graph corresponding to the second example:The graph corresponding to the third example:

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	des := make([]int, 2*(n+1))
	l, r := 0, 0
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &l, &r)
		des[l] = i + 1
		des[r] = -(i + 1)
	}
	edge := 0
	edges := make([][]int, n+1)
	pos := make([]int, n+1)
	stack := make([]int, n)
	fail := false
	//fmt.Println("debug", des)
	for i := 1; i <= 2*n; i++ {
		if fail {
			break
		}
		if des[i] > 0 {
			pos[des[i]] = len(stack)
			stack = append(stack, des[i])
		} else if des[i] < 0 {
			id := -des[i]
			for i := pos[id]; i < len(stack)-1; i++ {
				pos[stack[i+1]]--
				stack[i], stack[i+1] = stack[i+1], stack[i]
				edges[stack[i]] = append(edges[stack[i]], stack[i+1])
				edges[stack[i+1]] = append(edges[stack[i+1]], stack[i])
				edge++
				if edge >= n {
					fail = true
					break
				}
			}
			stack = stack[:len(stack)-1]
		}
	}
	//fmt.Println(edges, edge)
	if edge != n-1 {
		fmt.Fprintf(out, "NO\n")
	} else {
		queue := make([]int, 0)
		queue = append(queue, 1)
		found := make([]bool, n+1)
		found[1] = true
		foundNum := 1
		for len(queue) > 0 {
			cur := queue[0]
			queue = queue[1:]
			for i := 0; i < len(edges[cur]); i++ {
				if !found[edges[cur][i]] {
					queue = append(queue, edges[cur][i])
					found[edges[cur][i]] = true
					foundNum++
				}
			}
		}
		if foundNum == n {
			fmt.Fprintf(out, "YES\n")
		} else {
			fmt.Fprintf(out, "NO\n")
		}
	}
	return
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1278D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, l, r, c int
	Fscan(in, &n)
	type event struct{ p, d, i int }
	es := make([]event, 0, 2*n)
	for i := 0; i < n; i++ {
		Fscan(in, &l, &r)
		es = append(es, event{l, 1, i}, event{r, 0, i})
	}
	sort.Slice(es, func(i, j int) bool { return es[i].p < es[j].p })

	g := make([][]int, n)
	s := []event{}
	for _, e := range es {
		if e.d > 0 {
			s = append(s, e)
		} else {
			for i := len(s) - 1; ; i-- {
				e2 := s[i]
				if e2.i == e.i {
					s = append(s[:i], s[i+1:]...)
					break
				}
				if c >= n {
					break
				}
				c++
				g[e.i] = append(g[e.i], e2.i)
				g[e2.i] = append(g[e2.i], e.i)
			}
		}
	}
	if c == n-1 {
		c++
		vis := make([]bool, n)
		var f func(int)
		f = func(v int) {
			vis[v] = true
			c--
			for _, w := range g[v] {
				if !vis[w] {
					f(w)
				}
			}
			return
		}
		f(0)
		if c == 0 {
			Fprint(out, "YES")
			return
		}
	}
	Fprint(out, "NO")
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1278D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, l, r, c int
	Fscan(in, &n)
	type event struct{ p, d, i int }
	es := make([]event, 0, 2*n)
	for i := 0; i < n; i++ {
		Fscan(in, &l, &r)
		es = append(es, event{l, 1, i}, event{r, 0, i})
	}
	sort.Slice(es, func(i, j int) bool { return es[i].p < es[j].p })

	g := make([][]int, n)
	s := []event{}
o:
	for _, e := range es {
		if e.d > 0 {
			s = append(s, e)
		} else {
			for i := len(s) - 1; ; i-- {
				e2 := s[i]
				if e2.i == e.i {
					s = append(s[:i], s[i+1:]...)
					break
				}
				if c++; c >= n {
					break o
				}
				g[e.i] = append(g[e.i], e2.i)
				g[e2.i] = append(g[e2.i], e.i)
			}
		}
	}
	if c == n-1 {
		c++
		vis := make([]bool, n)
		var f func(int)
		f = func(v int) {
			vis[v] = true
			c--
			for _, w := range g[v] {
				if !vis[w] {
					f(w)
				}
			}
			return
		}
		f(0)
		if c == 0 {
			Fprint(out, "YES")
			return
		}
	}
	Fprint(out, "NO")
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1278D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, c int
	Fscan(in, &n)
	type pair struct{ l, r int }
	ps := make([]pair, n)
	for i := range ps {
		Fscan(in, &ps[i].l, &ps[i].r)
	}
	sort.Slice(ps, func(i, j int) bool { return ps[i].r < ps[j].r })

	m := 2 * n
	tree := make([]int, m+1)
	add := func(i int) {
		for ; i <= m; i += i & -i {
			tree[i]++
		}
	}
	sum := func(i int) (res int) {
		for ; i > 0; i &= i - 1 {
			res += tree[i]
		}
		return
	}
	for i, p := range ps {
		j := sort.Search(i, func(j int) bool { return ps[j].r > p.l })
		c += sum(p.l) - j
		if c >= n {
			break
		}
		add(p.l)
	}
	if c == n-1 {
		Fprint(out, "YES")
	} else {
		Fprint(out, "NO")
	}
}

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


Inna loves sweets very much. She has n closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to n, from left to right.As the boxes are closed, Inna doesn't know which boxes contain candies and which boxes contain nothing. Inna chose number k and asked w questions to Dima to find that out. Each question is characterised by two integers li, ri (1 ≤ li ≤ ri ≤ n; r - l + 1 is divisible by k), the i-th question is: "Dima, is that true that among the boxes with numbers from li to ri, inclusive, the candies lie only in boxes with numbers li + k - 1, li + 2k - 1, li + 3k - 1, ..., ri?"Dima hates to say "no" to Inna. That's why he wonders, what number of actions he will have to make for each question to make the answer to the question positive. In one action, Dima can either secretly take the candy from any box or put a candy to any box (Dima has infinitely many candies). Help Dima count the number of actions for each Inna's question.Please note that Dima doesn't change the array during Inna's questions. That's why when you calculate the number of operations for the current question, please assume that the sequence of boxes didn't change.

The first line of the input contains three integers n, k and w (1 ≤ k ≤ min(n, 10), 1 ≤ n, w ≤ 105). The second line contains n characters. If the i-th box contains a candy, the i-th character of the line equals 1, otherwise it equals 0. Each of the following w lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th question. It is guaranteed that ri - li + 1 is divisible by k.

For each question, print a single number on a single line — the minimum number of operations Dima needs to make the answer to the question positive.

NoteFor the first question, you need to take a candy from the first box to make the answer positive. So the answer is 1.For the second question, you need to take a candy from the first box, take a candy from the fifth box and put a candy to the sixth box. The answer is 3.For the third question, you need to take a candy from the fifth box and put it to the sixth box. The answer is 2.

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n, k, w int
	fmt.Fscanf(reader, "%d %d %d\n", &n, &k, &w)
	sum := make([]int, n+1)
	kSum := make([]int, n+1)
	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	for i := 1; i <= n; i++ {
		kPrev := i - k
		if kPrev < 0 {
			kPrev = 0
		}
		if s[i-1] == '1' {
			sum[i] = sum[i-1] + 1
			kSum[i] = kSum[kPrev] + 1
		} else {
			sum[i] = sum[i-1]
			kSum[i] = kSum[kPrev]
		}
	}
	for i := 0; i < w; i++ {
		var l, r int
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		kCandy := kSum[r] - kSum[l-1]
		allCandy := sum[r] - sum[l-1]
		fmt.Printf("%d\n", allCandy-kCandy+(r-l+1)/k-kCandy)
	}
}