CCF稀疏向量-java-60分-运行错误
题目如下:
Java实现代码
import java.util.Scanner;
public class Main {
static int[] u;
static long sum = 0; //内积和
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int a = input.nextInt();
int b = input.nextInt();
u = new int[n];
for(int i = 0; i < a; i ++){
u[input.nextInt()-1] = input.nextInt();
}
for(int i = 0; i < b; i ++){
int x = input.nextInt();
int y = input.nextInt();
sum += y*u[x-1];
}
System.out.println(sum);
}
}
系统分数
二次修改
1.将数组更换为hashmap
2.将scanner类读数据更换为BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Reader {
static StringTokenizer token =new StringTokenizer("");
static BufferedReader reader =new BufferedReader (new InputStreamReader(System.in)) ;
static String nextLine() throws IOException {
return reader.readLine() ;
}
static String next() throws IOException {
while(!token.hasMoreTokens()) {
token =new StringTokenizer(reader.readLine()) ;
}
return token.nextToken() ;
}
static int nextInt() throws IOException {
return Integer.parseInt(next()) ;
}
static double nextDouble() throws IOException {
return Double.parseDouble(next()) ;
}
}
public class Main2 {
static long sum = 0;
public static void main(String[] args) throws IOException{
int n = Reader.nextInt() ;
int a = Reader.nextInt() ;
int b = Reader.nextInt() ;
HashMap<Integer,Integer> arr = new HashMap<>();
for(int i = 0; i < a; i++){
arr.put(Reader.nextInt(),Reader.nextInt());
}
for(int j = 0; j < b ; j++){
int index = Reader.nextInt();
int num = Reader.nextInt();
if(num!=0 && arr.containsKey(index))
sum += num*arr.get(index);
}
System.out.println(sum);
}
}
代码建议来自:https://blog.csdn.net/zzzlueng/article/details/108283249