PAT 1002 A+B for Polynomials (25)

来源:互联网 发布:python 读取文件名 编辑:程序博客网 时间:2024/05/29 13:20

  • 题目英文
  • 题目中文
    • 输入
    • 输出
    • 示例输入
    • 示例输出
  • 分析
  • 程序1
  • 程序2

题目英文

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

Input

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.

Output

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

题目中文

这一次,希望你可以计算出A+B,这次的A,B都是多项式。

输入

每个输入文件包含一个测试用例。每个测试用例占两行,每一行的信息类似如下多项式:k N1 aN1 N2 aN2 …NK aNK ,其中k是多项式中非0的项数, Ni和aNi是其中的典型的指数和系数。K将会是1到10之间的一个数,指数NK小于1000。

输出

对于每个测试用例你都应该在一行中输出A和B的加和。与输入的格式一致。注意在每一行末尾不可以有空格。请精确到数字后面的一位。

示例输入

2 1 2.4 0 3.2
2 2 1.5 1 0.5

示例输出

3 2 1.5 1 2.9 0 3.2

分析

从标准的数据来看,系统希望我们按照降幂来排列

程序1

分析,发现爱上了python,也不知道是否上机场地都支持python,但是单纯的先使用起来,毕竟高效简洁,其他关于python和c的对比我也没必要说,网络大把,此处喜欢用python。
看到这种多项式,想起了使用字典来记录相应幂的系数,然后可以用字典相加的算法计算了。
nnd 看到很多都不支持python,并且pat对python支持也很烂,哎,理想很丰满,现实很骨感,看来还得是c或者c++
下面的程序可以满足示例运行,但是不知道为什么无法通过测试,只好放一放了。。。。。。

import stringinput1 = raw_input()input2 = raw_input()array1 = input1.split()array2 = input2.split()print array1,array2dirt1 = {}dirt2 = {}for i in range(int(array1[0])):        dirt1[array1[2*i+1]] = array1[2*i+2]for i in range(int(array2[0])):        dirt2[array2[2*i+1]] = array2[2*i+2]dirttotal = dirt1.copy()for k,v in dirt2.items():        if k in dirt1.keys():                dirttotal[k] = string.atof(dirttotal[k]) + string.atof(v)        else:                dirttotal[k] = string.atof(v)result = sorted(dirttotal.items(),key = lambda e : e[0],reverse = True)print len(result),for item in result:        print item[0],        print item[1],print ''

程序2

还是回归到我比较熟悉的C上去吧,说熟悉,其实也不熟悉,呵呵
心得1:scanf后面再次scanf需要使用fflush清空stdin缓冲器
心得2:scanf的时候,数据需要严格执行,要么是int,要么是float,之前将后面的float给截断了用了int,导致了int无法正确识别,从而导致了scanf很快就退出了

原创粉丝点击