Extended Introduction to Computer Science CS1001.py Lecture 27: Starting to Recap

Σχετικά έγγραφα
EE512: Error Control Coding

2 Composition. Invertible Mappings

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 19/5/2007

TMA4115 Matematikk 3

3.4 SUM AND DIFFERENCE FORMULAS. NOTE: cos(α+β) cos α + cos β cos(α-β) cos α -cos β

Phys460.nb Solution for the t-dependent Schrodinger s equation How did we find the solution? (not required)

Instruction Execution Times

Models for Probabilistic Programs with an Adversary

Section 8.3 Trigonometric Equations

Finite Field Problems: Solutions

Other Test Constructions: Likelihood Ratio & Bayes Tests

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 6/5/2006

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 24/3/2007

Homework 3 Solutions

The Simply Typed Lambda Calculus

Nowhere-zero flows Let be a digraph, Abelian group. A Γ-circulation in is a mapping : such that, where, and : tail in X, head in

SCHOOL OF MATHEMATICAL SCIENCES G11LMA Linear Mathematics Examination Solutions

Lecture 2: Dirac notation and a review of linear algebra Read Sakurai chapter 1, Baym chatper 3

derivation of the Laplacian from rectangular to spherical coordinates

Lecture 2. Soundness and completeness of propositional logic

תורת הגרפים - סימונים

Concrete Mathematics Exercises from 30 September 2016

Statistical Inference I Locally most powerful tests

Fourier Series. MATH 211, Calculus II. J. Robert Buchanan. Spring Department of Mathematics

Physical DB Design. B-Trees Index files can become quite large for large main files Indices on index files are possible.

Section 7.6 Double and Half Angle Formulas

Overview. Transition Semantics. Configurations and the transition relation. Executions and computation

4.6 Autoregressive Moving Average Model ARMA(1,1)

HOMEWORK 4 = G. In order to plot the stress versus the stretch we define a normalized stretch:

Approximation of distance between locations on earth given by latitude and longitude

Dynamic types, Lambda calculus machines Section and Practice Problems Apr 21 22, 2016

פתרון תרגיל מרחבים וקטורים. x = s t ולכן. ur uur נסמן, ur uur לכן U הוא. ur uur. ur uur

Partial Differential Equations in Biology The boundary element method. March 26, 2013

Πρόβλημα 1: Αναζήτηση Ελάχιστης/Μέγιστης Τιμής

Right Rear Door. Let's now finish the door hinge saga with the right rear door

CHAPTER 25 SOLVING EQUATIONS BY ITERATIVE METHODS

ST5224: Advanced Statistical Theory II

the total number of electrons passing through the lamp.

ΕΛΛΗΝΙΚΗ ΔΗΜΟΚΡΑΤΙΑ ΠΑΝΕΠΙΣΤΗΜΙΟ ΚΡΗΤΗΣ. Ψηφιακή Οικονομία. Διάλεξη 7η: Consumer Behavior Mαρίνα Μπιτσάκη Τμήμα Επιστήμης Υπολογιστών

Matrices and Determinants

Assalamu `alaikum wr. wb.

Fractional Colorings and Zykov Products of graphs

PARTIAL NOTES for 6.1 Trigonometric Identities

Section 9.2 Polar Equations and Graphs

Jesse Maassen and Mark Lundstrom Purdue University November 25, 2013

Ordinal Arithmetic: Addition, Multiplication, Exponentiation and Limit

9.09. # 1. Area inside the oval limaçon r = cos θ. To graph, start with θ = 0 so r = 6. Compute dr

The challenges of non-stable predicates

Areas and Lengths in Polar Coordinates

פתרון תרגיל 5 מבוא ללוגיקה ותורת הקבוצות, סתיו תשע"ד

Numerical Analysis FMN011

Abstract Storage Devices

Econ 2110: Fall 2008 Suggested Solutions to Problem Set 8 questions or comments to Dan Fetter 1

ΓΡΑΜΜΙΚΟΣ & ΔΙΚΤΥΑΚΟΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ

רשימת בעיות בסיבוכיות

Areas and Lengths in Polar Coordinates

{ : Halts on every input}

C.S. 430 Assignment 6, Sample Solutions

ΕΙΣΑΓΩΓΗ ΣΤΗ ΣΤΑΤΙΣΤΙΚΗ ΑΝΑΛΥΣΗ

Elements of Information Theory

Problem Set 3: Solutions

ΑΛΓΟΡΙΘΜΟΙ Άνοιξη I. ΜΗΛΗΣ

Example Sheet 3 Solutions

Block Ciphers Modes. Ramki Thurimella

[1] P Q. Fig. 3.1

Srednicki Chapter 55

About these lecture notes. Simply Typed λ-calculus. Types

Solutions to Exercise Sheet 5

חורף תש''ע פתרון בחינה סופית מועד א'

ΠΑΝΕΠΙΣΤΗΜΙΟ ΚΥΠΡΟΥ - ΤΜΗΜΑ ΠΛΗΡΟΦΟΡΙΚΗΣ ΕΠΛ 133: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΕΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ ΕΡΓΑΣΤΗΡΙΟ 3 Javadoc Tutorial

Μηχανική Μάθηση Hypothesis Testing

( ) 2 and compare to M.

ES440/ES911: CFD. Chapter 5. Solution of Linear Equation Systems

ΚΥΠΡΙΑΚΟΣ ΣΥΝΔΕΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY 21 ος ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ Δεύτερος Γύρος - 30 Μαρτίου 2011

Αλγόριθμοι και πολυπλοκότητα NP-Completeness (2)

Durbin-Levinson recursive method

Every set of first-order formulas is equivalent to an independent set

Démographie spatiale/spatial Demography

Advanced Subsidiary Unit 1: Understanding and Written Response

department listing department name αχχουντσ ϕανε βαλικτ δδσϕηασδδη σδηφγ ασκϕηλκ τεχηνιχαλ αλαν ϕουν διξ τεχηνιχαλ ϕοην µαριανι

CRASH COURSE IN PRECALCULUS

Solutions to the Schrodinger equation atomic orbitals. Ψ 1 s Ψ 2 s Ψ 2 px Ψ 2 py Ψ 2 pz

Math221: HW# 1 solutions

ω ω ω ω ω ω+2 ω ω+2 + ω ω ω ω+2 + ω ω+1 ω ω+2 2 ω ω ω ω ω ω ω ω+1 ω ω2 ω ω2 + ω ω ω2 + ω ω ω ω2 + ω ω+1 ω ω2 + ω ω+1 + ω ω ω ω2 + ω

F-TF Sum and Difference angle

forms This gives Remark 1. How to remember the above formulas: Substituting these into the equation we obtain with

Main source: "Discrete-time systems and computer control" by Α. ΣΚΟΔΡΑΣ ΨΗΦΙΑΚΟΣ ΕΛΕΓΧΟΣ ΔΙΑΛΕΞΗ 4 ΔΙΑΦΑΝΕΙΑ 1

Homework 8 Model Solution Section

Bounding Nonsplitting Enumeration Degrees

Συστήματα Διαχείρισης Βάσεων Δεδομένων

b. Use the parametrization from (a) to compute the area of S a as S a ds. Be sure to substitute for ds!

Code Breaker. TEACHER s NOTES

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 11/3/2006

Πανεπιστήμιο Πειραιώς Τμήμα Πληροφορικής Πρόγραμμα Μεταπτυχιακών Σπουδών «Πληροφορική»

ANSWERSHEET (TOPIC = DIFFERENTIAL CALCULUS) COLLECTION #2. h 0 h h 0 h h 0 ( ) g k = g 0 + g 1 + g g 2009 =?

UNIVERSITY OF CALIFORNIA. EECS 150 Fall ) You are implementing an 4:1 Multiplexer that has the following specifications:

[ ] Observability, Controllability תרגול 6. ( t) t t קונטרולבילית H למימדים!!) והאובז' דוגמא: x. נשתמש בעובדה ש ) SS rank( S) = rank( עבור מטריצה m

מתמטיקה בדידה תרגול מס' 13

CHAPTER 12: PERIMETER, AREA, CIRCUMFERENCE, AND 12.1 INTRODUCTION TO GEOMETRIC 12.2 PERIMETER: SQUARES, RECTANGLES,

Notes on the Open Economy

Transcript:

Extended Introduction to Computer Science CS1001.py Lecture 27: Starting to Recap Instructors: Benny Chor, Amir Rubinstein Teaching Assistants: Michal Kleinbort, Yael Baran School of Computer Science Tel-Aviv University Spring Semester, 2013-14 http://tau-cs1001-py.wikidot.com

Lecture 27: Plan Cycles in Linked Lists An old Debt A high level view of algorithm, computational problems, and computational complexity. - Algorithmic approaches - A crash intro to the P vs. NP problem - Map coloring 2

Linked Lists An old debt Reminder: An alternative to using a contiguous block of memory, is to specify, for each item, the memory location of the next item in the list. We can represent this graphically using a boxes-andpointers diagram: 1 2 3 4 3

Linked Lists Representation (reminder) We introduce two classes. One for each node in the list, and another one to represent a list. The class Node is very simple, just holding two fields, as illustrated in the diagram. class Node (): def init (self, val): self.value = val self.next = None def repr (self): return str(self.value) # return "[" + str(self.value) + "," + str(id(self.next))+ "]" 4

Linked List class (reminder) class Linked_list (): def init (self): self.next = None # using same field name as in Node def repr (self): out = "" p= self.next while (p!= None ): out += str(p) + " p=p. next return out More methods will be presented in the next slides 5

Perils of Linked Lists With linked lists, we are in charge of memory management, and we may introduce cycles: >>> L = Linked_list() >>> L.next = L >>> L Can we check if a given list includes a cycle? 6 Here we assume a cycle may only occur due to the next pointer pointing to an element that appears closer to the head of the structure. But cycles may occur also due to the content field

Detecting Cycles: First Variant def detect_cycle1 (lst): dict ={ } p= lst while True : if (p == None ): return False if (p in dict ): return True dict [p] = 1 p = p.next Note that we are adding the whole list element ( box") to the dictionary, and not just its contents. Can we do it more efficiently? In the worst case we may have to traverse the whole list to detect a cycle, so O(n) time in the worst case is inherent. But can we detect cycles using just O(1) additional memory? 7

8 Detecting cycles: The Tortoise and the Hare Algorithm def detect_cycle2 ( lst ): # The hare moves twice as quickly as the tortoise # Eventually they will both be inside the cycle # and the distance between them will decrease by 1 every # time until they meet. slow = fast = lst while True : if ( slow == None or fast == None ): return if ( fast.next == None ): return slow = slow.next fast = fast.next.next if ( ): return True

9 Detecting cycles: The Tortoise and the Hare Algorithm def detect_cycle2 ( lst ): # The hare moves twice as quickly as the tortoise # Eventually they will both be inside the cycle # and the distance between them will decrease by 1 every # time until they meet. slow = fast = lst while True : if ( slow == None or fast == None ): return False if ( fast.next == None ): return False slow = slow.next fast = fast.next.next if ( slow is fast ): return True The same idea is used in Pollard's algorithm for factoring integers. If interested, take Benny's Intro to modern cryptography in 2 years

Testing the cycle detection algorithms The python file contains a function that converts a string to a linked list, and a function that introduces a cycle in a list. >>> lst = string_to_linked_list("abcde") >>> lst a b c d e >>> detect_cycle1(lst) False >>> create_cycle(lst,2,4) >>> detect_cycle1(lst) True >>> detect_cycle2(lst) True 10

Perils of Regular" Python Lists Even with non-linked lists, mutations may introduce cycles. In this example, either append or assign do the trick. >>> lst =["a","b","c","d","e"] >>> lst.append(lst) >>> lst ['a', 'b', 'c', 'd', 'e', [...]] >>> lst = ["a","b","c","d","e"] >>> lst[3] = lst >>> lst ['a', 'b', 'c', [...], 'e'] >>> lst[1] = lst >>> lst ['a', [...], 'c', [...], 'e'] 11 We see that Python recognizes such cyclical lists and [...] is printed to indicate the fact.

Computational Problems and Algorithms Two central notions in most CS courses What is a computational problem? A mapping input output What is an algorithm? A solution to a computational problem A series of operations that transforms input to output. What is an operation? Context dependent Levels of resolution: electron level bit level integer level (add, mult, read, write, compare, ) data structure level (list sort, matrix mult, tree insert) button click in a GUI 12

Algorithms In what ways can one describe an algorithm? Code (formal, in some programming language) Pseudo-code: less formal, but avoids the technical details Natural language (Hebrew, Arabic, Russian, Swahili, ) Flow diagram Animation Video Implementation of an algorithm A concrete mechanism capable of executing the algorithm (e.g. code) Execution of an algorithm Specific machine(s) at a specific time 13

Algorithmic Approaches Throughout the course, you have been exposed to several algorithmic approaches. When facing some computational problem, one should take into consideration these approaches, each with its pros and cons. Or invent a new approach 14

Iterative Algorithms Algorithms are not limited to a linear sequence of operations they usually include control structures. A basic control structure is the loop (an even more basic one is the conditional if). In low level languages (assembly), a loop is implemented with a goto statement. Most high-level programming languages include while and for loops. In Python, for loops are somewhat safer, as they are normally used to iterate over finite collections. This is not the case in all languages 15

Complexity A important measure for an algorithm's efficiency Time complexity number of operations / concrete time measurement as a function of the input size Space complexity maximal number of memory cells allocated simultaneously at any specific step of the algorithm as a function of input size Recall the key difference between time and space: time cannot be reused. c g(n) The O( ) notation a convenient formalization of complexity asymptotic correlates to "rate of growth" 16 rather than absolute number of operations hides multiplicative constants and negligible additives n 0 t(n) = O(g(n)) t(n)

Complexity of Iterative Algorithms Basic iterative patterns (c is some constant independent of n): O(n) 1. i = 1 2. while i < n: 3. i = i +1 1. i = 1 2. while i < n: 3. i = i + c 1. i = n 2. while i > 1: 3. i = i - c (c >0) O(logn) 1. i = 1 2. while i < n: 3. i = i *2 1. i = 1 2. while i < n: 3. i = i *c 1. i = n 2. while i > 1: 3. i = i / c (c >1) O(???) 1. i = 2 2. while i < n: 3. i = i * i 1. i = 2 2. while i < n: 3. i = i**c 1. i = n 2. while i > 2: 3. i = i**1/c (c >1) Things get more complicated when we have nested loops that are dependent, as we have seen in many occasions throughout the course. 17

Worst / Best Case Complexity In many cases, for the same size of input, the content of the input itself affects the complexity. Examples we have seen? Examples in which this is not the case? Note that this statement is completely illogical: "The best time complexity is when n is very small " Often the average complexity is more informative (e.g. when the worst case is rather rare). However analyzing it is usually more complicated, and requires some knowledge on the distribution of inputs. T( I) Assuming distribution is uniform: T ( n) = average I Input( n) Input( n) 18 examples from our course? - hash operation are O(1) on average (not including comparing/hashing elements) - Quicksort runs on average in O(nlogn) (also best case)

Recursive Algorithms Divide Conquer Join Solve smaller instances of the problem and join them Tips: 1. First define the recursion step: think about only 1 level of the recursion. Then adjust the appropriate base conditions 2. If subproblems repeat, consider memoization to speedup solution Recursive algorithms seen in our course: Lectures: - Fibonacci, n!, binary search (also seen iterative), Quicksort, Mergesort, Hanoi, 8 queens, Recitations: - Binom, the "change" problem, maximum (several versions), HW: - tree stuff (heavypath, mirror), munch (ahhm, chomp), 19

Recursion Trees A useful tool for understanding and analyzing recursion. Recall the Fibonacci recursion tree analysis: O(n/2) O(n) Each node requires O(1) time. = c(1+2+...+2 n-1 ) = c(2 n -1) = O(2 n ) 20 = c(1+2+...+2 (n/2)-1 ) = c(2 n/2-1) = O(2 n/2 ) = O( 2 n )

Recurrence Relations Another, more compact and formal description of recursive processes is recurrence relations. Recall the formula for Quicksort's best case t(n) = 2t(n/2) + O(n) This allows easy categorization of the recursive "pattern": how many recursive calls? of what size each? how much time beyond recursion (for the divide and join stages) 21

Recursive Formulae Summary דוגמא פעולות מעבר לרקורסיה קריאות רקורסיביות נוסחת נסיגה סיבוכיות O(N) T(N)=1+T(N-1) N-1 1,max1 עצרת O(log N) T(N)=1+T(N/2) N/2 חיפוש בינרי 1 O(N 2 ) T(N)=N+ T(N-1) N-1 N Quicksort (worst case) max11 O(N log N) T(N)=N+2T(N/2) N/2,N/2 N Mergesort Quicksort (best case) max22 O(N) T(N)=N+T(N/2) N/2 N חיפוש slicing בינארי עם O(N) T(N)=1+2T(N/2) N/2,N/2 1 max2 O(2 N ) T(N)=1+2T(N-1) N-1, N-1 1 האנוי φ = 1+ 5 2 O(φ N ) T(N)=1+T(N-1)+T(N-2) N-1, N-2 1 פיבונאצ'י 22

Randomized Algorithms Apply a random choice at some stage (as opposed to deterministic algorithms). Also termed probabilistic / coin flipping algorithms Randomness in this course? - Probabilistic primality testing (with Fermat's little theorem) - Diffie-Hellman protocol for generating a secret shared key over a public communication network - Quicksort (with random pivot selection) - Karp Rabin - Π approximation What is randomness good for? Running time improvement (e.g. primality testing) Crypto secrecy (e.g. DH) Defense against evil opponent / bad luck (e.g. QS, KR) Sampling (e.g. Π) 23

Greedy Algorithms Do what's best now! Do not look at the larger "picture" The simple version of Ziv-Lempel compression that we have learned is greedy. HW7: is this justified in terms of compression efficiency? Huffman tree construction is also greedy. Greediness does not necessarily pay off (computationally speaking) 24 image from Wikipedia

"Brute Force" Algorithms Brute force, or exhaustive algorithms, simply "try out" all possible solutions. When the number of possible solutions is exponential, we do our best to avoid such algorithms. A short detour: HW6's puzzle problem 25

HW6's puzzle problem Brute force solution: check all m 2! arrangements. a terrible solution for even relatively small m Here is a high level description of a possible solution, assuming the puzzle is unique * : 1. find e.g. top-left corner 2. extend it step by step to complete leftmost column 3. extend each leftish cell to a whole row Not assuming the puzzle is unique, we may consider these approaches: - approach 1: reduce the probability for a wrong stich (but still prob>0, i.e. solution may fail): - By checking more than 1 border before each stich. For example, fill upper row and leftmost column first, then fill up the lines by checking "corners" (see solution sketch in the next slides) - By trying several starting positions - Approach 2: use recursion to examine all possible routes (ensures success) - reminds a bit of the 8 queen problem Can use hash (of borders) for speedup 26 * each piece has a single neighbor from each side, except the borders that lack some of them

HW6's puzzle problem Solution Sketch def find_right_nbr(piece, puzzle): '''find a neighbor on the right of piece''' for i in range(m): for j in range(m): if right_nbr(piece, puzzle[i][j]): return i,j return None def right_nbr(piece1, piece2):... def find_down_nbr(piece, puzzle):... def down_nbr(piece1, piece2):... def find_top_left(puzzle): for i in range(m): for j in range(m): if is_top_left(puzzle,i,j) == True: return i,j def is_top_left(puzzle,i,j):... 27

HW6's puzzle problem Solution Sketch (2) print("solving puzzle...") result = [[0]*m for i in range(m)] print("locating top left corner...") i,j = find_top_left(puzzle) result[0][0] = puzzle[i][j] print("recreating leftmost column...") for i in range(m-1): current = result[i][0] x,y = find_down_nbr(current, puzzle) result[i+1][0] = puzzle[x][y] print("recreating upper row...")... print("recreating rest of puzzle...") for i in range(1,m): for j in range(1,m): x,y =... result[i][j] = puzzle[x][y] 28

Parallel / Distributed Algorithms Parallel if 2 subtasks are independent, solve them at the same time by 2 computers Distributed several computing units interact with each other, but there is no high level "manager". In parallel computing there is a central computing unit that acts as the "manager" of the whole process 29 Dictatorship Democracy

הצצה אל העולם האפל של הסיבוכיות החישוביות NPC NP P 30

קושי של בעיות נבחין בין מצבי הידע הבאים בנוגע לפתרון לבעיות חישוביות: בעיות טריוויאליות - בעיות שאנו פשוט יודעים את הפתרון שלהן, מצריכות רק שליפה מהזיכרון * דוגמה: כמה זה? 1+2.1 בעיות קלות איננו יודעים פתרון, אבל יש לנו דרך יעילה** לחשב פתרון דוגמה: כמה זה 2? 6 17- דוגמה: כמה פעמים מופיע המילה "and" בעמוד הראשי של הניו-יורק טיימס? דוגמה: מיון רשימה.2 בעיות קשות לא ידועה / לא קיימת דרך פתרון יעילה דוגמה: הדפסת כל המעברים בבעיית מגדלי האנוי עבור n דיסקיות (ידועה רק דרך אקספוננציאלית).3 * מבחינת המחשב, אין באמת בעיות טריוויאלית: כל דבר דורש חישוב. אבל אם הפתרון שמור איפשהו והמחשב רק שולף אותו, נתייחס לזה כאל בעייה טריוויאלית. ** דרך יעילה = אלגוריתם בזמן ריצה פולינומי 31

מצבי ידע ולמידה אחת ההגדרות של למידה היא מעבר ממצב ידע אחד למצב ידע גבוה יותר. 7*8 =? בעיות קלות בעיות טריוויאליות בעיות קשות 32

בעיה קשה אך קלה לאימות מחלקת הבעיות הקשות מכילה בעיות שלא ידוע חלק מבעיות אלו מקיימות תכונה מעניינת: להם פתרון פולינומי. (verify) אותו. אם נקבל לידנו פתרון חוקי, יש לנו דרך יעילה* לאמת דוגמה שראינו בקורס? בעיית הלוגריתם הדיסקרטי Log).(Discrete.p, g, g a % p מתוך a לא יודעת איך למצוא את Eve אבל אם תנסה את כל האפשרויות ו"תיפול" על a מתאים, היא תוכל לאמת זאת בקלות (כי Modular exponentiation קלה). מעתה המונח בעיות קשות יתייחס לסוג זה של בעיות, ואילו המונח בעיות קשות באמת יתייחס לאלו שידוע שאין להם פתרון פולינומי. כרגיל, * יעיל = בזמן פולינומי 33

4 דרגות קושי של בעיות בעיות טריוויאליות אנו יודעים את הפתרון שלהן, מצריכות שליפה מהזיכרון.1 בעיות קלות איננו יודעים פתרון, אבל יש לנו דרך פולינומית לחשב פתרון דוגמה: מיון רשימה בעיות קשות איננו יודעים פתרון או דרך יעילה לחשב פתרון, אבל אם נקבל לידנו פתרון חוקי, יש לנו דרך יעילה לאמת אותו דוגמה: לוג דיסקרטי.2.3 בעיות קשות באמת לחישוב פתרון. קיימות רק דרכים בלתי-יעילות (אקספוננציאליות).4 דוגמה: האנוי 34

עוד דוגמה x =? x = 1+2 x 2 + 2x - 7 = 0 x 7 + 2x 4-7x + 4 = 0 בעיה טריוויאלית בעיה קלה בעיה קשה 35

התמודדות חישובית עם בעיות בעיות טריוויאליות אינן מעניינות מבחינה חישובית..1 לבעיות קלות יש אלגוריתמים יעילים, ולכן חישובית אינן צריכות להדאיג. אבל אפשר לנסות לשפר את האלגוריתמים / להוכיח חסם תחתון לבעיה המעיד כי לא ניתן לשפר עוד. דרכים להתמודד עם בעיות (a (b (c (d קשות: אלו היו במוקד הקורס שלנו גם אלו נמצאות בלב מדעי המחשב ניסוי וטעייה, או בשם אחר חיפוש ממצה search) :(exhaustive מעבר שיטתי על כל האפשרויות ובדיקתן אחת אחת קירובים (approximations) פתרון "כמעט" נכון בזמן פולינומי הנחת הנחות שונות המצמצמות את הבעיה לתת-משפחות אותן קל יותר לפתור למידה ומחקר בנסיון להפכן לבעיות קלות או אפילו טריוויאליות..2.3 c דרכים a התמודדות עם בעיות קשות באמת: לעיל עד.4 36

בעיות הכרעה רוב הבעיות שראינו בקורס עד כה ביקשו לחשב תוצאה כלשהי שהיא מספר, מחרוזת או אובייקט אחר כלשהו: x x חיפוש: רשימה ואיבר המיקום של ברשימה, אם קיים a לוג דיסקרטי: p, g, g a % p... נגביל כעת את הדיון לבעיות הכרעה: בעיות שמבקשות תשובה "כן" / "לא" בלבד לשאלה כלשהי. רוב הבעיות שאינן בעיות הכרעה ניתנות לניסוח כבעיות הכרעה:? x האם x חיפוש: רשימה ואיבר ברשימה? a<k האם k לוג דיסקרטי: p, g, g a %p ובנוסף מספר קיים 37

להלן מפה מדינית: דוגמה: צביעת מפות (מתוך האתר "מדעי המחשב ללא מחשב".(http://csu-il.blogspot.com נגדיר צביעה חוקית של מפה: צביעה של כל מדינה בצבע אחד, כך שאין שתי מדינות גובלות באותו צבע. שאלות: 3 4 - - - האם ניתן לצבוע את המפה הזו ב- 2 צבעים? צבעים? צבעים? 2 צבעים 3 צבעים 4 צבעים 5 צבעים יש מפה כן כל מפה לא לא?????? 38

צביעת מפות ייצוג והכללה (Graph) מפה ניתנת לייצוג באמצעות גרף אוסף של קדקדים וקשתות. המדינות בין שתי מדינות שכנות מיפוי מצמתים למספרים,1,2,3 צמתים = קשתות = צביעה = ננסח את השאלות מהשקף הקודם באופן כללי, וכשאלת הכרעה: בהינתן גרף ומספר k, האם ניתן לצבוע את הגרף באמצעות k צבעים בלבד? 39

צביעת גרף 2 צבעים תנאי להיותו של גרף 2 -צביע (2-colorable) גרף ניתן לצביעה ב- 2 צבעים אם"ם אין בו מעגלים באורך איזוגי. גרף כזה מכונה גם גרף דו-צדדי.(Bipartite) 40

- סיבוכיות צביעת גרף ב- 2 צבעים שאלה: מה דרגת הקושי של הבעיה "האם גרף ניתן לצביעה ב- 2 צבעים"?,(n) האלגוריתם עובר על כל צומת ועל כל קשת פעם אחת. אם גודל הקלט הוא מספר הקשתות (m) ומספר הצמתים סיבוכיות של,O(n+m) כלומר ליניארית. ניתן להשיג לכן בדיקה האם גרף הוא 2 -צביע היא בעיה קלה חישובית. 41

גרף מישורי לפני שנחשוף עוד תוצאה מפורסמת, נשים לב לתכונה הבאה: גרף שמייצג מפה מישורית ניתן לשרטוט כאשר אף קשת לא חותכת אף קשת אחרת. גרף כזה נקרא graph).(planar גרף מישורי 42

4 צבעים בגרף מישורי מתי גרף מישורי הוא 4 -צביע (4-colorable)? תמיד!! משפט ארבעת הצבעים: כל גרף מישורי ניתן לצביעה ב- 4 צבעים. בשנת 1852 צעיר בריטי בשם פרנסיס גאתרי ניסח זאת כהשערה. במשך למעלה מ- 120 שנה טובי המתמטיקאים בעולם ניסו להוכיח את השערת ארבעת הצבעים ללא הצלחה. המשפט הוכח בשנת 1976. ההוכחה מראה שניתן לסווג כל דוגמה נגדית אפשרית לאחת מ- אחד מצעדי ההוכחה כולל בחינת סוגים אלו באמצעות מחשב. 1936 סוגי מפות. ההוכחה שנויה במחלוקת מבחינה פילוסופית. מדוע? מה דעתכם? שאלה: לאיזו קטגוריה שייכת הבעיה "האם גרף מישורי ניתן לצביעה ב- 4 צבעים"? תשובה: זוהי בעיה טריוויאלית. אבל: בעיית מציאת צביעה ב- 4 צבעים לגרף מישורי, אם קיימת, איננה כזו. 43

3 צבעים? לא ידוע כיום אלגוריתם יעיל שעונה "כן"/"לא" לשאלה: בהינתן גרף כלשהו, האם ניתן לצבוע אותו ב- 3 צבעים? כלומר הבעיה איננה קלה. האם לדעתכם היא קשה או קשה באמת? במילים אחרות: אם נתון לנו גרף כלשהו, ונתונה צביעה חוקית שלו ב- 3 ניתן לוודא ביעילות שזוהי אכן צביעה חוקית? צבעים האם מסקנה: הבעיה "האם גרף כלשהו ניתן לצביעה ב- 3 צבעים" היא בעיה קשה. למעשה, המסקנה נכונה לכל מספר צבעים 2<k (לא עבור המקרה הפרטי של גרף מישורי, כאמור). 44

? P = NP מחלקת בעיות ההכרעה הקלות מסומנת (Polynomial) P מחלקת בעיות ההכרעה הקשות מסומנת,Non-deterministic polynomial) NP לא נסביר...) NP? מה היחס בין שתי המחלקות הללו? P=NP הסבר ודיון. P השאלה הפתוחה הגדולה של מדעי המחשב (הפרס - מיליון דולר במזומן ותהילת עולם): האם היכולת לזהות ביעילות פתרון חוקי של בעיה מעידה על יכולת לפתור אותה ביעילות? פורמלית: האם?P=NP 45 רוב מדעני המחשב סבורים ש-.P NP אך זה מעולם לא הוכח. יש לכך תימוכין מכיוונים שונים,

בדיקת ראשוניות testing) (Primality הבעיה: בהינתן מספר שלם חיובי N, האם הוא ראשוני? עד לא מזמן ידעו לומר שהבעיה ב-.NP ב- 2002 נתגלה שהבעיה למעשה ב- P. הערה: יש להבדיל בין בדיקת ראשוניות לבין פירוק לגורמים ראשוניים. לבעייה אחרונה לא ידוע אלגוריתם פולינומי כיום. שאלה: האם בעיית הפירוק לגורמים ב-?NP 46

המחלקה NPC NP-Complete הוא קיצור של NPC (בעברית: NP -שלם). לא נסביר את השם הזה... זוהי תת מחלקה של NP הכוללת למעלה מ- 1000 בעיות בעלות התכונה המפתיעה הבאה: 1) אם לאחת מהן יש פתרון פולינומי לכולן יש 2) אם לאחת מהן אין פתרון פולינומי לאף אחת אין ניתן להראות שבמקרה (1,P=NP ואילו במקרה (2 NP P ומכאן העניין הרב שיש במחלקה זו. NPC P=NP=NPC NP? P 47 בעיית צביעה ב- 3 צבעים שייכת ל-.NPC בעיית הלוג הדיסקרטי שייכת ל-,NP ולא ידוע אם היא שייכת גם ל-,NPC או שאולי ל- P.

עוד דוגמה: שבעת הגשרים של Königsberg כיום קלינינגרד ברוסיה Königsberg בעיה שנוסחה ע"י לאונרד 1735 ב- אוילר, נחשבת לפרסום הראשון ב"תורת הגרפים" לימים ענף מרכזי במדעי המחשב 48 האם ניתן להתחיל מנקודה מסוימת בעיר, לאותה נקודה? לעבור בכל הגשרים בדיוק פעם אחת, ולחזור

מידול והפשטה (abstraction) האם ניתן להתחיל מנקודה מסוימת בעיר, ולחזור לאותה נקודה? מה הפרטים החשובים כאן? לעבור בכל הגשרים בדיוק פעם אחת, האם יש בגרף מסלול שעובר בכל קשת בדיוק פעם אחת? 49

מסלול / מעגל אוילר הגדרה: מסלול אוילר בגרף הוא מסלול שעובר בכל קשת בדיוק פעם אחת. אם מסלול אוילר מתחיל ונגמר באותו צומת, הוא ייקרא מעגל אוילר. השאלה שלנו אם כן הפכה להיות: מתי גרף מכיל מסלול / מעגל אוילר? משפט (אוילר, 1736): ** * מכיל "מסלול אוילר" אם כל צמתיו, למעט בדיוק 2, בעלי דרגה גרף קשיר והוא מכיל "מעגל אוילר" אם כל צמתיו בעלי דרגה זוגית. זוגית. 50 גרף קשיר מכל צומת ניתן להגיע לכל צומת * ** דרגה של צומת - כמות הקשתות שנוגעות בצומת

House of Santa האם תוכלו לצייר את הבית מבלי להרים את העיפרון? האם יש בגרף מסלול אוילר? הפשטה מאפשרת לראות דמיון בין בעיות! 51

מסלולי אוילר / המילטון מסלול אוילר :(Euler) מסלול שעובר בכל קשתות הגרף בדיוק פעם אחת. הבעיה "האם גרף קשיר מכיל מסלול אוילר" ניתנת לפתרון בזמן פולינומי: עוברים על הגרף ובודקים כמה צמתים יש עם דרגה איזוגית. אם יש 0 או 2 עונים "כן", אחרת עונים "לא". P. בעיית מסלול אוילר שייכת למחלקה מסלול המילטון :(Hamilton) מסלול שעובר בכל צמתי הגרף בדיוק פעם אחת. למרות הדמיון בין הבעיות, לא ידוע כיום אלגוריתם פולינומי לבעיה זו. שאלה: האם הבעייה או קשה קשה באמת? 52 שאלה: האם ייתכן שהבעיה בכל זאת ב- P?

בעיות קשות עוד יותר? האם יש בעיות קשות יותר מהבעיות ה"קשות באמת"? האם יש בעיות שבכלל לא ניתן לפתור בזמן סופי? בשיעור הבא (והאחרון)... כל הנ"ל יילמד לעומק ובאופן פורמלי הרבה יותר בקורס מודלים חישוביים 53