- 这题可以用数组做,比较简单,我用了链表,锻炼自己对链表的操作
- 大致逻辑写出来可以得到前面的17分,后面几个测试点一开始我没过,后来想到了是关于0项的处理,就是两个exp相等,然后coef相加为0的情况。
- 注意有可能结果就是一个0多项式,只需要输出0就可以。
代码如下
#include <stdio.h>
#include <stdlib.h>
struct node{
int exp;
double coef;
node* next;
};
int cnt = 0;
void Attach(node* p,node* t)
{
while(p->next) p = p->next;
t->next = NULL;
p->next = t;
}
node* Add(node*p1,node* p2)
{
node *add,*t,*pre;
add = new node;
add->next = NULL;
pre = add;
p1 = p1->next;
p2 = p2->next;
while(p1 && p2){
int flag = 1;
t = new node;
if((p1->exp) > (p2->exp)){
t->exp = p1->exp;
t->coef = p1->coef;
p1 = p1->next;
}
else if((p2->exp) > (p1->exp)){
t->exp = p2->exp;
t->coef = p2->coef;
p2 = p2->next;
}
else{
t->exp = p1->exp;
t->coef = p1->coef + p2->coef;
if(t->coef==0)flag = 0;
p1 = p1->next;
p2 = p2->next;
}
if(flag){
t->next = NULL;
pre->next = t;
pre = t;
}
}
pre->next = p1?p1:p2;
return add;
}
void Print(node* p)
{
node* t;
p = p->next;
t = p;
while(t){
cnt++;
t = t->next;
}
printf("%d",cnt);
while(p){
printf(" %d %.1f",p->exp,p->coef);
p = p->next;
}
}
int main()
{
node *p1 = new node;
node *p2 = new node;
p1->next = p2->next = NULL;
int k1,k2;
int exp;
double coef;
scanf("%d",&k1);
for(int i=0;i<k1;i++){
scanf("%d%lf",&exp,&coef);
node *t = new node;
t->exp = exp;
t->coef = coef;
Attach(p1,t);
}
scanf("%d",&k2);
for(int i=0;i<k2;i++){
scanf("%d%lf",&exp,&coef);
node *t = new node;
t->exp = exp;
t->coef = coef;
Attach(p2,t);
}
node* add = Add(p1,p2);
Print(add);
return 0;
}