【PAT A1002】 1002 A+B for Polynomials (25)(25 分)

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


一定要审好题,第一遍做的时候看错了,以为前面的是指数,后面的是系数。所以做成了这样:

/*用stl,float为key,int为value,由于map是红黑树所以自带排序*/
#include 
#include 
#include 
#define maxn 1010
using namespace std;

map poly;
map::iterator it;
int main() {
    int m,n;
    int a;
    float b;
    scanf("%d",&m);
    while(m--){
        scanf("%d%f",&a,&b);
        poly.insert(make_pair(b,a));
    }
    scanf("%d",&n);
    while(n--){
        scanf("%d%f",&a,&b);
        if(poly.insert(make_pair(b,a)).second==false){
        poly[a]+=b;
        }
    }
    cout<second<<" "<first;
    }
    system("pause");
    return 0;
}
image.png

正确的答案是这样的:
想用hash,因为这种一一对应的问题应用hash可以避免很多查询(循环)的问题。
但是简单的用hash存储 项--->系数 的映射会出现最后无法排序输出的问题。
最后折中一下,开一个struct存储弄好的结构体,直接用sort排序结构体即可。
(什么鬼是系数从大到小的排序。。。怨念)

#include 
#include 
#include 
using namespace std;
#define maxn 1010
float h[maxn];
struct poly{
   int a;
   float b;
}po[maxn];
bool cmp(poly x,poly y){
   return x.a>y.a;
}
int main() {
   int m,n,a;
   float b;
   int sum=0;
   scanf("%d",&m);
   while(m--){
   scanf("%d%f",&a,&b);
       h[a]=b;
   }
   scanf("%d",&n);
   while(n--){
       scanf("%d%f",&a,&b);
       if(h[a]!=0){
           h[a]+=b;
       }
       else{
           h[a]=b;
       }
   }
   for(int i=0;i

你可能感兴趣的:(【PAT A1002】 1002 A+B for Polynomials (25)(25 分))