- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 186 lines of Java from the credited upstream file ccc10s3.java.
- The implementation visibly relies on sequence storage.
- 11 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234567891011121314151617181920212223242526272829303132333435 36 37import java.awt.*;38import hsa.*;39 40public class S32010v341{42 43 public static int h, k;44 public static int[] house;45 46 public static void main (String[] args)47 {48 TextInputFile c;49 c = new TextInputFile ("s3.1.in");50 int diameter, x, high, low;51 52 53 h = c.readInt ();54 house = new int [h];55 for (int i = 0 ; i < h ; i++)56 house [i] = c.readInt ();57 k = c.readInt ();58 59 if (k >= h)60 System.out.println (0);61 else62 {63 sortHouses ();64 shiftHouses ();65 66 67 diameter = 1000000 / k;68 high = diameter;69 low = 0;70 x = check (diameter);71 while (x != 0)72 {73 if (x < 0)74 low = diameter;75 else76 high = diameter;77 diameter = (low + high) / 2;78 x = check (diameter);79 }80 81 82 83 x = check (diameter);84 while (x == 0)85 {86 diameter--;87 x = check (diameter);88 }89 System.out.println ((float) (diameter + 1) / 2);90 }91 }92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 public static int check (int diameter)108 {109 int i = 0;110 int start;111 int count, startPlace, houseCount;112 113 start = 0;114 i = start;115 count = 0;116 while (i < h)117 {118 startPlace = house [i];119 while (i < h && startPlace + diameter > house [i])120 i++;121 count++;122 if (i < h && startPlace + diameter == house [i])123 i++;124 }125 if (count < k)126 return 1;127 else if (count > k)128 return -1;129 else130 return 0;131 }132 133 134 public static void sortHouses ()135 {136 int hold, j;137 for (int i = 1 ; i < h ; i++)138 {139 hold = house [i];140 j = i - 1;141 while (j >= 0 && hold < house [j])142 {143 house [j + 1] = house [j];144 j--;145 }146 house [j + 1] = hold;147 }148 }149 150 151 152 153 154 public static void shiftHouses ()155 {156 157 int largestGap = 1000000 - house [h - 1] + house [0];158 int largestI = 0;159 int hold;160 for (int i = 1 ; i < h ; i++)161 if (house [i] - house [i - 1] > largestGap)162 {163 largestGap = house [i] - house [i - 1];164 largestI = i;165 }166 167 168 hold = house [largestI];169 for (int i = 0 ; i < largestI ; i++)170 house [i] = house [i] + (1000000 - hold);171 for (int i = largestI ; i < h ; i++)172 house [i] = house [i] - hold;173 174 175 sortHouses ();176 }177 178 179 public static void print ()180 {181 for (int i = 0 ; i < h ; i++)182 System.out.println (house [i]);183 }184}185 186