|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +class IOController { |
| 6 | + BufferedReader br; |
| 7 | + BufferedWriter bw; |
| 8 | + StringTokenizer st; |
| 9 | + |
| 10 | + public IOController() { |
| 11 | + br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 13 | + st = new StringTokenizer(""); |
| 14 | + } |
| 15 | + |
| 16 | + String nextLine() throws Exception { |
| 17 | + String line = br.readLine(); |
| 18 | + st = new StringTokenizer(line); |
| 19 | + return line; |
| 20 | + } |
| 21 | + |
| 22 | + String nextToken() throws Exception { |
| 23 | + while (!st.hasMoreTokens()) nextLine(); |
| 24 | + return st.nextToken(); |
| 25 | + } |
| 26 | + |
| 27 | + int nextInt() throws Exception { |
| 28 | + return Integer.parseInt(nextToken()); |
| 29 | + } |
| 30 | + |
| 31 | + long nextLong() throws Exception { |
| 32 | + return Long.parseLong(nextToken()); |
| 33 | + } |
| 34 | + |
| 35 | + double nextDouble() throws Exception { |
| 36 | + return Double.parseDouble(nextToken()); |
| 37 | + } |
| 38 | + |
| 39 | + void close() throws Exception { |
| 40 | + bw.flush(); |
| 41 | + bw.close(); |
| 42 | + } |
| 43 | + |
| 44 | + void write(String content) throws Exception { |
| 45 | + bw.write(content); |
| 46 | + } |
| 47 | + |
| 48 | +} |
| 49 | + |
| 50 | +public class Main { |
| 51 | + |
| 52 | + static IOController io; |
| 53 | + |
| 54 | + // |
| 55 | + |
| 56 | + static int N; |
| 57 | + static long[] a; |
| 58 | + |
| 59 | + public static void main(String[] args) throws Exception { |
| 60 | + |
| 61 | + io = new IOController(); |
| 62 | + |
| 63 | + init(); |
| 64 | + solve(); |
| 65 | + |
| 66 | + io.close(); |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | + public static void init() throws Exception { |
| 71 | + |
| 72 | + N = io.nextInt(); |
| 73 | + a = new long[N]; |
| 74 | + for(int i=0;i<N;i++) a[i] = io.nextInt(); |
| 75 | + |
| 76 | + } |
| 77 | + |
| 78 | + static void solve() throws Exception { |
| 79 | + |
| 80 | + long s = 1, e = 1000000000, m1 = s + (e-s)/3, m2 = s + (e-s)*2/3; |
| 81 | + while(e-s > 5) { |
| 82 | + long res1 = getDist(m1); |
| 83 | + long res2 = getDist(m2); |
| 84 | + if(res1 > res2) s = m1; |
| 85 | + else e = m2; |
| 86 | + m1 = s + (e-s)/3; |
| 87 | + m2 = s + (e-s)*2/3; |
| 88 | + } |
| 89 | + long ans = Long.MAX_VALUE; |
| 90 | + for(int k=(int)s;k<=e;k++) ans = Math.min(ans, getDist(k)); |
| 91 | + io.write(ans + "\n"); |
| 92 | + |
| 93 | + } |
| 94 | + |
| 95 | + static long getDist(long x) { |
| 96 | + long res = 0; |
| 97 | + for(int i=1;i<N;i++) res += Math.abs(x*i - a[i]); |
| 98 | + return res; |
| 99 | + } |
| 100 | + |
| 101 | +} |
| 102 | +``` |
0 commit comments