码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1002 A+B for Polynomials

时间:2018-08-28 23:51:30      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:stream   bin   double   output   problem   +=   each   题目   min   

题目描述

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:

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???? (i=1,2,?,K) are the exponents and coefficients, respectively. It is given that 1K10,0N?K??<?<N?2??<N?1??1000.

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

题目求解

这道题不难,除了题目所提示的,还需要注意的是,两个多项式求和以后,系数和为0的项。

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<algorithm>
 4 #include<map>
 5 #include<iomanip>
 6 
 7 using namespace std;
 8 
 9 int m[1002] = {0};
10 map<int, double> mm;
11 
12 int main(){
13     int k;  //k number of nonzero terms
14     int n;
15     double a;   //n is exponents, a is coefficients
16     cin>>k;
17     for(int i=0;i<k;i++){
18         cin>>n>>a;
19         if(m[n]==0){
20             m[n] = 1;
21             m[1001] += 1;
22             mm[n] = a;
23         }
24         else{
25             mm[n] += a;
26         }
27     }
28     cin>>k;
29     for(int i=0;i<k;i++){
30         cin>>n>>a;
31         if(m[n]==0){
32             m[n] = 1;
33             m[1001] += 1;
34             mm[n] = a;
35         }
36         else{
37             mm[n] += a;
38         }
39     }
40     for(int i=1000;i>=0;i--){
41         if(m[i]!=0&&mm[i]==0.0){
42             m[1001]--;
43         }
44     }
45     cout<<m[1001];
46     for(int i=1000;i>=0;i--){
47         if(m[i]!=0&&mm[i]!=0.0){
48             cout<<" "<<i<<" "<<fixed<<setprecision(1)<<mm[i];
49         }
50     }
51     cout<<endl;
52     return 0;
53 }

 

PAT1002 A+B for Polynomials

标签:stream   bin   double   output   problem   +=   each   题目   min   

原文地址:https://www.cnblogs.com/sgatbl/p/9551367.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!