- 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
- 94 lines of Java from the credited upstream file ccc02s5.java.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 45 678910 11121314 151617 18import java.awt.*;19import hsa.*;20 21public class S5Bounce22{23 24 public static void main (String[] args)25 {26 double width, height, startx, starty, x, y, a, b;27 double slope;28 Console c = new Console ();29 30 TextInputFile fi = new TextInputFile ("ball5.in");31 TextOutputFile fo = new TextOutputFile ("ball5.out");32 int numwidth, numheight, k, bounce;33 boolean done;34 35 36 width = fi.readLong ();37 height = fi.readLong ();38 startx = fi.readLong ();39 starty = fi.readLong ();40 41 done = false;42 slope = starty / (width - startx);43 for (k = 1 ; k <= 1000000 && !done ; k++)44 {45 46 y = slope * ((k * width) - startx);47 48 x = (k * height) / slope + startx;49 50 51 numheight = (int) ((y - (height / 2)) / height) + 1;52 53 numwidth = (int) ((x - (width / 2)) / width) + 1;54 a = numheight * height;55 b = numwidth * width;56 57 if ((Math.abs (a - y) < 5) || (Math.abs (b - x) < 5))58 {59 60 61 if (Math.abs (a - y) < 5)62 if (a != y)63 bounce = k - 1 + (int) (y / height);64 else65 66 bounce = k - 1 + (int) (y / height) - 1;67 68 69 70 else71 if (b != x)72 bounce = k - 1 + (int) (x / width);73 else74 75 bounce = k - 1 + (int) (x / width) - 1;76 77 fo.println (bounce);78 c.println (bounce);79 done = true;80 }81 82 }83 if (!done)84 {85 fo.println ("0");86 c.println ("0");87 }88 fi.close ();89 fo.close ();90 }91}92 93 94