- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 89 lines of Java from the credited upstream file ccc00s5.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 456789 101112 13import java.awt.*;14import hsa.*;15 16 17public class S5SheepandCoyotes18{19 static Console c;20 21 public static void main (String [] args)22 {23 c = new Console ();24 Point sheep [] = new Point [100];25 int eaten [] = new int [100]; 26 int n, ne, s;27 double d, m;28 boolean dup;29 30 TextInputFile fi = new TextInputFile ("sheep.in5");31 TextOutputFile fo = new TextOutputFile ("sheep.ou5");32 33 n = fi.readInt ();34 for (int i = 0 ; i < n ; i++)35 sheep [i] = new Point (fi.readDouble (), fi.readDouble ());36 ne = 0;37 for (double x = 0 ; x <= 1000.0 ; x = x + 0.01)38 {39 40 41 s = 0;42 m = 9999999.0;43 for (int i = 0 ; i < n ; i++)44 {45 d = distance (sheep [i], x);46 if (d < m)47 {48 m = d;49 s = i;50 }51 }52 53 54 dup = false;55 for (int j = 0 ; j < ne ; j++)56 if (s == eaten [j])57 dup = true;58 59 60 if (!dup)61 eaten [ne++] = s;62 }63 for (int j = 0 ; j < ne ; j++)64 {65 fo.println ("The sheep at (" + sheep [eaten [j]].x + ", " + sheep [eaten [j]].y + ") might be eaten.");66 c.println ("The sheep at (" + sheep [eaten [j]].x + ", " + sheep [eaten [j]].y + ") might be eaten.");67 }68 fi.close ();69 fo.close ();70 }71 72 73 public static double distance (Point p, double x)74 {75 return (p.x - x) * (p.x - x) + p.y * p.y;76 }77}78 79class Point80{81 public double x, y;82 public Point (double a, double b)83 {84 x = a;85 y = b;86 }87}88 89