PAT1002 A+B for Polynomials
Posted sgatbl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT1002 A+B for Polynomials相关的知识,希望对你有一定的参考价值。
题目描述
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 1≤K≤10,0≤N?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的主要内容,如果未能解决你的问题,请参考以下文章
PAT 甲级 1002 A+B for Polynomials
PAT 甲级1002 A+B for Polynomials (25)