File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+ import java.io.* ;
4+ public class Main {
5+ static BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
6+ static BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System . out));
7+ static StringTokenizer st;
8+ static int N ;
9+ static int [][] cost;
10+ static int [][] dp;
11+
12+ public static void main (String [] args ) throws Exception {
13+ N = Integer . parseInt(br. readLine());
14+ cost = new int [N + 1 ][3 ];
15+
16+ for (int i= 1 ; i<= N ;i++ ){
17+ st = new StringTokenizer (br. readLine());
18+ cost[i][0 ] = Integer . parseInt(st. nextToken());
19+ cost[i][1 ] = Integer . parseInt(st. nextToken());
20+ cost[i][2 ] = Integer . parseInt(st. nextToken());
21+ }
22+
23+ int min = Integer . MAX_VALUE ;
24+ for (int firstColor= 0 ; firstColor< 3 ; firstColor++ ){
25+ dp = new int [N + 1 ][3 ];
26+ dp[1 ][firstColor] = cost[1 ][firstColor];
27+ dp[1 ][(firstColor+ 1 )% 3 ] = 10000000 ;
28+ dp[1 ][(firstColor+ 2 )% 3 ] = 10000000 ;
29+
30+ for (int i= 2 ;i< N ;i++ ){
31+ for (int j = 0 ;j< 3 ;j++ ){
32+ dp[i][j] = Math . min(dp[i- 1 ][(j+ 1 )% 3 ] + cost[i][j], dp[i- 1 ][(j+ 2 )% 3 ] + cost[i][j]);
33+ }
34+ }
35+ dp[N ][(firstColor+ 1 )% 3 ] = Math . min(dp[N - 1 ][firstColor]+ cost[N ][(firstColor+ 1 )% 3 ], dp[N - 1 ][(firstColor+ 2 )% 3 ]+ cost[N ][(firstColor+ 1 )% 3 ]);
36+ dp[N ][(firstColor+ 2 )% 3 ] = Math . min(dp[N - 1 ][firstColor]+ cost[N ][(firstColor+ 2 )% 3 ], dp[N - 1 ][(firstColor+ 1 )% 3 ]+ cost[N ][(firstColor+ 2 )% 3 ]);
37+
38+ min = Math . min(min, dp[N ][(firstColor+ 1 )% 3 ]);
39+ min = Math . min(min, dp[N ][(firstColor+ 2 )% 3 ]);
40+ }
41+ bw. write(min+ " " );
42+ bw. close();
43+ }
44+ }
45+ ```
You can’t perform that action at this time.
0 commit comments