我要做的是解决一个关于切割钢筋的问题,用户会被问到他有多少根钢筋和长度,他要切割多少根钢筋和长度,然后程序必须计算在用户知道组合之后,应该给出条形的残留物和所有可能的切割组合,就像根据条形的残留物对切割进行“排名”一样。
例如:
Number of bars: 3
Lenght of bar 1: 10
Length of bar 2: 20
Length of bar 3: 30
Number of cuts: 4
Length of cut 1: 5
Length of cut 2: 5
Length of cut 3: 15
Length of cut 4: 20
所以可能的削减组合是:
Combination 1:
Cuts in bar 1: 5, 5 Residue bar 1: 0
Cuts in bar 2: 20 Residue bar 2: 0
Cuts in bar 3: 15 Residue bar 3: 15
Combination 2:
Cuts in bar 1: 5, 5 Residue: 0
Cuts in bar 2: 15 Residue: 5
Cuts in bar 3: 20 Residue: 10
Combination 3:
Cuts in bar 1: 0 Residue: 10
Cuts in bar 2: 5, 15 Residue: 0
Cuts in bar 3: 5, 20 Residue: 5
Combination 4:
Cuts in bar 1: 0 Residue: 10
Cuts in bar 2: 15 Residue: 5
Cuts in bar 3: 20, 5, 5 Residue: 0
到目前为止,我有这段代码,但是在显示组合时出现了一些错误:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int s, n=0, cont=1, m, i, j, q, a, z;
System.out.print("Number of bars to be cut : ");
s = scan.nextInt();
int b[] = new int[s];
do{
System.out.print("Bar's length " + cont + ": ");
b[n] = scan.nextInt();
n++;
cont++;
}while (n<s);
System.out.print("Number of pieces to be cut: ");
m = scan.nextInt();
int p[] = new int[m];
n=0;
cont=1;
do{
System.out.print("Length of the piece " + cont + ": ");
p[n] = scan.nextInt();
n++;
cont++;
}while (n<m);
int bars[][] = new int[s][s];
int pieces[][] = new int[m][m];
for (n=0; n<s; n++){
q=n;
for (cont=0; cont<s; cont++){
bars[n][q] = b[cont];
q++;
if (q>=s){
q = q - s;
}
}
}
for (n=0; n<m; n++){
q=n;
for (cont=0; cont<m; cont++){
pieces[n][q] = p[cont];
q++;
if (q>=m){
q = q - m;
}
}
}
int auxb[][] = new int[s][s];
int auxp[][] = new int[m][m];
int cpb[][]= new int [100][100];
for (i=0; i<s; i++){
for (j=0; j<m; j++){
for(q=0; q<s; q++){
auxb[i][q] = bars[i][q];
}
for(q=0; q<m; q++){
auxp[j][q] = pieces[j][q];
}
q=0;
for (n=0;n<s;n++){
for (cont=0;cont<m;cont++){
if (bars[i][n]>=pieces[j][cont] && pieces[j][cont]!=0){
bars[i][n] = (bars[i][n] - pieces[j][cont]);
cpb[n][q]=pieces[j][cont];
pieces[j][cont]=0;
q++;
}
}
}
q=0;
while(q<m && pieces[j][q]==0){
q++;
}
if (q==m){
a=1;
z=0;
System.out.print("Probability " + i + "," + j + " \n");
for (q=0; q<s; q++){
System.out.print("Residue of bar " + a + " es: " + bars[i][q] + ", with cuts of ");
while (cpb[q][z]!=0){
System.out.print(cpb[q][z] + ", ");
z++;
}
System.out.print("\n");
a++;
}
System.out.print("\n");
}
else
System.out.print("It's not possible to make those cuts \n");
for(q=0; q<s; q++){
bars[i][q] = auxb[i][q];
}
for(q=0; q<m; q++){
pieces[j][q] = auxp[j][q];
}
}
}
}
我怎样才能使它起作用?谢谢