PAT 1002. A+B for Polynomials
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
代码如下(复杂的链表)
#include<iostream>
using namespace std;
struct node{
int exp;
double coe;
node* next;
};
int main(){
int N,cnt=0;
cin>>N;
node* l1=new node();
node* ptr1=l1;
for(int i=0;i<N;i++){
node *lnode=new node();
lnode->next=NULL;
cin>>lnode->exp>>lnode->coe;
ptr1->next=lnode;
ptr1=ptr1->next;
}
cin>>N;
node* l2=new node();
node* ptr2=l2;
for(int i=0;i<N;i++){
node *lnode=new node();
cin>>lnode->exp>>lnode->coe;
lnode->next=NULL;
ptr2->next=lnode;
ptr2=ptr2->next;
}
ptr1=l1->next; ptr2=l2->next;
node* l=new node(); node* ptr=l;
while(ptr1!=NULL&&ptr2!=NULL){
if(ptr1->exp>ptr2->exp){
if(ptr1->coe!=0) cnt++;
ptr->next=ptr1;
ptr=ptr->next;
ptr1=ptr1->next;
}
else if(ptr1->exp<ptr2->exp){
if(ptr2->coe!=0) cnt++;
ptr->next=ptr2;
ptr=ptr->next;
ptr2=ptr2->next;
}else{
ptr1->coe+=ptr2->coe;
if(ptr1->coe!=0) cnt++;
ptr->next=ptr1;
ptr=ptr->next;
ptr1=ptr1->next;
ptr2=ptr2->next;
}
}
while(ptr1!=NULL){
if(ptr1->coe!=0) cnt++;
ptr->next=ptr1;
ptr=ptr->next;
ptr1=ptr1->next;
}
while(ptr2!=NULL){
if(ptr2->coe!=0) cnt++;
ptr->next=ptr2;
ptr=ptr->next;
ptr2=ptr2->next;
}
ptr=l->next;
cout<<cnt;
while(ptr!=NULL){
if(ptr->coe!=0)
printf(" %d %.1f",ptr->exp,ptr->coe);
ptr=ptr->next;
}
}
分析
其实用其他容器都可以很好的解决这个问题,vector,map等等;下面附上我的另一种解法
代码如下
#include<iostream>
#include<map>
using namespace std;
int main(){
map<int,double> map1,map2;
int N,exp,cnt=0;
double coe;
cin>>N;
for(int i=0;i<N;i++){
cin>>exp>>coe;
map1[exp]=coe;
}
cin>>N;
for(int i=0;i<N;i++){
cin>>exp>>coe;
map2[exp]=coe;
}
auto p1=map1.begin();
for(;p1!=map1.end();p1++){
map2[p1->first]+=p1->second;
}
for(auto p2=map2.rbegin();p2!=map2.rend();p2++){
if(p2->second!=0)
cnt++;
}
cout<<cnt;
for(auto p2=map2.rbegin();p2!=map2.rend();p2++){
if(p2->second!=0)
printf(" %d %.1f",p2->first,p2->second);
}
}