- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 143 lines of Java from the credited upstream file ccc98s4.java.
- The implementation visibly relies on sequence storage.
- 9 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12345678910111213 14import java.awt.*;15import hsa.*;16 17public class P4Lottery18{19 static Console c;20 21 public static void main (String [] args)22 {23 c = new Console ();24 25 TextInputFile fi = new TextInputFile ("lottery.in");26 TextOutputFile fo = new TextOutputFile ("lottery.out");27 int n, x;28 String s;29 30 n = fi.readInt ();31 for (int i = 1 ; i <= n ; i++)32 {33 s = fi.readLine ();34 35 36 x = 0;37 while (x < s.length ())38 {39 while (x < s.length () && s.charAt (x) != 'X')40 x++;41 if (x < s.length ())42 {43 s = left (s, x);44 s = right (s, x + 1);45 }46 x = x + 2; 47 }48 49 50 x = 0;51 while (x < s.length ())52 {53 while (x < s.length () && !(s.charAt (x) == '+' || s.charAt (x) == '-'))54 x++;55 if (x < s.length ())56 {57 s = left (s, x);58 s = right (s, x + 1);59 }60 x = x + 2; 61 }62 c.println (s.substring (1, s.length () - 1));63 c.println ("");64 fo.println (s.substring (1, s.length () - 1));65 fo.println ("");66 }67 fi.close ();68 fo.close ();69 }70 71 72 73 74 75 76 77 78 79 public static String left (String s, int x)80 {81 x = x - 2;82 if (s.charAt (x) == ')')83 {84 int count = 1;85 x--;86 while (count != 0)87 {88 if (s.charAt (x) == ')')89 count++;90 else if (s.charAt (x) == '(')91 count--;92 x--;93 }94 }95 else96 {97 while (x >= 0 && s.charAt (x) != ' ')98 x--;99 }100 if (x == -1)101 s = "(" + s;102 else103 s = s.substring (0, x + 1) + "(" + s.substring (x + 1);104 return s;105 }106 107 108 109 110 111 112 113 114 115 public static String right (String s, int x)116 {117 x = x + 2;118 if (s.charAt (x) == '(')119 {120 int count = 1;121 x++;122 while (count != 0)123 {124 if (s.charAt (x) == '(')125 count++;126 else if (s.charAt (x) == ')')127 count--;128 x++;129 }130 }131 else132 {133 while (x < s.length () && s.charAt (x) != ' ')134 x++;135 }136 if (x == s.length ())137 s = s + ")";138 else139 s = s.substring (0, x) + ")" + s.substring (x);140 return s;141 }142}143