Im not used to code in java so i need help to translate this code to from c++ to java in a functional way. I tried it myself but the result was always 0. It is the CUTTING STICKS PROBLEM.
#include <iostream>
#define MAXINT 2147483647
#define NCUTS 50
using namespace std;
int main() {
int len;
int nc;
int arr[NCUTS+2];
int dp[NCUTS+2][NCUTS+2];
while((cin >> len) && (len != 0)) {
cin >> nc;
for(int i=0; i<nc; i++) {
cin >> arr[i+1];
}
arr[0] = 0;
nc++;
arr[nc] = len;
for(int i=0; i<=NCUTS+1; i++) {
for(int j=0;j<=NCUTS+1;j++) {
dp[i][j] = MAXINT;
}
}
for(int i=0; i<=nc; i++) {
dp[i][i] = 0;
dp[i][i+1] = 0;
开发者_如何学Go dp[i][i+2] = arr[i+2] - arr[i];
}
for(int k=3; k<=nc; k++) {
for(int i=0; i<=nc-k; i++) {
for(int j=i+1; j<=i+k-1; j++) {
if((dp[i][j] + dp[j][i+k] + arr[i+k] - arr[i]) < dp[i][i+k]) {
dp[i][i+k] = dp[i][j] + dp[j][i+k] + arr[i+k] - arr[i];
}
}
}
}
cout << "The minimum cutting is "<< dp[0][nc] << "." << endl;
}
}
I won't post the full translation, but some specific differences between C++ and Java that will be relevant here:
- You need to wrap everything in a class, such as
public class CuttingSticks
. - Replace
#define NAME value
with aprivate static final
, for example,private static final int NAME = value;
. MAXINT
is justInteger.MAX_VALUE
.- main must be defined as
public static void main(String[] args)
, even if you don't useargs
. - You can't use fixed-size arrays. You must allocate them. For example,
int[] arr = new int[NCUTS+2]
. There are no 2D arrays, only "arrays of arrays" (you need to allocate the outer array and then allocate another array for each inner array). Alternatively, manually write your own rectangular array. - Instead of
cin
, useSystem.in
. This is an InputStream. - Instead of
cout
, useSystem.out
. This is a PrintStream -- usually you will just useSystem.out.println
.
import java.io.*;
import java.util.*;
class MyClass {
static final int MAXINT = Integer.MAX_VALUE;
static final int NCUTS = 50;
public static void main (String [] args) throws IOException {
int len;
int nc;
int[] arr = new int[NCUTS+2];
int[][] dp = new int[NCUTS+2][NCUTS+2];
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while((len = Integer.parseInt(in.readLine())) != 0) {
nc = Integer.parseInt(in.readLine());
for(int i=0; i<nc; i++) {
arr[i+1] = Integer.parseInt(in.readLine());
}
arr[0] = 0;
nc++;
arr[nc] = len;
for(int i=0; i<=NCUTS+1; i++) {
for(int j=0;j<=NCUTS+1;j++) {
dp[i][j] = MAXINT;
}
}
for(int i=0; i<=nc; i++) {
dp[i][i] = 0;
dp[i][i+1] = 0;
dp[i][i+2] = arr[i+2] - arr[i];
}
for(int k=3; k<=nc; k++) {
for(int i=0; i<=nc-k; i++) {
for(int j=i+1; j<=i+k-1; j++) {
if((dp[i][j] + dp[j][i+k] + arr[i+k] - arr[i]) < dp[i][i+k]) {
dp[i][i+k] = dp[i][j] + dp[j][i+k] + arr[i+k] - arr[i];
}
}
}
}
System.out.println("The minimum cutting is " + dp[0][nc] + ".");
}
}
}
精彩评论