【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


一定要審好題,第一遍做的時(shí)候看錯(cuò)了,以為前面的是指數(shù),后面的是系數(shù)。所以做成了這樣:

/*用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,因?yàn)檫@種一一對(duì)應(yīng)的問題應(yīng)用hash可以避免很多查詢(循環(huán))的問題。
但是簡(jiǎn)單的用hash存儲(chǔ) 項(xiàng)--->系數(shù) 的映射會(huì)出現(xiàn)最后無法排序輸出的問題。
最后折中一下,開一個(gè)struct存儲(chǔ)弄好的結(jié)構(gòu)體,直接用sort排序結(jié)構(gòu)體即可。
(什么鬼是系數(shù)從大到小的排序。。。怨念)

#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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容