普林斯顿算法课第五周作业


Use the immutable data type  RectHV.java  (not part of  algs4.jar ) for axis-aligned rectanges. Here is the subset of its API that you may use:
public class RectHV {
   public    RectHV(double xmin, double ymin,      // construct the rectangle [xmin, xmax] x [ymin, ymax] 
                    double xmax, double ymax)      // throw a java.lang.IllegalArgumentException if (xmin > xmax) or (ymin > ymax)
   public  double xmin()                           // minimum x-coordinate of rectangle 
   public  double ymin()                           // minimum y-coordinate of rectangle 
   public  double xmax()                           // maximum x-coordinate of rectangle 
   public  double ymax()                           // maximum y-coordinate of rectangle 
   public boolean contains(Point2D p)              // does this rectangle contain the point p (either inside or on boundary)? 
   public boolean intersects(RectHV that)          // does this rectangle intersect that rectangle (at one or more points)? 
   public  double distanceTo(Point2D p)            // Euclidean distance from point p to closest point in rectangle 
   public  double distanceSquaredTo(Point2D p)     // square of Euclidean distance from point p to closest point in rectangle 
   public boolean equals(Object that)              // does this rectangle equal that object? 
   public    void draw()                           // draw to standard draw 
   public  String toString()                       // string representation 
}
Do not modify these data types.

Brute-force implementation. Write a mutable data type PointSET.java that represents a set of points in the unit square. Implement the following API by using a red-black BST (using either SET from algs4.jar or java.util.TreeSet).

public class PointSET {
   public         PointSET()                               // construct an empty set of points 
   public           boolean isEmpty()                      // is the set empty? 
   public               int size()                         // number of points in the set 
   public              void insert(Point2D p)              // add the point to the set (if it is not already in the set)
   public           boolean contains(Point2D p)            // does the set contain point p? 
   public              void draw()                         // draw all points to standard draw 
   public Iterable<Point2D> range(RectHV rect)             // all points that are inside the rectangle 
   public           Point2D nearest(Point2D p)             // a nearest neighbor in the set to point p; null if the set is empty 

   public static void main(String[] args)                  // unit testing of the methods (optional) 
}
Your implementation should support  insert()  and  contains()  in time proportional to the logarithm of the number of points in the set in the worst case; it should support nearest()  and  range()  in time proportional to the number of points in the set.

2d-tree implementation. Write a mutable data type KdTree.java that uses a 2d-tree to implement the same API (but replace PointSET with KdTree). A 2d-tree is a generalization of a BST to two-dimensional keys. The idea is to build a BST with points in the nodes, using the x- and y-coordinates of the points as keys in strictly alternating sequence.

  • Search and insert. The algorithms for search and insert are similar to those for BSTs, but at the root we use the x-coordinate (if the point to be inserted has a smaller x-coordinate than the point at the root, go left; otherwise go right); then at the next level, we use the y-coordinate (if the point to be inserted has a smaller y-coordinate than the point in the node, go left; otherwise go right); then at the next level the x-coordinate, and so forth.

Insert (0.7, 0.2)

insert (0.7, 0.2)
Insert (0.5, 0.4)

insert (0.5, 0.4)
Insert (0.2, 0.3)

insert (0.2, 0.3)
Insert (0.4, 0.7)

insert (0.4, 0.7)
Insert (0.9, 0.6)

insert (0.9, 0.6)
Insert (0.7, 0.2)
Insert (0.5, 0.4)
Insert (0.2, 0.3)
Insert (0.4, 0.7)
Insert (0.9, 0.6)
  • Draw. A 2d-tree divides the unit square in a simple way: all the points to the left of the root go in the left subtree; all those to the right go in the right subtree; and so forth, recursively. Your draw() method should draw all of the points to standard draw in black and the subdivisions in red (for vertical splits) and blue (for horizontal splits). This method need not be efficient—it is primarily for debugging.

The prime advantage of a 2d-tree over a BST is that it supports efficient implementation of range search and nearest neighbor search. Each node corresponds to an axis-aligned rectangle in the unit square, which encloses all of the points in its subtree. The root corresponds to the unit square; the left and right children of the root corresponds to the two rectangles split by the x-coordinate of the point at the root; and so forth.

  • Range search. To find all points contained in a given query rectangle, start at the root and recursively search for points in both subtrees using the followingpruning rule: if the query rectangle does not intersect the rectangle corresponding to a node, there is no need to explore that node (or its subtrees). A subtree is searched only if it might contain a point contained in the query rectangle.

  • Nearest neighbor search. To find a closest point to a given query point, start at the root and recursively search in both subtrees using the following pruning rule: if the closest point discovered so far is closer than the distance between the query point and the rectangle corresponding to a node, there is no need to explore that node (or its subtrees). That is, a node is searched only if it might contain a point that is closer than the best one found so far. The effectiveness of the pruning rule depends on quickly finding a nearby point. To do this, organize your recursive method so that when there are two possible subtrees to go down, you always choose the subtree that is on the same side of the splitting line as the query point as the first subtree to explore—the closest point found while exploring the first subtree may enable pruning of the second subtree.

Clients.  You may use the following interactive client programs to test and debug your code.

  • KdTreeVisualizer.java computes and draws the 2d-tree that results from the sequence of points clicked by the user in the standard drawing window.

  • RangeSearchVisualizer.java reads a sequence of points from a file (specified as a command-line argument) and inserts those points into a 2d-tree. Then, it performs range searches on the axis-aligned rectangles dragged by the user in the standard drawing window.

  • NearestNeighborVisualizer.java reads a sequence of points from a file (specified as a command-line argument) and inserts those points into a 2d-tree. Then, it performs nearest neighbor queries on the point corresponding to the location of the mouse in the standard drawing window.

Analysis of running time and memory usage (optional and not graded). 

  • Give the total memory usage in bytes (using tilde notation) of your 2d-tree data structure as a function of the number of points N, using the memory-cost model from lecture and Section 1.4 of the textbook. Count all memory that is used by your 2d-tree, including memory for the nodes, points, and rectangles.

  • Give the expected running time in seconds (using tilde notation) to build a 2d-tree on N random points in the unit square. (Do not count the time to read in the points from standard input.)

  • How many nearest neighbor calculations can your 2d-tree implementation perform per second for input100K.txt (100,000 points) and input1M.txt (1 million points), where the query points are random points in the unit square? (Do not count the time to read in the points or to build the 2d-tree.) Repeat this question but with the brute-force implementation.

Submission.  Submit only PointSET.java and and KdTree.java. We will supply RectHV.javastdlib.jar, and algs4.jar. Your may not call any library functions other than those in java.langjava.utilstdlib.jar, and algs4.jar.

This assignment was developed by Kevin Wayne.


---------------------------------------------------
正文:
第五周作业 Kd-Trees


本次的作业是应用2d-tree写出一个有效地范围搜索算法和找出临近点的搜索算法。


本周作业需要用到两个官方jar包中的类Point2D和RectHV,用来计算点到点距离以及点到指定矩形距离,非常方便。


而学生需要自行写出的则有两个类
第一个是暴力解法PointSET

public class PointSET {
   public         PointSET()                               // construct an empty set of points 
   public           boolean isEmpty()                      // is the set empty? 
   public               int size()                         // number of points in the set 
   public              void insert(Point2D p)              // add the point to the set (if it is not already in the set)
   public           boolean contains(Point2D p)            // does the set contain point p? 
   public              void draw()                         // draw all points to standard draw 
   public Iterable<Point2D> range(RectHV rect)             // all points that are inside the rectangle 
   public           Point2D nearest(Point2D p)             // a nearest neighbor in the set to point p; null if the set is empty 


   public static void main(String[] args)                  // unit testing of the methods (optional) 
}



第二个则是应用2d-tree方法的解法。两者API相同只有类名不同。


先稍微说一下暴力解法。
我创建了一个集合类TreeSet用来实现数据的存储.
TreeSet 是一个类,使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。 
此实现为基本操作(add、remove 和 contains)提供受保证的 log(n) 时间开销。
所以本类中大部分的方法都可以用库中方法实现。
而搜索算法则是用迭代器遍历所得。




而KdTree当然是用了KD-Tree方法来实现。


在Q&A中也提到,需要使用链表对树本身进行构建。


需要注意的是以下几点:
1.insert中需要对插入节点为水平或垂直进行判断。
这就要再每个节点添加一个参数。


2.contain函数的遍历算法也同样用到了对节点垂直性的判断。
若垂直,则比较x坐标,小左大右。
若水平,则比较y坐标,同样也是小左大右。

源代码如下:
PointSET.java
import java.util.TreeSet;

public class PointSET {
	private TreeSet<Point2D> pointSET;
	public PointSET(){
	   this.pointSET=new TreeSet<Point2D>();	   
   }                               // construct an empty set of points 
   
	public boolean isEmpty(){
	   return this.pointSET.size()==0; 
   }                      // is the set empty? 
   
	public int size(){
	   return this.pointSET.size();
   }                         // number of points in the set 
   
   public  void insert(Point2D p){
	   this.pointSET.add(p);
   }              // add the point to the set (if it is not already in the set)
   
   public boolean contains(Point2D p){
   
	   return pointSET.contains(p); 
   }            // does the set contain point p? 
   
   public void draw(){
	   for (Point2D p : pointSET) {  
           StdDraw.point(p.x(), p.y());  
       }  
   }                         // draw all points to standard draw 
   
   public Iterable<Point2D> range(RectHV rect){
	   TreeSet<Point2D> rangeSet = new TreeSet<Point2D>();  
       for (Point2D p : pointSET) {  
           if (rect.contains(p)){  
               rangeSet.add(p);  
           }  
       }  
       return rangeSet;  
	   
   }             // all points that are inside the rectangle 
   
   public  Point2D nearest(Point2D p){
	   Point2D nearestPoint2D = null;  
       double distance = Double.MAX_VALUE;  
         
       if (this.pointSET.isEmpty()){  
           return nearestPoint2D;  
       }  
         
       for (Point2D pointIter : pointSET) {  
           if (pointIter.distanceTo(p) < distance){  
               nearestPoint2D = pointIter;  
               distance = pointIter.distanceTo(p);  
           }  
       }  
       return nearestPoint2D;  
   }             // a nearest neighbor in the set to point p; null if the set is empty 

   public static void main(String[] args) {

       
       In in = new In(args[0]);


       StdDraw.show(0);

       // initialize the data structures with N points from standard input
       PointSET brute = new PointSET();
       //KdTree kdtree = new KdTree();
       while (!in.isEmpty()) {
           double x = in.readDouble();
           double y = in.readDouble();
           Point2D p = new Point2D(x, y);
           //kdtree.insert(p);
           brute.insert(p);
       }

       double x0 = 0.0, y0 = 0.0;      // initial endpoint of rectangle
       double x1 = 0.0, y1 = 0.0;      // current location of mouse
       boolean isDragging = false;     // is the user dragging a rectangle

       // draw the points
       StdDraw.clear();
       StdDraw.setPenColor(StdDraw.BLACK);
       StdDraw.setPenRadius(.01);
       brute.draw();

       while (true) {
           StdDraw.show(40);

           // user starts to drag a rectangle
           if (StdDraw.mousePressed() && !isDragging) {
               x0 = StdDraw.mouseX();
               y0 = StdDraw.mouseY();
               isDragging = true;
               continue;
           }

           // user is dragging a rectangle
           else if (StdDraw.mousePressed() && isDragging) {
               x1 = StdDraw.mouseX();
               y1 = StdDraw.mouseY();
               continue;
           }

           // mouse no longer pressed
           else if (!StdDraw.mousePressed() && isDragging) {
               isDragging = false;
           }


           RectHV rect = new RectHV(Math.min(x0, x1), Math.min(y0, y1),
                                    Math.max(x0, x1), Math.max(y0, y1));
           // draw the points
           StdDraw.clear();
           StdDraw.setPenColor(StdDraw.BLACK);
           StdDraw.setPenRadius(.01);
           brute.draw();

           // draw the rectangle
           StdDraw.setPenColor(StdDraw.BLACK);
           StdDraw.setPenRadius();
           rect.draw();

           // draw the range search results for brute-force data structure in red
           StdDraw.setPenRadius(.03);
           StdDraw.setPenColor(StdDraw.RED);
           for (Point2D p : brute.range(rect))
               p.draw();

           // draw the range search results for kd-tree in blue
           StdDraw.setPenRadius(.02);
           StdDraw.setPenColor(StdDraw.BLUE);
           //for (Point2D p : kdtree.range(rect))
             //  p.draw();

           StdDraw.show(40);
       }
   }                 // unit testing of the methods (optional) 
}

kdtree.java
import java.util.TreeSet;


public class KdTree {
	//create struct
	 private static class KdNode {  
	        private KdNode leftNode;  
	        private KdNode rightNode;  
	        private final boolean isVertical;  
	        private final double x;  
	        private final double y;  
	  
	        public KdNode(final double x, final double y, final KdNode leftNode,  final KdNode rightNode, final boolean isVertical) {  
	            this.x = x;  
	            this.y = y;  
	            this.leftNode = leftNode;  
	            this.rightNode = rightNode;  
	            this.isVertical = isVertical;  
	            }  
	        }  
	    private static final RectHV CONTAINER = new RectHV(0, 0, 1, 1);  
	    private KdNode rootNode;  
	    private int size;  
	   public KdTree(){
		   this.size = 0;  
	       this.rootNode = null;  
	   }                               // construct an empty set of points 
	  
	   public boolean isEmpty(){
		   return this.size == 0;
	   }                      // is the set empty? 
	   
	   public int size(){
		   return this.size;
	   }                         // number of points in the set 
	   
	   public void insert(final Point2D p){
		   this.rootNode = insert(this.rootNode, p, true);
	   }              // add the point to the set (if it is not already in the set)
	   
	   private KdNode insert(final KdNode node, final Point2D p,  
	            final boolean isVertical) {  
	        // if new node, create it  
	        if (node == null) {  
	            size++;  
	            return new KdNode(p.x(), p.y(), null, null, isVertical);  
	        }  
	  
	        // if already in, return it  
	        if (node.x == p.x() && node.y == p.y()) {  
	            return node;  
	        }  
	  
	        // insert it where corresponds (left - right recursive call)  
	        if (node.isVertical && p.x() < node.x || !node.isVertical  
	                && p.y() < node.y) {  
	            node.leftNode = insert(node.leftNode, p, !node.isVertical);  
	        } else {  
	            node.rightNode = insert(node.rightNode, p, !node.isVertical);  
	        }  
	        return node;  
	    }  
	   public boolean contains(Point2D p) {  
	        return contains(rootNode, p.x(), p.y());  
	    } 
	   private boolean contains(KdNode node, double x, double y) {  
	        if (node == null) {  
	            return false;  
	        }  
	  
	        if (node.x == x && node.y == y) {  
	            return true;  
	        }  
	  
	        if (node.isVertical && x < node.x || !node.isVertical && y < node.y) {  
	            return contains(node.leftNode, x, y);  
	        } else {  
	            return contains(node.rightNode, x, y);  
	        }  
	    }              // does the set contain point p? 
	   public void draw() {  
	        StdDraw.setScale(0, 1);  
	  
	        StdDraw.setPenColor(StdDraw.BLACK);  
	        StdDraw.setPenRadius();  
	        CONTAINER.draw();  
	  
	        draw(rootNode, CONTAINER);  
	    }  
	   private void draw(final KdNode node, final RectHV rect) {  
	        if (node == null) {  
	            return;  
	        }  
	  
	        // draw the point  
	        StdDraw.setPenColor(StdDraw.BLACK);  
	        StdDraw.setPenRadius(0.01);  
	        new Point2D(node.x, node.y).draw();  
	  
	        // get the min and max points of division line  
	        Point2D min, max;  
	        if (node.isVertical) {  
	            StdDraw.setPenColor(StdDraw.RED);  
	            min = new Point2D(node.x, rect.ymin());  
	            max = new Point2D(node.x, rect.ymax());  
	        } else {  
	            StdDraw.setPenColor(StdDraw.BLUE);  
	            min = new Point2D(rect.xmin(), node.y);  
	            max = new Point2D(rect.xmax(), node.y);  
	        }  
	  
	        // draw that division line  
	        StdDraw.setPenRadius();  
	        min.drawTo(max);  
	  
	        // recursively draw children  
	        draw(node.leftNode, leftRect(rect, node));  
	        draw(node.rightNode, rightRect(rect, node));  
	    }  
	  
	    private RectHV leftRect(final RectHV rect, final KdNode node) {  
	        if (node.isVertical) {  
	            return new RectHV(rect.xmin(), rect.ymin(), node.x, rect.ymax());  
	        } else {  
	            return new RectHV(rect.xmin(), rect.ymin(), rect.xmax(), node.y);  
	        }  
	    }  
	  
	    private RectHV rightRect(final RectHV rect, final KdNode node) {  
	        if (node.isVertical) {  
	            return new RectHV(node.x, rect.ymin(), rect.xmax(), rect.ymax());  
	        } else {  
	            return new RectHV(rect.xmin(), node.y, rect.xmax(), rect.ymax());  
	        }  
	    }  
	  
	    // all points in the set that are inside the rectangle  
	    public Iterable<Point2D> range(final RectHV rect) {  
	        final TreeSet<Point2D> rangeSet = new TreeSet<Point2D>();  
	        range(rootNode, CONTAINER, rect, rangeSet);  
	  
	        return rangeSet;  
	    }  
	  
	    private void range(final KdNode node, final RectHV nrect,  
	            final RectHV rect, final TreeSet<Point2D> rangeSet) {  
	        if (node == null)  
	            return;  
	  
	        if (rect.intersects(nrect)) {  
	            final Point2D p = new Point2D(node.x, node.y);  
	            if (rect.contains(p))  
	                rangeSet.add(p);  
	            range(node.leftNode, leftRect(nrect, node), rect, rangeSet);  
	            range(node.rightNode, rightRect(nrect, node), rect, rangeSet);  
	        }  
	    }  
	  
	    // a nearest neighbor in the set to p; null if set is empty  
	    public Point2D nearest(final Point2D p) {  
	        return nearest(rootNode, CONTAINER, p.x(), p.y(), null);  
	    }  
	  
	    private Point2D nearest(final KdNode node, final RectHV rect,  
	            final double x, final double y, final Point2D candidate) {  
	        if (node == null){  
	            return candidate;  
	        }  
	  
	        double dqn = 0.0;  
	        double drq = 0.0;  
	        RectHV left = null;  
	        RectHV rigt = null;  
	        final Point2D query = new Point2D(x, y);  
	        Point2D nearest = candidate;  
	  
	        if (nearest != null) {  
	            dqn = query.distanceSquaredTo(nearest);  
	            drq = rect.distanceSquaredTo(query);  
	        }  
	  
	        if (nearest == null || dqn > drq) {  
	            final Point2D point = new Point2D(node.x, node.y);  
	            if (nearest == null || dqn > query.distanceSquaredTo(point))  
	                nearest = point;  
	  
	            if (node.isVertical) {  
	                left = new RectHV(rect.xmin(), rect.ymin(), node.x, rect.ymax());  
	                rigt = new RectHV(node.x, rect.ymin(), rect.xmax(), rect.ymax());  
	  
	                if (x < node.x) {  
	                    nearest = nearest(node.leftNode, left, x, y, nearest);  
	                    nearest = nearest(node.rightNode, rigt, x, y, nearest);  
	                } else {  
	                    nearest = nearest(node.rightNode, rigt, x, y, nearest);  
	                    nearest = nearest(node.leftNode, left, x, y, nearest);  
	                }  
	            } else {  
	                left = new RectHV(rect.xmin(), rect.ymin(), rect.xmax(), node.y);  
	                rigt = new RectHV(rect.xmin(), node.y, rect.xmax(), rect.ymax());  
	  
	                if (y < node.y) {  
	                    nearest = nearest(node.leftNode, left, x, y, nearest);  
	                    nearest = nearest(node.rightNode, rigt, x, y, nearest);  
	                } else {  
	                    nearest = nearest(node.rightNode, rigt, x, y, nearest);  
	                    nearest = nearest(node.leftNode, left, x, y, nearest);  
	                }  
	            }  
	        }  
	  
	        return nearest;  
	    }  
	    public static void main(String[] args) {

	        String filename = args[0];
	        In in = new In(filename);


	        StdDraw.show(0);

	        // initialize the data structures with N points from standard input
	        PointSET brute = new PointSET();
	        KdTree kdtree = new KdTree();
	        while (!in.isEmpty()) {
	            double x = in.readDouble();
	            double y = in.readDouble();
	            Point2D p = new Point2D(x, y);
	            kdtree.insert(p);
	            brute.insert(p);
	        }

	        double x0 = 0.0, y0 = 0.0;      // initial endpoint of rectangle
	        double x1 = 0.0, y1 = 0.0;      // current location of mouse
	        boolean isDragging = false;     // is the user dragging a rectangle

	        // draw the points
	        StdDraw.clear();
	        StdDraw.setPenColor(StdDraw.BLACK);
	        StdDraw.setPenRadius(.01);
	        brute.draw();

	        while (true) {
	            StdDraw.show(40);

	            // user starts to drag a rectangle
	            if (StdDraw.mousePressed() && !isDragging) {
	                x0 = StdDraw.mouseX();
	                y0 = StdDraw.mouseY();
	                isDragging = true;
	                continue;
	            }

	            // user is dragging a rectangle
	            else if (StdDraw.mousePressed() && isDragging) {
	                x1 = StdDraw.mouseX();
	                y1 = StdDraw.mouseY();
	                continue;
	            }

	            // mouse no longer pressed
	            else if (!StdDraw.mousePressed() && isDragging) {
	                isDragging = false;
	            }


	            RectHV rect = new RectHV(Math.min(x0, x1), Math.min(y0, y1),
	                                     Math.max(x0, x1), Math.max(y0, y1));
	            // draw the points
	            StdDraw.clear();
	            StdDraw.setPenColor(StdDraw.BLACK);
	            StdDraw.setPenRadius(.01);
	            brute.draw();

	            // draw the rectangle
	            StdDraw.setPenColor(StdDraw.BLACK);
	            StdDraw.setPenRadius();
	            rect.draw();

	            // draw the range search results for brute-force data structure in red
	            StdDraw.setPenRadius(.03);
	            StdDraw.setPenColor(StdDraw.RED);
	            for (Point2D p : brute.range(rect))
	                p.draw();

	            // draw the range search results for kd-tree in blue
	            StdDraw.setPenRadius(.02);
	            StdDraw.setPenColor(StdDraw.BLUE);
	            for (Point2D p : kdtree.range(rect))
	                p.draw();

	            StdDraw.show(40);
	        }
	    }
}








评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值