稀疏向量
自己的代码(只有60分)
import java.util.ArrayList;
import java.util.Scanner;
public class svector {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
Integer m = 0;
ArrayList<Integer> array = new ArrayList();
for (int i = 0; i < n; i++) {
array.add(0);
}
for (int i = 0; i < x; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
array.set(a-1, b);
}
for (int i = 0; i < y; i++) {
int c = sc.nextInt();
int d = sc.nextInt();
m += array.get(c-1)*d;
}
System.out.print(m);
}
}
);
}
for (int i = 0; i < x; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
array.set(a-1, b);
}
for (int i = 0; i < y; i++) {
int c = sc.nextInt();
int d = sc.nextInt();
m += array.get(c-1)*d;
}
System.out.print(m);
}
}
100分答案
import java.util.Scanner;
//第一次编译超时,90分;第二次满分
public class XiShuXiangLiang_3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//1. 接收数据 n, a, b
int n, a, b;
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
a = scan.nextInt();
b = scan.nextInt();
//2.1 接收向量 u 的稀疏表示数据
int[] u_index = new int[a];
int[] u_value = new int[a];
for(int i=0; i<a; i++){
u_index[i] = scan.nextInt();
u_value[i] = scan.nextInt();
}
//3. 初始化最后结果
long result = 0L;
int v_index, v_value;
int index_u = 0;
for(int i=0; i<b; i++){
v_index = scan.nextInt();
v_value = scan.nextInt();
while(index_u < a && i<a && index_u < b){
if(u_index[index_u] == v_index){
result += v_value * u_value[index_u];
index_u++;
break;
}else if(u_index[index_u] < v_index){
index_u++;
}else{
break;
}
}
}
//4. 输出结果
System.out.println(result);
}
}