You are on page 1of 6

G s k e r o fs G k e

A computer science portal for geeks


Home Arrays Q&A Interview Corner Ask a question Articles Contribute GFacts GATE Algorithms MCQ C Misc Bit Magic C/C++ Puzzles Linked Lists

GeeksQuiz
Login

C++

Books

About us Trees Search

Output

Strings

m g e t n sn eil n e vig w o t fi k c e h co t H w o
Given two line segments (p1, q1) and (p2, q2), find if the given line segments intersect with each other. Before we discuss solution, let us define notion of orientation. Orientation of an ordered triplet of points in the plane can be counterclockwise clockwise colinear The following diagram shows different possible orientations of (a, b, c)

Interview Experiences Advanced Data Structures Dynamic Programming GreedyAlgorithms Backtracking Pattern Searching Divide & Conquer Graph Mathematical Algorithms Recursion Java

Note the word ordered here. Orientation of (a, b, c) may be different from orientation of (c, b, a). How is Orientation useful here? Two segments (p1,q1) and (p2,q2) intersect if and only if one of the following two conditions is verified 1. General Case: - (p1, q1, p2) and (p1, q1, q2) have different orientations and - (p2, q2, p1) and (p2, q2, q1) have different orientations 2. Special Case - (p1, q1, p2), (p1, q1, q2), (p2, q2, p1), and (p2, q2, q1) are all collinear and - the x-projections of (p1, q1) and (p2, q2) intersect - the y-projections of (p1, q1) and (p2, q2) intersect Examples of General Case: GeeksforGeeks
Like 40,945 people like GeeksforGeeks.

F acebook social plugin

sts or P au l p o P
All permutations of a given string Memory Layout of C Programs Understanding extern keyword in C Median of two sorted arrays Tree traversal without recursion and without stack! Structure Member Alignment, Padding and Data Packing Intersection point of two Linked Lists Lowest Common Ancestor in a BST. Check if a binary tree is BST or not Sorted Linked List to Balanced BST

Examples of Special Case:

Following is C++ implementation based on above idea.


// A C++ program to check if two given line segments intersect #include <iostream> using namespace std;

converted by Web2PDFConvert.com

using namespace std; struct Point { int x; int y; }; // Given three colinear // point q lies on line bool onSegment(Point p, { if (q.x <= max(p.x, q.y <= max(p.y, return true; return false; } // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are colinear // 1 --> Clockwise // 2 --> Counterclockwise int orientation(Point p, Point q, Point r) { // See 10th slides from following link for derivation of the formula // http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf int val = (q.y - p.y) * (r.x - q.x) (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // colinear return (val > 0)? 1: 2; // clock or counterclock wise } // The main function that returns true if line segment 'p1q1' // and 'p2q2' intersect. bool doIntersect(Point p1, Point q1, Point p2, Point q2) { // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases } // Driver program to test above functions int main() { struct Point p1 = {1, 1}, q1 = {10, 1}; struct Point p2 = {1, 2}, q2 = {10, 2}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; p1 = {10, 0}, q1 = {0, 10}; p2 = {0, 0}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; p1 = {-5, -5}, q1 = {0, 0}; p2 = {1, 1}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; return 0; }
Follow @Geeksforgeeks 1,911 followers

Nursing School Online


www.chamberlain.edu
points p, q, r, the function checks if segment 'pr' Point q, Point r) r.x) && q.x >= min(p.x, r.x) && r.y) && q.y >= min(p.y, r.y))

Earn Your RN To BSN in 3 Semesters. Online, Affordable & User Friendly!

IIAR Ammonia Pipe Marking Enterprise Web Hardware Cleveland State Univ. Hiring hadoop & ML expert C++ Static Analysis

625

Subscribe

C m o s m t n e R c e
Anirban SahaIs it neccessary to find lsum and rsum and find...
Remove all nodes which dont lie in any path with sum>= k 50 minutes ago

RaghuArule - "Virtual Base class is constructed by...


Multiple Inheritance in C++ 51 minutes ago

Anirban SahaYes i feel the same too .. Is there any...


Remove all nodes which dont lie in any path with sum>= k 1 hour ago

shobhit chaturvedican you share hr id through which u got call...


D E Shaw Interview | Set 3 2 hours ago

Rohit MitraIt can be written as (m + n 2) C (n - 1)


Count all possible paths from top left to bottom right of a mXn matrix 2 hours ago

Output:
No Yes No

Mohammad Abuomar@Doom this won't work since you're only...


The Celebrity Problem 4 hours ago

Sources: http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest

Parallel Lines Graph Java The Intersection

converted by Web2PDFConvert.com

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Like 34 Tweet 3

Java C++ Format Java Parallel C++ Format Java Java To The Intersection

Related Questions:
How to compare two arrays in Java? DELL Interview | Set 1 (On-Campus) Oracle Interview | Set 4 (On-Campus) Print all possible paths from top left to bottom right of a mXn matrix D E Shaw Interview | Set 3 Generate all unique partitions of an integer Microsoft Interview | Set 24 Oracle Interview | Set 3 (On-Campus)
Writing code in comment? Please use ideone.com and share the link here.

@geeksforgeeks, Some rights reserved

Contact Us!

Powered by WordPress & MooTools, customized by geeksforgeeks team

converted by Web2PDFConvert.com

G s k e r o fs G k e
A computer science portal for geeks
Home Arrays Q&A Interview Corner Ask a question Articles Contribute GFacts GATE Algorithms MCQ C Misc Bit Magic C/C++ Puzzles Linked Lists

GeeksQuiz
Login

C++

Books

About us Trees Search

Output

Strings

gi n p alr O e v (1 t e S| m a r m g n o i rc P m D a n y i ) y tr e p o rm P e s l b o r p b u S
Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems and stores the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming. 1) Overlapping Subproblems 2) Optimal Substructure 1) Overlapping Subproblems: Like Divide and Conquer, Dynamic Programming combines solutions to sub-problems. Dynamic Programming is mainly used when solutions of same subproblems are needed again and again. In dynamic programming, computed solutions to subproblems are stored in a table so that these dont have to recomputed. So Dynamic Programming is not useful when there are no common (overlapping) subproblems because there is no point storing the solutions if they are not needed again. For example, Binary Search doesnt have common subproblems. If we take example of following recursive program for Fibonacci Numbers, there are many subproblems which are solved again and again.
/* simple recursive program for Fibonacci numbers */ int fib(int n) { if ( n <= 1 ) return n; return fib(n-1) + fib(n-2); }

Interview Experiences Advanced Data Structures Dynamic Programming GreedyAlgorithms Backtracking Pattern Searching Divide & Conquer Graph Mathematical Algorithms Recursion Java

GeeksforGeeks
Like 41,166 people like GeeksforGeeks.

Recursion tree for execution of fib(5)


fib(5) / \ fib(4) fib(3) / \ / \ fib(3) fib(2) fib(2) fib(1) / \ / \ / \ fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) / \ fib(1) fib(0)

F acebook social plugin

We can see that the function f(3) is being called 2 times. If we would have stored the value of f(3), then instead of computing it again, we would have reused the old stored value. There are following two different ways to store the values so that these values can be reused. a) Memoization (Top Down): b) Tabulation (Bottom Up): a) Memoization (Top Down): The memoized program for a problem is similar to the recursive version with a small modification that it looks into a lookup table before computing solutions. We initialize a lookup array with all initial values as NIL. Whenever we need solution to a subproblem, we first look into the lookup table. If the precomputed value is there then we return that value, otherwise we calculate the value and put the result in lookup table so that it can be reused later. Following is the memoized version for nth Fibonacci Number.
/* Memoized version for nth Fibonacci number */ #include<stdio.h> #define NIL -1 #define MAX 100 int lookup[MAX]; /* Function to initialize NIL values in lookup table */ void _initialize() { int i; for (i = 0; i < MAX; i++) lookup[i] = NIL; } /* function for nth Fibonacci number */ int fib(int n) {

sts or P au l p o P
All permutations of a given string Memory Layout of C Programs Understanding extern keyword in C Median of two sorted arrays Tree traversal without recursion and without stack! Structure Member Alignment, Padding and Data Packing Intersection point of two Linked Lists Lowest Common Ancestor in a BST. Check if a binary tree is BST or not Sorted Linked List to Balanced BST

converted by Web2PDFConvert.com

if(lookup[n] { if ( n <= 1 lookup[n] else lookup[n] } }

== NIL) ) = n; = fib(n-1) + fib(n-2);

return lookup[n]; int main () { int n = 40; _initialize(); printf("Fibonacci number is %d ", fib(n)); getchar(); return 0; }

b) Tabulation (Bottom Up): The tabulated program for a given problem builds a table in bottom up fashion and returns the last entry from table.
/* tabulated version */ #include<stdio.h> int fib(int n) { int f[n+1]; int i; f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) f[i] = f[i-1] + f[i-2]; return f[n]; } int main () { int n = 9; printf("Fibonacci number is %d ", fib(n)); getchar(); return 0; }

Both tabulated and Memoized store the solutions of subproblems. In Memoized version, table is filled on demand while in tabulated version, starting from the first entry, all entries are filled one by one. Unlike the tabulated version, all entries of the lookup table are not necessarily filled in memoized version. For example, memoized solution of LCS problem doesnt necessarily fill all entries. To see the optimization achieved by memoized and tabulated versions over the basic recursive version, see the time taken by following runs for 40th Fibonacci number. Simple recursive program Memoized version tabulated version Also see method 2 of Ugly Number post for one more simple example where we have overlapping subproblems and we store the results of subproblems. We will be covering Optimal Substructure Property and some more example problems in future posts on Dynamic Programming. Try following questions as an exercise of this post. 1) Write a memoized version for LCS problem. Note that the tabular version is given in the CLRS book. 2) How would you choose between Memoization and Tabulation? Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. References: http://www.cs.uiuc.edu/class/fa08/cs573/lectures/05-dynprog.pdf http://web.iiit.ac.in/~avidullu/pdfs/dynprg/Dynamic%20Programming%20Lesson.pdf http://www.youtube.com/watch?v=V5hZoJ6uK-s
Like 10 Tweet 1

Follow @Geeksforgeeks

1,916 followers

625

Subscribe

C m o s m t n e R c e
abhatnagMore efficient code in C++ using classes...
Graph and its representations 13 minutes ago

fateh_singh1 more thing dere s no condition to stop...


Recursively remove all adjacent duplicates 17 minutes ago

Knyaz Miloslavskiin c++, unless the function is virtual, it is...


Does overloading work with Inheritance? 1 hour ago

mrigank#include<stdio.h> struct node { int data;...</stdio.h>


Merge a linked list into another linked list at alternate positions 1 hour ago

GeeksforGeeksMeet, thanks for pointing this out. We have...


Does overloading work with Inheritance? 2 hours ago

Meetit never disturbs with the (enclosing) scope of...


Does overloading work with Inheritance? 2 hours ago

Fibonacci Property Lookup


converted by Web2PDFConvert.com

Property Lookup Post Code Lookup Post Code Lookup Algorithm Recursion Fibonacci Function

Related Questions:
Count all possible paths from top left to bottom right of a mXn matrix How to compare two arrays in Java? DELL Interview | Set 1 (On-Campus) Oracle Interview | Set 4 (On-Campus) Print all possible paths from top left to bottom right of a mXn matrix D E Shaw Interview | Set 3 Generate all unique partitions of an integer Microsoft Interview | Set 24
Writing code in comment? Please use ideone.com and share the link here.

@geeksforgeeks, Some rights reserved

Contact Us!

Powered by WordPress & MooTools, customized by geeksforgeeks team

converted by Web2PDFConvert.com

You might also like