1.在下采用链表做,锻炼debug能力。不得不说,链表真是很容易出现各种bug,好在最后都调通了。
2.核心代码是Attach函数和Mult函数,Attach尤为关键。
3.刚开始交上去第一个测试点万年过不去,后来想到可能链表里面有系数为0的项,遂在printf里面改之,依然不对,想了好久想到了cnt计数也要考虑,coef不为0才计数。
AC代码如下
#include <stdio.h>
struct node{
int expon;
double coef;
node* next;
};
void Attach(node* p,node* t)
{
if(p->next==NULL){
t->next = NULL;
p->next = t;
}
else{
p = p->next;
while(p){
if(p->expon == t->expon){ //指数相同系数相加
p->coef += t->coef;
break;
}
else{
if(p->next){
if(p->next->expon < t->expon){
t->next = p->next;
p->next = t;
break;
}
else p = p->next;
}
else{ //p->next == NULL
t->next = NULL;
p->next = t;
break;
}
}
}
}
}
node* Mult(node* p1,node* p2)
{
p1 = p1->next;
p2 = p2->next;
node *pro = new node;
pro->next = NULL;
node *pp2; //用另一个指针方便再循环
pp2 = p2;
while(p1){
while(pp2){
node* t = new node;
t->expon = p1->expon + pp2->expon;
t->coef = p1->coef * pp2->coef;
if(t->coef)Attach(pro,t);
pp2 = pp2->next;
}
p1 = p1->next;
pp2 = p2;
}
return pro;
}
int main(int argc, char const *argv[])
{
node *p1 = new node,*p2 = new node;
p1->next = p2->next = NULL;
int k1,k2;
int expon;
double coef;
scanf("%d",&k1);
for(int i=0;i<k1;i++){
scanf("%d%lf",&expon,&coef);
node* t = new node;
t->expon = expon;
t->coef = coef;
Attach(p1,t);
}
scanf("%d",&k2);
for(int i=0;i<k2;i++){
scanf("%d%lf",&expon,&coef);
node* t = new node;
t->expon = expon;
t->coef = coef;
Attach(p2,t);
}
node *prdt = Mult(p1,p2);
int cnt = 0;
for(node* p=prdt->next;p!=NULL;p=p->next){
if(p->coef)cnt++;
}
printf("%d",cnt);
for(node* p=prdt->next;p!=NULL;p=p->next){
if(p->coef) printf(" %d %.1f",p->expon,p->coef);
}
return 0;
}