Skip to content

Commit 3dec29c

Browse files
authored
Merge pull request #277 from AlgorithmWithGod/khj20006
[20250320] BOJ / G2 / Snakes / 권혁준
2 parents 2d6d6b2 + c81004f commit 3dec29c

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
```java
2+
3+
import java.util.*;
4+
import java.io.*;
5+
6+
class Main {
7+
8+
// IO field
9+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
11+
static StringTokenizer st = new StringTokenizer("");
12+
13+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
14+
static String nextToken() throws Exception {
15+
if(!st.hasMoreTokens()) nextLine();
16+
return st.nextToken();
17+
}
18+
static int nextInt() throws Exception { return Integer.parseInt(nextToken()); }
19+
static long nextLong() throws Exception { return Long.parseLong(nextToken()); }
20+
static double nextDouble() throws Exception { return Double.parseDouble(nextToken()); }
21+
static void bwEnd() throws Exception {bw.flush();bw.close();}
22+
23+
// Additional field
24+
25+
static int N, K;
26+
static int[] A, sum;
27+
static long[][] dp, S;
28+
static final long INF = (long)1e18;
29+
30+
public static void main(String[] args) throws Exception {
31+
32+
ready();
33+
solve();
34+
35+
bwEnd();
36+
37+
}
38+
39+
static void ready() throws Exception{
40+
41+
N = nextInt();
42+
K = nextInt();
43+
A = new int[N+1];
44+
sum = new int[N+1];
45+
for(int i=1;i<=N;i++) {
46+
A[i] = nextInt();
47+
sum[i] = sum[i-1] + A[i];
48+
}
49+
dp = new long[N+1][K+1];
50+
S = new long[N+1][K+1];
51+
for(int i=0;i<=N;i++) Arrays.fill(dp[i], INF);
52+
dp[0][0] = 0;
53+
54+
}
55+
56+
static void solve() throws Exception{
57+
58+
long ans = INF;
59+
dp[1][1] = 0;
60+
long temp = 0;
61+
for(int i=1;i<=N;i++) {
62+
temp = Math.max(temp, A[i]);
63+
dp[i][0] = temp*i - sum[i];
64+
}
65+
for(int i=2;i<=N;i++) {
66+
for(int k=1;k<=Math.min(i,K);k++) {
67+
int max = A[i];
68+
for(int j=i-1;j>=k;j--) {
69+
if(dp[j][k-1] == INF) continue;
70+
dp[i][k] = Math.min(dp[i][k], dp[j][k-1] + (long)max * (i-j) - (sum[i]-sum[j]));
71+
max = Math.max(max, A[j]);
72+
}
73+
if(i == N) ans = Math.min(ans, dp[i][k]);
74+
}
75+
}
76+
bw.write(ans + "\n");
77+
78+
}
79+
80+
}
81+
82+
```

0 commit comments

Comments
 (0)