美文网首页
【PAT A1002】 1002 A+B for Polynom

【PAT A1002】 1002 A+B for Polynom

作者: AdmondGuo | 来源:发表于2018-06-27 13:24 被阅读0次

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<map>,float为key,int为value,由于map是红黑树所以自带排序*/
#include <iostream>
#include <map>
#include <cstdio>
#define maxn 1010
using namespace std;

map<float ,int> poly;
map<float ,int>::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<<poly.size()<<" ";
    for(it=poly.begin();it!=poly.end();it++){
        cout<<" "<<it->second<<" "<<it->first;
    }
    system("pause");
    return 0;
}
image.png

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

#include <iostream>
#include <cstdio>
#include <algorithm>
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<maxn;i++){
       if(h[i]!=0){
           po[sum].a=i;
           po[sum++].b=h[i];
       }
   }
   sort(po,po+sum,cmp);
   cout<<sum;
   for(int i=0;i<sum;i++){
       printf(" %d %.1f",po[i].a,po[i].b);
   }
   system("pause");
   return 0;
}

相关文章

网友评论

      本文标题:【PAT A1002】 1002 A+B for Polynom

      本文链接:https://www.haomeiwen.com/subject/bhdbyftx.html