首页 > 编程语言 > 详细

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

时间:2020-10-12 19:59:56      阅读:35      评论:0      收藏:0      [点我收藏+]

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:

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.

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])
		}
	}
}

  

 

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

原文:https://www.cnblogs.com/tao10203/p/13804661.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!