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;
}

正確的答案是這樣的:
想用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;
}