A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

Solved Exercises 1. Finding the Peak. Let A= a 1,…,a n be a sequence of n numbers with the following property: there is p in {1,…,n} for which (i) the.

Apresentações semelhantes


Apresentação em tema: "Solved Exercises 1. Finding the Peak. Let A= a 1,…,a n be a sequence of n numbers with the following property: there is p in {1,…,n} for which (i) the."— Transcrição da apresentação:

1

2

3 Solved Exercises 1. Finding the Peak. Let A= a 1,…,a n be a sequence of n numbers with the following property: there is p in {1,…,n} for which (i) the subsequence a 1,..,a p is increasing and (ii) the subsequence a p,…,a n is decreasing. Find p in O( log n) time. Exemplo A = 1 3 5 6 8 6 4 3 2 p = 5

4 Solved Exercises 2. Subcadeia de Soma Máxima Entrada a = (a 1, a 2, …, a N ) um vetor de inteiros Saída: i e j tais que S[i, j ]= a i + a i+1 + … + a j é máximo.  quando todos os valores de a são negativos, então a subsequencia vazia é escolhida e o valor máximo da soma é considerado 0. Exemplo: a = (-2, 11, -4, 13, -5, -2) Solução  i=2 e j=4  s[2,4]= 11 - 4 + 13 = 20

5 Solução “força bruta” Existem O(n 2 ) intervalos Para calcular s[i, j ] gasta-se O(j-i)=O(n) Complexidade de tempo O(n 3 )

6 Solução “força bruta” S max  0 Para i:=1 até n faça Para j:=i ate n faça S  A[i] Para k:=i+1 até j faça S  S+A[k] if S > S max then S max  S

7 Preprocessamento... Calculando s[1,i], para 1≤ i ≤ n, podemos calcular as demais somas em O(1): S[ i, j ]= s[ 1, j ] –s[ 1, i-1 ] O(n 2 ) intervalos => Complexidade de tempo O(n 2 )

8 Preprocessamento... Para i:=0 até n Prefix[i]  0 Para i:=1 até n Prefix[i+1]  Prefix[i] + A[i] S max  0 Para i:=1 até n faça Para j:=i ate n faça if Prefix[j] – Prefix[i-1] > S max then S max  Prefix[j] – Prefix[i-1]

9 ...“dividir-e-conquistar” Quebrar em dois subvetores menores a1a1 a2a2 resposta a esquerda resposta a direita resposta no centro a1a1 a2a2

10 ...“dividir-e-conquistar” Quebrar em dois subvetores menores a1a1 a2a2 T(esq): subsequencia de soma máxima que começa em algum i* menor ou igual a n/2 e termina em n/2 T(dir): subsequencia de soma máxima que começa em n/2 e termina em algum j* maior ou igual a n/2 Melhor resposta no centro igual a s[ i*, j* ] resposta no centro

11 …“dividir-e-conquistar” T(n) = esforço para resolver instancia de tamanho n T(n) = n + 2.T(n/2) T(1) = O(1) T(n) = O(n.lg(n)) + O(n) = O(n.lg(n)) Complexidade de tempo O(n log n)

12 …“ É possível melhorar ?” Programação Dinâmica n Tempo Linear


Carregar ppt "Solved Exercises 1. Finding the Peak. Let A= a 1,…,a n be a sequence of n numbers with the following property: there is p in {1,…,n} for which (i) the."

Apresentações semelhantes


Anúncios Google