我有以下代码。
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
public class Scalar {
public static void main(String args[]) throws Exception {
Scanner sc=new Scanner(new File("D:/GC/Scalar/A-small.in"));
int testcases=Integer.parseInt(sc.next());
System.out.println(testcases);
ArrayList<BigInteger> a=new ArrayList<BigInteger>();
ArrayList<BigInteger> b=new ArrayList<BigInteger>();
for(int j=0;j<2;j++){
int size=Integer.parseInt(sc.next());
System.out.println(size);
for(int i=0;i<size;i++)
{
a.add(sc.nextBigInteger());
}
for(int i=0;i<size;i++)
{
b.add(sc.nextBigInteger());
}
Collections.sort(a);
System.out.println(a.size());
System.out.println(a);
Collections.sort(b,Collections.reverseOrder());
System.out.println(b);
BigInteger sum;
for(int i=0;i<a.size();i++){
sum=a.get(i).multiply(b.get(i));
sum=sum.add(sum);
}
}
}
}
以及文本文件中的以下内容。
1000
3
1 -5 3
-2 1 4
5
5 4 3 1 2
1 1 0 1 0
7
677 463 -569 516 401 -998 882
890 588 959 909 948 -617 -655
8
-912 937 167 366 -222 -397 190 -216
354
这里我试图以相反的顺序对第一个数组和第二个数组进行排序,然后进行求和和乘积,这里我只采用了2个案例,上面输入的1000个是测试用例的总数,而单个数字行表示数组大小,并在我的程序中,以确保数组的大小匹配给定的大小,我打印大小,在第一种情况下,输入大小为3,我得到它正确,但在第二种情况,输入大小为5,但我得到的数字是8,下面是我得到的输出。
1000
3
3
[-5, 1, 3]
[4, 1, -2]
5
8
[-5, 1, 1, 2, 3, 3, 4, 5]
[4, 1, 1, 1, 1, 0, 0, -2]
请让我知道我哪里出错了。
由于
答案 0 :(得分:3)
这是问题所在:
ArrayList<BigInteger> a=new ArrayList<BigInteger>();
ArrayList<BigInteger> b=new ArrayList<BigInteger>();
for(int j=0;j<2;j++){
// Stuff
}
您正在为每个测试重复使用相同的列表 - 因此您要将第二个测试中的值添加到已包含第一个测试数据的列表中。
选项:
鉴于您没有逻辑希望将列表从一个测试保持到另一个,我只需将代码更改为:
for(int j = 0; j < 2; j++){
List<BigInteger> a = new ArrayList<BigInteger>();
List<BigInteger> b = new ArrayList<BigInteger>();
// Populate the lists, etc.
}
请注意,此也可以更轻松地将“读取大小,读取数据,将其排序”的整个操作提取到单独的方法中。
另外,我怀疑你要将你的循环改为:
for(int j = 0; j < testcases; j++) {
......否则你会在两次测试后停止。
如果您使用的是Java 7,则可以使用类型推断来简化ArrayList
创建:
List<BigInteger> a = new ArrayList<>();
...您甚至可以考虑将“读取n
号码”提取到一个单独的方法中,以便您的代码看起来像:
int size = Integer.parseInt(sc.next());
System.out.println(size);
List<BigInteger> a = readBigIntegers(sc, size);
List<BigInteger> b = readBigIntegers(sc, size);
// Now sort etc.
另请考虑使用Scanner.nextInt()
代替明确的Integer.parseInt
来电。