20206-2 稀疏向量

稀疏向量

在这里插入图片描述
在这里插入图片描述

自己的代码(只有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);
			}
 
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值