PAT-1002. A+B for Polynomials(Map)

Today I studied the concept of Map in Java.

In <Thinking in Java> Map is described as : a group of key-value object pairs, allowing you to look up a value using a key. The ability to map objects to other objects can be an immensely powerful way to solve programming problems.

So the question is to add two polynomials. The format is like this:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:K N1 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.

Sample Input

2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output
3 2 1.5 1 2.9 0 3.2

I think to define a object of Map<Integer, Double> can solve this problem.

the code

package acm;


import java.util.HashMap;
import java.util.Scanner;


public class a1002 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		HashMap<Integer, Double> map = new HashMap<Integer, Double>();
		
		int nNum = sc.nextInt();
		
		for(int i = 0; i < nNum; i ++)
		{
			map.put(sc.nextInt(), sc.nextDouble());
			
		}
		nNum = sc.nextInt();
		for(int i = 0; i < nNum; i ++)
		{
			int index = sc.nextInt();
			double dval = sc.nextDouble();
			if(map.containsKey(index))
				map.put(index,  dval + map.get(index));
			else 
				map.put(index,  dval);
			if(map.get(index) == 0.0)
				map.remove(index);
		}
		
		System.out.print(map.size() + " ");
		Object[] list = map.keySet().toArray();
		for(int i = list.length-1; i >= 0; i --)
		{
			
			int nKey = (Integer)list[i];
			System.out.print(nKey + " ");
			System.out.format("%.1f", map.get(nKey));
			if(i != 0)
				System.out.print(" ");
		}
		sc.close();

	}

}

The problems I encountered were:

1. before we get an object from map, we must check if the key is in map using method of map.containKey(int );

2. It seems that it is a little complex to print the map value, especially by decrease order. Maybe I did not find a simple way.

But if we just print the values by normal order, it will be more convenient  :

for(Integer key : map.keySet())
{
       System.out.print(map.get(key));
}

The other problem confused me is that : java program takes more time and space to solve the same problem compared with c++.

What is more, I usually cannot pass the test case by java even some simple problem.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值