Advertisement
Guest User

Untitled

a guest
May 21st, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.16 KB | None | 0 0
  1. //https://github.com/williamfiset/Algorithms/tree/master/com/williamfiset/algorithms/geometry GITHUB GEO algos
  2. //https://geomalgorithms.com/
  3. //http://tutorial.math.lamar.edu/pdf/Calculus_Cheat_Sheet_All.pdf
  4. //http://static.pdesas.org/content/documents/Keystone_Formula_Sheet-Geometry.pdf
  5. //http://tutorial.math.lamar.edu/pdf/Trig_Cheat_Sheet.pdf
  6. //https://www.tug.org/texshowcase/cheat.pdf
  7.  
  8. //Segment tree min query
  9. // Java Program to show segment tree operations like construction,
  10. // query and update
  11. import java.util.*;
  12.  
  13. // Java Program to show segment tree operations like construction,
  14. // query and update
  15. class SegmentTree  
  16. {
  17.     int st[]; // The array that stores segment tree nodes
  18.  
  19.     /* Constructor to construct segment tree from given array. This
  20.        constructor  allocates memory for segment tree and calls
  21.        constructSTUtil() to  fill the allocated memory */
  22.     SegmentTree(int arr[], int n)
  23.     {
  24.         // Allocate memory for segment tree
  25.         //Height of segment tree
  26.         int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
  27.  
  28.         //Maximum size of segment tree
  29.         int max_size = 2 * (int) Math.pow(2, x) - 1;
  30.  
  31.         st = new int[max_size]; // Memory allocation
  32.  
  33.         constructSTUtil(arr, 0, n - 1, 0);
  34.     }
  35.  
  36.     // A utility function to get the middle index from corner indexes.
  37.     int getMid(int s, int e) {
  38.         return s + (e - s) / 2;
  39.     }
  40.  
  41.     /*  A recursive function to get the sum of values in given range
  42.         of the array.  The following are parameters for this function.
  43.  
  44.       st    --> Pointer to segment tree
  45.       si    --> Index of current node in the segment tree. Initially
  46.                 0 is passed as root is always at index 0
  47.       ss & se  --> Starting and ending indexes of the segment represented
  48.                     by current node, i.e., st[si]
  49.       qs & qe  --> Starting and ending indexes of query range */
  50.     int getSumUtil(int ss, int se, int qs, int qe, int si)
  51.     {
  52.         // If segment of this node is a part of given range, then return
  53.         // the sum of the segment
  54.         if (qs <= ss && qe >= se)
  55.             return st[si];
  56.  
  57.         // If segment of this node is outside the given range
  58.         if (se < qs || ss > qe)
  59.             return 0;
  60.  
  61.         // If a part of this segment overlaps with the given range
  62.         int mid = getMid(ss, se);
  63.         return getSumUtil(ss, mid, qs, qe, 2 * si + 1) +
  64.                 getSumUtil(mid + 1, se, qs, qe, 2 * si + 2);
  65.     }
  66.  
  67.     /* A recursive function to update the nodes which have the given  
  68.        index in their range. The following are parameters
  69.         st, si, ss and se are same as getSumUtil()
  70.         i    --> index of the element to be updated. This index is in
  71.                  input array.
  72.        diff --> Value to be added to all nodes which have i in range */
  73.     void updateValueUtil(int ss, int se, int i, int diff, int si)
  74.     {
  75.         // Base Case: If the input index lies outside the range of  
  76.         // this segment
  77.         if (i < ss || i > se)
  78.             return;
  79.  
  80.         // If the input index is in range of this node, then update the
  81.         // value of the node and its children
  82.         st[si] = st[si] + diff;
  83.         if (se != ss) {
  84.             int mid = getMid(ss, se);
  85.             updateValueUtil(ss, mid, i, diff, 2 * si + 1);
  86.             updateValueUtil(mid + 1, se, i, diff, 2 * si + 2);
  87.         }
  88.     }
  89.  
  90.     // The function to update a value in input array and segment tree.
  91.    // It uses updateValueUtil() to update the value in segment tree
  92.     void updateValue(int arr[], int n, int i, int new_val)
  93.     {
  94.         // Check for erroneous input index
  95.         if (i < 0 || i > n - 1) {
  96.             System.out.println("Invalid Input");
  97.             return;
  98.         }
  99.  
  100.         // Get the difference between new value and old value
  101.         int diff = new_val - arr[i];
  102.  
  103.         // Update the value in array
  104.         arr[i] = new_val;
  105.  
  106.         // Update the values of nodes in segment tree
  107.         updateValueUtil(0, n - 1, i, diff, 0);
  108.     }
  109.  
  110.     // Return sum of elements in range from index qs (quey start) to
  111.    // qe (query end).  It mainly uses getSumUtil()
  112.     int getSum(int n, int qs, int qe)
  113.     {
  114.         // Check for erroneous input values
  115.         if (qs < 0 || qe > n - 1 || qs > qe) {
  116.             System.out.println("Invalid Input");
  117.             return -1;
  118.         }
  119.         return getSumUtil(0, n - 1, qs, qe, 0);
  120.     }
  121.  
  122.     // A recursive function that constructs Segment Tree for array[ss..se].
  123.     // si is index of current node in segment tree st
  124.     int constructSTUtil(int arr[], int ss, int se, int si)
  125.     {
  126.         // If there is one element in array, store it in current node of
  127.         // segment tree and return
  128.         if (ss == se) {
  129.             st[si] = arr[ss];
  130.             return arr[ss];
  131.         }
  132.  
  133.         // If there are more than one elements, then recur for left and
  134.         // right subtrees and store the sum of values in this node
  135.         int mid = getMid(ss, se);
  136.         st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) +
  137.                  constructSTUtil(arr, mid + 1, se, si * 2 + 2);
  138.         return st[si];
  139.     }
  140.  
  141.     // Driver program to test above functions
  142.     public static void main(String args[])
  143.     {
  144.         int arr[] = {1, 3, 5, 7, 9, 11};
  145.         int n = arr.length;
  146.         SegmentTree  tree = new SegmentTree(arr, n);
  147.  
  148.         // Build segment tree from given array
  149.  
  150.         // Print sum of values in array from index 1 to 3
  151.         System.out.println("Sum of values in given range = " +
  152.                            tree.getSum(n, 1, 3));
  153.  
  154.         // Update: set arr[1] = 10 and update corresponding segment
  155.         // tree nodes
  156.         tree.updateValue(arr, n, 1, 10);
  157.  
  158.         // Find sum after the value is updated
  159.         System.out.println("Updated sum of values in given range = " +
  160.                 tree.getSum(n, 1, 3));
  161.     }
  162. }
  163.  
  164. //Binary indexed tree
  165.  
  166. // Java program to demonstrate lazy  
  167. // propagation in segment tree
  168. import java.util.*;
  169. import java.lang.*;
  170. import java.io.*;
  171.  
  172. class BinaryIndexedTree
  173. {  
  174.     // Max tree size
  175.     final static int MAX = 1000;      
  176.  
  177.     static int BITree[] = new int[MAX];
  178.      
  179.     /* n --> No. of elements present in input array.  
  180.     BITree[0..n] --> Array that represents Binary  
  181.                     Indexed Tree.
  182.     arr[0..n-1] --> Input array for whic prefix sum  
  183.                     is evaluated. */
  184.  
  185.     // Returns sum of arr[0..index]. This function  
  186.     // assumes that the array is preprocessed and  
  187.     // partial sums of array elements are stored  
  188.     // in BITree[].
  189.     int getSum(int index)
  190.     {
  191.         int sum = 0; // Iniialize result
  192.      
  193.         // index in BITree[] is 1 more than
  194.         // the index in arr[]
  195.         index = index + 1;
  196.      
  197.         // Traverse ancestors of BITree[index]
  198.         while(index>0)
  199.         {
  200.             // Add current element of BITree  
  201.             // to sum
  202.             sum += BITree[index];
  203.      
  204.             // Move index to parent node in  
  205.             // getSum View
  206.             index -= index & (-index);
  207.         }
  208.         return sum;
  209.     }
  210.  
  211.     // Updates a node in Binary Index Tree (BITree)
  212.     // at given index in BITree. The given value  
  213.     // 'val' is added to BITree[i] and all of  
  214.     // its ancestors in tree.
  215.     public static void updateBIT(int n, int index,  
  216.                                         int val)
  217.     {
  218.         // index in BITree[] is 1 more than  
  219.         // the index in arr[]
  220.         index = index + 1;
  221.      
  222.         // Traverse all ancestors and add 'val'
  223.         while(index <= n)
  224.         {
  225.         // Add 'val' to current node of BIT Tree
  226.         BITree[index] += val;
  227.      
  228.         // Update index to that of parent  
  229.         // in update View
  230.         index += index & (-index);
  231.         }
  232.     }
  233.  
  234.     /* Function to construct fenwick tree  
  235.     from given array.*/
  236.     void constructBITree(int arr[], int n)
  237.     {
  238.         // Initialize BITree[] as 0
  239.         for(int i=1; i<=n; i++)
  240.             BITree[i] = 0;
  241.      
  242.         // Store the actual values in BITree[]
  243.         // using update()
  244.         for(int i = 0; i < n; i++)
  245.             updateBIT(n, i, arr[i]);
  246.     }
  247.  
  248.     // Main function
  249.     public static void main(String args[])
  250.     {
  251.         int freq[] = {2, 1, 1, 3, 2, 3,  
  252.                     4, 5, 6, 7, 8, 9};
  253.         int n = freq.length;
  254.         BinaryIndexedTree tree = new BinaryIndexedTree();
  255.  
  256.         // Build fenwick tree from given array
  257.         tree.constructBITree(freq, n);
  258.  
  259.         System.out.println("Sum of elements in arr[0..5]"+
  260.                         " is "+ tree.getSum(5));
  261.          
  262.         // Let use test the update operation
  263.         freq[3] += 6;
  264.          
  265.         // Update BIT for above change in arr[]
  266.         updateBIT(n, 3, 6);  
  267.  
  268.         // Find sum after the value is updated
  269.         System.out.println("Sum of elements in arr[0..5]"+
  270.                     " after update is " + tree.getSum(5));
  271.     }
  272. }
  273.  
  274. // Various geometric functions
  275.  
  276. class Point{
  277.     int x,y;
  278.     Point(int x,int y){
  279.         this.x=x;
  280.         this.y=y;
  281.     }
  282. }
  283. class Line{
  284.     Point point1,point2;
  285.     Line(Point point1,Point point2){
  286.         this.point1=point1;
  287.         this.point2=point2;
  288.     }
  289. }
  290. public class Geometry {
  291.     public static int direction(Line someLine,Point somePoint{
  292.         //returns -1 if left of line, 1 if right, 0 of on line
  293.         int D = (someLine.point2.x-someLine.point1.x)*(somePoint.y-someLine.point1.y)
  294.                 -(someLine.point2.y-someLine.point1.y)*(somePoint.x-someLine.point1.x);
  295.         if (D>0)
  296.             return -1;
  297.         else if (D<0)
  298.             return 1;
  299.         else
  300.             return 0;
  301.     }
  302.     public static double scalar(Line line1,Line line2){
  303.         //line1 point1 = line2 point2
  304.         int xOffset = -line1.point1.x;
  305.         int yOffset = -line1.point1.y;
  306.  
  307.         return (line1.point2.x+xOffset)*(line2.point2.x+xOffset)
  308.                 +(line1.point2.y+yOffset)*(line2.point2.y+yOffset);
  309.     }
  310.  
  311.     public static double cardinality(Line line){
  312.         return Math.sqrt(Math.pow(line.point1.x-line.point2.x,2)+Math.pow(line.point1.y-line.point2.y,2));
  313.     }
  314.     public static double angle(Line line1,Line line2){
  315.         //returns angle between vectors line1 and line2
  316.         //lines are vectors which have common point!
  317.  
  318.         return Math.acos(scalar(line1,line2)/(cardinality(line1)*cardinality(line2)));
  319.     }
  320.  
  321.     public static Point lineIntersection(Point A, Point B, Point C, Point D)
  322.     {
  323.         // Line AB represented as a1x + b1y = c1
  324.         double a1 = B.y - A.y;
  325.         double b1 = A.x - B.x;
  326.         double c1 = a1*(A.x) + b1*(A.y);
  327.        
  328.         // Line CD represented as a2x + b2y = c2
  329.         double a2 = D.y - C.y;
  330.         double b2 = C.x - D.x;
  331.         double c2 = a2*(C.x)+ b2*(C.y);
  332.        
  333.         double determinant = a1*b2 - a2*b1;
  334.        
  335.         if (determinant == 0)
  336.         {
  337.             // The lines are parallel. This is simplified
  338.             // by returning a pair of FLT_MAX
  339.             return new Point(Double.MAX_VALUE, Double.MAX_VALUE);
  340.         }
  341.         else
  342.         {
  343.             double x = (b2*c1 - b1*c2)/determinant;
  344.             double y = (a1*c2 - a2*c1)/determinant;
  345.             if(Math.min(A.X,B.X)<=x<=Math.max(A.X,B.X) && Math.min(A.Y,B.Y)<=y<=Math.max(A.Y,B.Y)
  346.             && Math.min(C.X,D.X)<=x<=Math.max(C.X,D.X) && Math.min(C.Y,D.Y)<=y<=Math.max(C.Y,D.Y)) //ako lezhi presekot na dvete otsecki
  347.             return new Point(x, y);
  348.             else
  349.             return new Point(Double.MAX_VALUE, Double.MAX_VALUE);
  350.         }
  351.     }
  352.  
  353. //CONVEX HULL GRAHAM
  354.  
  355. import java.awt.Point;
  356. import java.util.*;
  357.  
  358. /**
  359.  *
  360.  */
  361. public final class GrahamScan {
  362.  
  363.     /**
  364.      * An enum denoting a directional-turn between 3 points (vectors).
  365.      */
  366.     protected static enum Turn { CLOCKWISE, COUNTER_CLOCKWISE, COLLINEAR }
  367.  
  368.     /**
  369.      * Returns true iff all points in <code>points</code> are collinear.
  370.      *
  371.      * @param points the list of points.
  372.      * @return       true iff all points in <code>points</code> are collinear.
  373.      */
  374.     protected static boolean areAllCollinear(List<Point> points) {
  375.  
  376.         if(points.size() < 2) {
  377.             return true;
  378.         }
  379.  
  380.         final Point a = points.get(0);
  381.         final Point b = points.get(1);
  382.  
  383.         for(int i = 2; i < points.size(); i++) {
  384.  
  385.             Point c = points.get(i);
  386.  
  387.             if(getTurn(a, b, c) != Turn.COLLINEAR) {
  388.                 return false;
  389.             }
  390.         }
  391.  
  392.         return true;
  393.     }
  394.  
  395.     /**
  396.      * Returns the convex hull of the points created from <code>xs</code>
  397.      * and <code>ys</code>. Note that the first and last point in the returned
  398.      * <code>List&lt;java.awt.Point&gt;</code> are the same point.
  399.      *
  400.      * @param xs the x coordinates.
  401.      * @param ys the y coordinates.
  402.      * @return   the convex hull of the points created from <code>xs</code>
  403.      *           and <code>ys</code>.
  404.      * @throws IllegalArgumentException if <code>xs</code> and <code>ys</code>
  405.      *                                  don't have the same size, if all points
  406.      *                                  are collinear or if there are less than
  407.      *                                  3 unique points present.
  408.      */
  409.     public static List<Point> getConvexHull(int[] xs, int[] ys) throws IllegalArgumentException {
  410.  
  411.         if(xs.length != ys.length) {
  412.             throw new IllegalArgumentException("xs and ys don't have the same size");
  413.         }
  414.  
  415.         List<Point> points = new ArrayList<Point>();
  416.  
  417.         for(int i = 0; i < xs.length; i++) {
  418.             points.add(new Point(xs[i], ys[i]));
  419.         }
  420.  
  421.         return getConvexHull(points);
  422.     }
  423.  
  424.     /**
  425.      * Returns the convex hull of the points created from the list
  426.      * <code>points</code>. Note that the first and last point in the
  427.      * returned <code>List&lt;java.awt.Point&gt;</code> are the same
  428.      * point.
  429.      *
  430.      * @param points the list of points.
  431.      * @return       the convex hull of the points created from the list
  432.      *               <code>points</code>.
  433.      * @throws IllegalArgumentException if all points are collinear or if there
  434.      *                                  are less than 3 unique points present.
  435.      */
  436.     public static List<Point> getConvexHull(List<Point> points) throws IllegalArgumentException {
  437.  
  438.         List<Point> sorted = new ArrayList<Point>(getSortedPointSet(points));
  439.  
  440.         if(sorted.size() < 3) {
  441.             throw new IllegalArgumentException("can only create a convex hull of 3 or more unique points");
  442.         }
  443.  
  444.         if(areAllCollinear(sorted)) {
  445.             throw new IllegalArgumentException("cannot create a convex hull from collinear points");
  446.         }
  447.  
  448.         Stack<Point> stack = new Stack<Point>();
  449.         stack.push(sorted.get(0));
  450.         stack.push(sorted.get(1));
  451.  
  452.         for (int i = 2; i < sorted.size(); i++) {
  453.  
  454.             Point head = sorted.get(i);
  455.             Point middle = stack.pop();
  456.             Point tail = stack.peek();
  457.  
  458.             Turn turn = getTurn(tail, middle, head);
  459.  
  460.             switch(turn) {
  461.                 case COUNTER_CLOCKWISE:
  462.                     stack.push(middle);
  463.                     stack.push(head);
  464.                     break;
  465.                 case CLOCKWISE:
  466.                     i--;
  467.                     break;
  468.                 case COLLINEAR:
  469.                     stack.push(head);
  470.                     break;
  471.             }
  472.         }
  473.  
  474.         // close the hull
  475.         stack.push(sorted.get(0));
  476.  
  477.         return new ArrayList<Point>(stack);
  478.     }
  479.  
  480.     /**
  481.      * Returns the points with the lowest y coordinate. In case more than 1 such
  482.      * point exists, the one with the lowest x coordinate is returned.
  483.      *
  484.      * @param points the list of points to return the lowest point from.
  485.      * @return       the points with the lowest y coordinate. In case more than
  486.      *               1 such point exists, the one with the lowest x coordinate
  487.      *               is returned.
  488.      */
  489.     protected static Point getLowestPoint(List<Point> points) {
  490.  
  491.         Point lowest = points.get(0);
  492.  
  493.         for(int i = 1; i < points.size(); i++) {
  494.  
  495.             Point temp = points.get(i);
  496.  
  497.             if(temp.y < lowest.y || (temp.y == lowest.y && temp.x < lowest.x)) {
  498.                 lowest = temp;
  499.             }
  500.         }
  501.  
  502.         return lowest;
  503.     }
  504.  
  505.     /**
  506.      * Returns a sorted set of points from the list <code>points</code>. The
  507.      * set of points are sorted in increasing order of the angle they and the
  508.      * lowest point <tt>P</tt> make with the x-axis. If tow (or more) points
  509.      * form the same angle towards <tt>P</tt>, the one closest to <tt>P</tt>
  510.      * comes first.
  511.      *
  512.      * @param points the list of points to sort.
  513.      * @return       a sorted set of points from the list <code>points</code>.
  514.      * @see GrahamScan#getLowestPoint(java.util.List)
  515.      */
  516.     protected static Set<Point> getSortedPointSet(List<Point> points) {
  517.  
  518.         final Point lowest = getLowestPoint(points);
  519.  
  520.         TreeSet<Point> set = new TreeSet<Point>(new Comparator<Point>() {
  521.             @Override
  522.             public int compare(Point a, Point b) {
  523.  
  524.                 if(a == b || a.equals(b)) {
  525.                     return 0;
  526.                 }
  527.  
  528.                 // use longs to guard against int-underflow
  529.                 double thetaA = Math.atan2((long)a.y - lowest.y, (long)a.x - lowest.x);
  530.                 double thetaB = Math.atan2((long)b.y - lowest.y, (long)b.x - lowest.x);
  531.  
  532.                 if(thetaA < thetaB) {
  533.                     return -1;
  534.                 }
  535.                 else if(thetaA > thetaB) {
  536.                     return 1;
  537.                 }
  538.                 else {
  539.                     // collinear with the 'lowest' point, let the point closest to it come first
  540.  
  541.                     // use longs to guard against int-over/underflow
  542.                     double distanceA = Math.sqrt((((long)lowest.x - a.x) * ((long)lowest.x - a.x)) +
  543.                                                 (((long)lowest.y - a.y) * ((long)lowest.y - a.y)));
  544.                     double distanceB = Math.sqrt((((long)lowest.x - b.x) * ((long)lowest.x - b.x)) +
  545.                                                 (((long)lowest.y - b.y) * ((long)lowest.y - b.y)));
  546.  
  547.                     if(distanceA < distanceB) {
  548.                         return -1;
  549.                     }
  550.                     else {
  551.                         return 1;
  552.                     }
  553.                 }
  554.             }
  555.         });
  556.  
  557.         set.addAll(points);
  558.  
  559.         return set;
  560.     }
  561.  
  562.     /**
  563.      * Returns the GrahamScan#Turn formed by traversing through the
  564.      * ordered points <code>a</code>, <code>b</code> and <code>c</code>.
  565.      * More specifically, the cross product <tt>C</tt> between the
  566.      * 3 points (vectors) is calculated:
  567.      *
  568.      * <tt>(b.x-a.x * c.y-a.y) - (b.y-a.y * c.x-a.x)</tt>
  569.      *
  570.      * and if <tt>C</tt> is less than 0, the turn is CLOCKWISE, if
  571.      * <tt>C</tt> is more than 0, the turn is COUNTER_CLOCKWISE, else
  572.      * the three points are COLLINEAR.
  573.      *
  574.      * @param a the starting point.
  575.      * @param b the second point.
  576.      * @param c the end point.
  577.      * @return the GrahamScan#Turn formed by traversing through the
  578.      *         ordered points <code>a</code>, <code>b</code> and
  579.      *         <code>c</code>.
  580.      */
  581.     protected static Turn getTurn(Point a, Point b, Point c) {
  582.  
  583.         // use longs to guard against int-over/underflow
  584.         long crossProduct = (((long)b.x - a.x) * ((long)c.y - a.y)) -
  585.                             (((long)b.y - a.y) * ((long)c.x - a.x));
  586.  
  587.         if(crossProduct > 0) {
  588.             return Turn.COUNTER_CLOCKWISE;
  589.         }
  590.         else if(crossProduct < 0) {
  591.             return Turn.CLOCKWISE;
  592.         }
  593.         else {
  594.             return Turn.COLLINEAR;
  595.         }
  596.     }
  597. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement