Пример #1
0
/****************************************************************************
 *  Data files:   http://algs4.cs.princeton.edu/15uf/tinyUF.txt
 *                http://algs4.cs.princeton.edu/15uf/mediumUF.txt
 *                http://algs4.cs.princeton.edu/15uf/largeUF.txt
 *
 *  % ./uf < tinyUF.txt
 *  4 3
 *  3 8
 *  6 5
 *  9 4
 *  2 1
 *  5 0
 *  7 2
 *  6 1
 *  2 components
 *
 ****************************************************************************/
func main() {
	var n int
	stdin := stdin.NewStdin()

	if !stdin.IsEmpty() {
		n, _ = stdin.ReadInt()
	} else {
		panic("No input...")
	}

	// uf := uf.NewQuickFind(n) // initialize n components
	// uf := uf.NewQuickUnion(n) // initialize n components
	// uf := uf.NewWeightedQuickUnion(n) // initialize n components
	uf := uf.NewWeightedQuickUnionWithPathCompression(n) // initialize n components
	var p, q int

	for !stdin.IsEmpty() {
		p, _ = stdin.ReadInt()
		if !stdin.IsEmpty() {
			q, _ = stdin.ReadInt() // read pair to connect
		}

		if uf.Connected(p, q) { // ignore if connected
			continue
		}

		uf.Union(p, q)              // combine components
		fmt.Printf("%d %d\n", p, q) // print connection
	}

	fmt.Printf("%d components\n", uf.Count())
}
Пример #2
0
// This program takes the name of a whitelist file (a sequence of integers) as argument and filters any
// entry that is on the whitelist from standard input, leaving only integers that are not on the whitelist
// on standard output. It uses the binary search algorithm, implemented in the method Rank(),
// to accomplish the task efficiently.
func main() {
	if len(os.Args) <= 1 {
		fmt.Printf("usage: %s tinyW.txt < tinyT.txt\n", filepath.Base(os.Args[0]))
		return
	}

	whitelist, err := in.ReadAllIntsFromFile(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	sort.Ints(whitelist)

	stdin := stdin.NewStdin()
	for !stdin.IsEmpty() {
		// Read key, print if not in whitelist
		key, err := stdin.ReadInt()
		if err != nil {
			log.Fatal(err)
		}

		if bsearch.Rank(key, whitelist) == -1 {
			fmt.Println(key)
		}
	}
}