This time, you are supposed to find A+B where A and B are two polynomials.
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N?1?? a?N?1???? N?2?? a?N?2???? ... N?K?? a?N?K????
where K is the number of nonzero terms in the polynomial, N?i?? and a?N?i???? (,) are the exponents and coefficients, respectively. It is given that 1,0.
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.
2 1 2.4 0 3.2
2 2 1.5 1 0.5
3 2 1.5 1 2.9 0 3.2
因为限定了指数小于1000,所以可以像哈希表一样,建立一个double数组ploy, 第i个位置存的就是指数为i的系数,然后两次读入数组将系数加起来。
设立cnt记录非零项个数,输入完毕后,从头遍历整个数组,当系数不为0时,cnt++,得到非零项的个数。
最后倒序输出多项式。
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]) } } }
PAT 1002 A+B for Polynomials Go语言题解及注意事项
原文:https://www.cnblogs.com/tao10203/p/13804661.html