0% found this document useful (0 votes)
118 views28 pages

Line Sweep Algorithms: Schalk-Willem Krüger - 2009 Training Camp 1

The document describes several algorithms that use a sweep line approach: 1. The closest pair algorithm finds the closest pair of points among a set of points by initializing the shortest distance and updating it as the sweep line encounters closer point pairs. This takes O(N log N) time. 2. Finding line segment intersections with only horizontal and vertical segments uses events for line starts/ends and intersections. A balanced binary tree stores current intersecting lines. This takes O(N log N) time. 3. Computing the union of rectangle areas sweeps the plane twice, incrementing/decrementing an overlap count at rectangle edges to sum multiplied edge distances. This takes O(N2) time with improvement

Uploaded by

Jasper Lu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views28 pages

Line Sweep Algorithms: Schalk-Willem Krüger - 2009 Training Camp 1

The document describes several algorithms that use a sweep line approach: 1. The closest pair algorithm finds the closest pair of points among a set of points by initializing the shortest distance and updating it as the sweep line encounters closer point pairs. This takes O(N log N) time. 2. Finding line segment intersections with only horizontal and vertical segments uses events for line starts/ends and intersections. A balanced binary tree stores current intersecting lines. This takes O(N log N) time. 3. Computing the union of rectangle areas sweeps the plane twice, incrementing/decrementing an overlap count at rectangle edges to sum multiplied edge distances. This takes O(N2) time with improvement

Uploaded by

Jasper Lu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 28

Line Sweep

Algorithms
Schalk-Willem Krger 2009 Training Camp 1

presentation.start();

Closest Pair Algorithm


The problem
2008TrainingCamp2:GoodNeighbours
Theproblem:
Brucewantstovisithisfriendsonweekends.
Thefriendsarescatteredaround(eachataunique
location).
Findthetwofriendsthatliveclosesttoeachother
Maximumof1000000friends
2

Bruteforce:O(N )tooslow

Closest Pair Algorithm

Initialize h (shortest distance found so far) with the distance between the first two points.
3
h = Euclidian distance between point 1 and 2 = 6.23 units

Closest Pair Algorithm

6.44 units
h

h = Euclidian distance between point 1 and 2 = 6.23 units


No distance less than 6.23 units.

Closest Pair Algorithm

6.26 units

5.45 units

h = Euclidian distance between point 1 and 2 = 6.23 units


There are two points that are closer than the current value of h! Change h to 5.45.

Closest Pair Algorithm

4.30 units

h = Euclidian distance between point 1 and 2 = 5.45 units


Change h to 4.30 units.

Closest Pair Algorithm


C++implementation(withSTL)
#include <stdio.h>
#include <set>
#include <algorithm>
#include <cmath>
using namespace std;
#define px second
#define py first
typedef pair<long long, long long> pairll;
int n;
pairll pnts [100000];
set<pairll> box;
double best;
int compx(pairll a, pairll b) { return a.px<b.px; }
int main () {
scanf("%d", &n);
for (int i=0;i<n;++i) scanf("%lld %lld", &pnts[i].px, &pnts[i].py);
sort(pnts, pnts+n, compx);
best = 1500000000; // INF
box.insert(pnts[0]);
int left = 0;
for (int i=1;i<n;++i) {
while (left<i && pnts[i].px-pnts[left].px > best) box.erase(pnts[left++]);
for (typeof(box.begin()) it=box.lower_bound(make_pair(pnts[i].py-best, pnts[i].px-best));
it! =box.end() && pnts[i].py+best>=it->py; it++)
best = min(best, sqrt(pow(pnts[i].py - it->py, 2.0)+pow(pnts[i].px - it->px, 2.0)));
box.insert(pnts[i]);
}
printf("%.2f\n", best);
return 0;
}

Use a balanced binary tree (Set)

Time complexity: O(N log N)


7

Closest Pair Algorithm


C++implementation(withSTL)zoomedin
box.insert(pnts[0]);
int left = 0;
for (int i=1;i<n;++i) {
while (left<i && pnts[i].px-pnts[left].px > best)
box.erase(pnts[left++]);
for (typeof(box.begin()) it=
box.lower_bound(make_pair(pnts[i].py-best, pnts[i].px-best));
it!=box.end() && pnts[i].py+best>=it->py; it++)
best = min(best, sqrt(pow(pnts[i].py it->py,2.0)+
pow(pnts[i].px - it->px, 2.0)));
box.insert(pnts[i]);
}
printf("%.2f\n", best);

Time complexity: O(N log N)


8

Line segment intersections (HV)


Problem:givenasetSofNclosedsegmentsinthe
plane,reportallintersectionpointsamongthe
segmentinS
Firstconsidertheproblemwithonlyhorizontaland
verticallinesegments
Bruteforce:O(N2)time
tooslow

Line segment intersections (HV)


Useevents:startofhorizontalline,endofhorizontalline
andverticalline.
Setcontainsallhorizontallinescutbythesweepline
(sortedbyY).Indicatedasredlinesondiagram.
Horizontallineevent:add/removelinefromset.
Verticallineevent:getallhorizontallinesitcuts(get
rangefromset).Indicatedasred
dotsondiagram.
Usebalancedbinarytree(C++set)
guaranteeO(logN)foroperations.
10

Line segment intersections (HV)


// <Headers, structs, declarations, etc.>
// type=0: Starting point of horizontal line
// type=1: Ending point of horizontal line
int main () {
// <Input>
sort(events, events+e);
// Sort events by X-coordinate
for (int i=0;i<e;++i) {
event c = events[i];
// c: current event
if (c.type==0) s.insert(c.p1);
// Add starting point to set
else if (c.type==1) s.erase(c.p2); // Remove ending point from set
else {
for (typeof(s.begin()) it=s.lower_bound(point(-1, c.p1.y));
it!=s.end() && it->y<=c.p2.y; it++) // Range search
printf("%d, %d\n", events[i].p1.x, it->y);
}
}
return 0;
}

11

Line segment intersections


Moregeneralcase:linesdon'thavetobehorizontalor
vertical.
Lineschangeplaceswhentheyintersect.
Usepriorityqueuetohandleevents.
EventsalsosortedbyX.
Eventsinpriorityqueue:
endpointsoflinesegments
intersectionpointsofadjacentelements.

Setcontainssegmentsthatarecurrently
intersectingwiththesweepline.

12

Line segment intersections


Atastartingpointofalinesegment:
Insertsegmentintoset.
Neigboursarenolongeradjacent.Deletetheirintersectionpoint(ifany)
fromthepriorityqueueifitexists.
Computeintersectionofthispointanditsneigbours(ifany)andinsertinto
priorityqueue.

Atanendingpointofalinesegment:
Deletesegmentfromset.
Neigboursarenowadjacent.Computetheirintersectionpoint(ifany)and
insertintopriorityqueue.

Atanintersectionpointoftwolinesegments:
Outputpoint.
Swappositionofintersectionsegmentsinset.
Theswappedsegmentshavenewneigboursnow.Insert/deleteintersecting
13
pointsfrompriorityqueue(ifneeded).

Area of union of rectangles


Calculateareaoftheunionofasetofrectangles.
Againworkwithevents(sortedbyx)andaset(sorted
byy).
Events:
Leftedge
Rightedge

Setcontainsalltherectangles
thesweeplineiscrossing.
14

Area of union of rectangles


Knowxdistance(x)betweentwoadjacentevents.
Multiplyitbythecutlengthofthesweepline(y)toget
thetotalareaofrectanglesbetweenthetwoevents.
Dothisbyrunningthesamealgorithmrotated90degrees.
(Horizontalsweeplinerunningfromtoptobottom)
Useonlyrectanglesintheactiveset
Event:Horizontaledges.
Useacounterthatindicateshowmany
rectanglesareoverlappingatthecurrentpoint.
Cutlengthsarebetweentwoeventswherethecountiszero.
15

Area of union of rectangles


Example of inner loop
Horizontal sweep line

Vertical sweep line

xbetweentwoadjacentverticalevents

Count: 1

16

Area of union of rectangles


Example of inner loop

Count: 2

17

Area of union of rectangles


Example of inner loop

Count: 3

18

Area of union of rectangles


Example of inner loop

Count: 2

19

Area of union of rectangles


Example of inner loop

Count: 1

20

Area of union of rectangles


Example of inner loop

Count: 0

21

Area of union of rectangles


Example of inner loop

Count: 1

22

Area of union of rectangles


Example of inner loop

Count: 0

23

Area of union of rectangles

Source code (C++) can be seen on the handout.

24

Area of union of rectangles


Runtime:O(N2)withbooleanarrayintheplaceofa
balancedbinarytree(presortthesetofhorizontal
edges).
CanbereducedtoO(NlogN)withabinarytree
manipulation.

25

IOI '98: Pictures


Given:Anumberofrectangles.(0<=N<5000)
Calculatetheperimeter(lengthoftheboundaryofthe
unionofallrectangles)

Usebasicallythesamealgorithm
Horizontalboundaries:wherecountiszeroininner
loop.

26

Convex hull with sweep line


Grahamscan:Sortbyangleisexpensiveandcanget
numericerrors.(CanuseC++complexlibrary)
Simpleralgorithm:Andrew'sAlgorithm
SortbyXanduseasweepline!
Upperhull:StartatpointwithminimumXcoordinateand
moveright.Whenthelastthreepointsaren'tconvex,
deletethesecondlastpoint.Repeatuntilthelastthree
pointsformaconvextriangle.
SweeplinealgorithmrunsinO(N)
O(NlogN)(pointsaresorted)

27

Questions?

?
presentation.end();

28

You might also like