1009 Product of Polynomials (25 分) Java

解题思路:

这题和1002有点像,但是不是+,而是乘。也考虑用map来存储。exp(指数)和coe(系数)刚好组成<Integer, Double>的键值对,指数Key是不能重复的,刚好符合多项式指数的特性,更新还方便。只是最后用TreeMap来存储结果,需要在初始化TreeMap的时候倒序排序,可以用Comparator.reverseOrder()。


import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Comparator;
public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int k1 = input.nextInt();
		Map<Integer, Double> map1 = new HashMap<>();
		Map<Integer, Double> map2 = new TreeMap<>(Comparator.reverseOrder());
		for(int i=0; i<k1; i++) {
			int exp = input.nextInt();
			double coe = input.nextDouble();
			if(!map1.containsKey(exp))
				map1.put(exp, coe);
			else
				map1.put(exp, map1.get(exp) + coe);
		}
		Set<Entry<Integer, Double>> entrySet = map1.entrySet();
		int k2 = input.nextInt();
		for(int i=0; i<k2; i++) {
			int exp = input.nextInt();
			double coe = input.nextDouble();
			for(Entry<Integer, Double> entry: entrySet) {
				int newExp = entry.getKey() + exp;
				double newCoe = entry.getValue() * coe;
				if(!map2.containsKey(newExp))
					map2.put(newExp, newCoe);
				else
					map2.put(newExp, map2.get(newExp) + newCoe);
			}
		}
		int size = map2.size();
		entrySet = map2.entrySet();
		String output = "";
		for(Entry<Integer, Double> entry: entrySet){
			if(entry.getValue().equals(Double.valueOf(0)))
				size--;
			else
				output += String.format(" %d %.1f", entry.getKey(), entry.getValue());
		}
		System.out.print(size + output);
		input.close();
	}
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值