PAT A1002 A+B for Polynomials Go语言题解及注意事项

1002 A+B for Polynomials (25分)

This time, you are supposed to find A+B where A and B are two polynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

N1​​ aN1​​​​ N2​​ aN2​​​​ ... NK​​ aNK​​​​

where K is the number of nonzero terms in the polynomial, Ni​​ and aNi​​​​ (,) are the exponents and coefficients, respectively. It is given that 1,0.

Output Specification:

For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.

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

思路

因为限定了指数小于1000,所以可以像哈希表一样,建立一个double数组ploy, 第i个位置存的就是指数为i的系数,然后两次读入数组将系数加起来。

设立cnt记录非零项个数,输入完毕后,从头遍历整个数组,当系数不为0时,cnt++,得到非零项的个数。

最后倒序输出多项式。

 Solution

package main

import "fmt"

var (
	e int
	c float64
)

func main() {
	poly := make([]float64, 1010)
	n := 0
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&e, &c)
		poly[e] += c
	}
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&e, &c)
		poly[e] += c
	}
	cnt := 0
	for _, v := range poly {
		if v != 0 {
			cnt++
		}
	}
	fmt.Printf("%d", cnt)
	for i := len(poly) - 1; i >= 0; i-- {
		if poly[i] != 0 {
			fmt.Printf(" %v %.1f", i, poly[i])
		}
	}
}

  

 
posted @ 2020-10-12 19:10  tao10203  阅读(125)  评论(0)    收藏  举报