|
| 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 final int INF = (int)1e9 + 7; |
| 57 | + |
| 58 | + static int N, M; |
| 59 | + static int[] a; |
| 60 | + static int[][] dp, idx; |
| 61 | + static int[] min; |
| 62 | + |
| 63 | + public static void main(String[] args) throws Exception { |
| 64 | + |
| 65 | + io = new IOController(); |
| 66 | + |
| 67 | + N = io.nextInt(); |
| 68 | + M = io.nextInt(); |
| 69 | + a = new int[N+1]; |
| 70 | + for(int i=1;i<=N;i++) a[i] = io.nextInt(); |
| 71 | + dp = new int[N+1][201]; |
| 72 | + idx = new int[N+1][201]; |
| 73 | + min = new int[N+1]; |
| 74 | + Arrays.fill(min, INF); |
| 75 | + min[0] = 0; |
| 76 | + |
| 77 | + for(int k=1;k<=200;k++) { |
| 78 | + int[] cnt = new int[M+1]; |
| 79 | + int count = 0; |
| 80 | + for(int s=1,e=1;e<=N;e++) { |
| 81 | + if(cnt[a[e]]++ == 0) count++; |
| 82 | + while(count > k) { |
| 83 | + if(--cnt[a[s++]] == 0) count--; |
| 84 | + } |
| 85 | + |
| 86 | + idx[e][k] = s; |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + for(int i=1;i<=N;i++) { |
| 91 | + for(int k=1;k<=200;k++) dp[i][k] = min[idx[i][k]-1] + k*k; |
| 92 | + for(int k=1;k<=200;k++) min[i] = Math.min(min[i], dp[i][k]); |
| 93 | + } |
| 94 | + |
| 95 | + io.write(min[N] + "\n"); |
| 96 | + |
| 97 | + io.close(); |
| 98 | + |
| 99 | + } |
| 100 | + |
| 101 | +} |
| 102 | +``` |
0 commit comments