Você está na página 1de 34

A disciplina Bibliografia Algoritmos: Introdução Exercícios

Introdução
INF 610 - Estruturas de dados e algoritmos

André Gustavo dos Santos

Departamento de Informática
Universidade Federal de Viçosa

INF 610 - 2013/1


A disciplina Bibliografia Algoritmos: Introdução Exercícios

Ementa

1 Estruturas de dados básicas e avançadas


2 Princípios de projeto e análise de algoritmos
3 Paradigmas de projeto de algoritmos
4 NP-Completude
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Programa Analítico
1 Estruturas de dados básicas e avançadas
Listas contíguas e encadeadas
Pilhas e filas
Árvores: árvore binária de pesquisa e árvore-B
Grafos
2 Princípios de projeto e análise de algoritmos
Conceitos de complexidade assintótica
Notação O, Ω e Θ
Indução, somatórios e relação de recorrência
3 Paradigmas de projeto de algoritmos
Paradigma incremental e divisão-e-conquista
Busca exaustiva, backtracking
Programação dinâmica
Algoritmos gulosos
4 NP-Completude
Conceitos e classificação de problemas NP-Completos
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Importância no PPGCC

Importância teórica
O estudo de algoritmos é o core da Ciência da Computação
Importância prática
toolkit de algoritmos conhecidos
framework para projeto e análise de algoritmos para novos
problemas
OBRIGATÓRIA
Pode ser dispensada, mediante prova específica
(nesse caso, não conta crédito)
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Dinâmica e distribuição de pontos

Aula, exercícios, trabalhos, provas, ...


Distribuição de pontos
2 provas de 30 pts ⇒ 60 pts
3 trabalhos de 10 pts ⇒ 30 pts
n listas de exercícios ⇒ 10 pts
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Bibliografia - I

Anany Levitin

Introduction to the Design and


Analysis of Algorithms

Pearson, 3rd Ed., 2011


A disciplina Bibliografia Algoritmos: Introdução Exercícios

Bibliografia - II

Thomas H. Cormen
Ronald L. Rivest
Clifford Stein
Charles E. Leiserson

Algoritmos - Teoria e Prática

Campus, 3a Ed., 2012


A disciplina Bibliografia Algoritmos: Introdução Exercícios

Bibliografia - III

Ellis Horowitz
Sartaj Sahni
Sanguthevar Rajasekaran

Computer Algorithms in C++

Computer Science Press, 1997


A disciplina Bibliografia Algoritmos: Introdução Exercícios

Bibliografia - IV

Nivio Ziviani

Projeto de Algoritmos com Im-


plementações em Pascal e C
Thomson Learning, 2a Ed., 2004
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Bibliografia - IV

Nivio Ziviani

Projeto de Algoritmos com Im-


plementações em Pascal e C
Cengage Learning, 3a Ed., 2010
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Bibliografia - IV

Nivio Ziviani

Projeto de Algoritmos com Im-


plementações em Java e C++
Cengage Learning, 2006
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Bibliografia - V

Udi Manber

Introduction to Algorithms:
a Creative Approach

Addison-Wesley, 1989
A disciplina Bibliografia Algoritmos: Introdução Exercícios

What is an algorithm?

Os slides seguintes são baseados nos slides1 fornecidos no


livro texto da disciplina. Foram apenas reformatados em Latex.

1
A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed.,
Ch. 1 2012.
c Pearson Education, Inc. Upper Saddle River, NJ. All Rights
Reserved.
A disciplina Bibliografia Algoritmos: Introdução Exercícios

What is an algorithm?
An algorithm is a sequence of unambiguous instructions for
solving a problem, i.e., for obtaining a required output for any
legitimate input in a finite amount of time.
A disciplina Bibliografia Algoritmos: Introdução Exercícios

What is an algorithm?

Recipe, process, method, technique, procedure, routine, ...


with following requirements:
Finiteness
terminates after a finite number of steps
Definiteness
rigorously and unambiguously specified
Input
valid inputs are clearly specified
Output
can be proved to produce the correct output given a valid
input
Effectiveness
steps are sufficiently simple and basic
A disciplina Bibliografia Algoritmos: Introdução Exercícios

What is an algorithm?

The nonambiguity requirement cannot be compromised


The range of inputs has to be specified carefully
The same algorithm can be represented in several different
ways
There may exist several algorithms for solving the same
problem
Algorithms for the same problem can be based on very
different ideas and can solve the problem with dramatically
different speeds
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Historical Perspective

Muh.ammad ibn Mūsā al-Khwārizmı̄


(9th century mathematician)

Euclid’s algorithm for finding the greatest common divisor


(3rd century B.C.)
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Euclid’s algorithm to find gcd

GCD problem
Find gcd(m,n), the greatest common divisor of two
nonnegative, not both zero integers m and n

Examples
gcd(60,24) = 12
gcd(60,0) = 60
gcd(0,0) = ?
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Euclid’s algorithm to find gcd

Euclid’s algorithm
Euclid’s algorithm is based on repeated application of equality
gcd(m,n) = gcd(n, m mod n) until the second number becomes
0, which makes the problem trivial.

Example
gcd(60,24) = gcd(24,12) = gcd(12,0) = 12
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Two descriptions of Euclid’s algorithm

Euclid’s algorithm
1 If n = 0, return m and stop; otherwise go to Step 2
2 Divide m by n and assign the value of the remainder to r
3 Assign the value of n to m and the value of r to n. Go to
Step 1.

Euclid’s algorithm
Euclid (int m, int n)
while n 6= 0 do
r ← m mod n
m←n
n←r
return m
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Other methods for computing gcd(m,n)

Consecutive integer checking algorithm


1 Assign the value of min(m,n) to t
2 Divide m by t. If the remainder is 0, go to Step 3;
otherwise, go to Step 4
3 Divide n by t. If the remainder is 0, return t and stop;
otherwise, go to Step 4
4 Decrease t by 1 and go to Step 2
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Other methods for computing gcd(m,n)

Middle-school procedure
1 Find the prime factorization of m
2 Find the prime factorization of n
3 Find all the common prime factors
4 Compute the product of all the common prime factors and
return it as gcd(m,n)

Is this an algorithm?
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Prime factorization
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Sieve of Eratosthenes to find primes (ca. 200 B.C.)


Sieve (int n)
Input: Integer n ≥ 2
Output: List of primes less than or equal to n
for p ← 2 to n do
A[p] ← p √
for p ← 2 to b nc do
if A[p] 6= 0 //p hasn’t been previously eliminated from the list
j ←p∗p
while j ≤ n do
A[j] ← 0 //mark element as eliminated
j ←j +p
//copy the remaining elements of A to array L of the primes
i←0
for p ← 2 to n do
if A[p] 6= 0
L[i] ← A[p]
i ←i +1
return L
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Why study algorithms?

Theoretical importance
the core of computer science
Practical importance
a practitioner’s toolkit of known algorithms
framework for designing and analyzing algorithms for new
problems
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Why study algorithms?

“Algorithmics is more than a branch of computer science. It is


the core of computer science, and, in all fairness, can be said
to be relevant to most of science, business, and technology.” 2

“It has often been said that a person does not really understand
something until after teaching it to someone else. Actually, a
person does not really understand something until after
teaching it to a computer, i.e., expressing it as an algorithm...” 3

2
David Harel, Algorithmics: The Spirit of Computing, 2nd ed. Addison-
Wesley, 1992.
3
Donald E. Knuth, Selected Papers on Computer Science. CSLI
Publications and Cambridge University Press, 1996.
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Two main issues related to algorithms

How to design algorithms


How to analyze algorithm efficiency
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Algorithm design techniques/strategies

Brute force
Divide and conquer
Decrease and conquer
Transform and conquer
Greedy approach
Dynamic programming
Backtracking and Branch and bound
Space and time tradeoffs
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Analysis of algorithms

How good is the algorithm?


time efficiency
space efficiency

Does there exist a better algorithm?


lower bounds
optimality
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Some well-known computational problems

Sorting
Searching
Shortest paths in a graph
Minimum spanning tree
Primality testing
Traveling salesman problem
Knapsack problem
Chess
Towers of Hanoi
Program termination
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Fundamental data structures

list
stack
queue
priority queue
tree
graph
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Exercícios

Exercício #1
Find gcd(31415, 14142) by applying Euclid’s algorithm.
Estimate how many times faster it will be to find
gcd(31415, 14142) by Euclid’s algorithm compared with
the algorithm based on checking consecutive integers from
min(m, n) down to gcd(m, n).

Exercício #2
What does Euclid’s algorithm do for a pair of integers in
which the first is smaller than the second?
What is the maximum number of times this can happen
during the algorithm’s execution on such an input?
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Exercícios

Exercício #3

Design an algorithm for computing b nc for any positive integer
n. Besides assignment and comparison, your algorithm may
only use the four basic arithmetical operations.

Exercício #4
Design an algorithm to find all the common elements in
two sorted lists of numbers. For example, for the lists 2, 5,
5, 5 and 2, 2, 3, 5, 5, 7, the output should be 2, 5, 5.
What is the maximum number of comparisons your
algorithm makes if the lengths of the two given lists are m
and n, respectively?
A disciplina Bibliografia Algoritmos: Introdução Exercícios

Exercícios

Exercício #5
There are n lockers in a hallway, numbered sequentially from 1
to n. Initially, all the locker doors are closed. You make n
passes by the lockers, each time starting with locker #1. On the
i-th pass, i = 1, 2, . . . , n, you toggle the door of every i-th
locker: if the door is closed, you open it; if it is open, you close
it. After the last pass, which locker doors are open and which
are closed? How many of them are open?

Você também pode gostar