题意:给定两个多项式,然后求两个多项式相乘的结果。
1思路:用一个数组a[1001],i下标为多项式的Ni,a[i]为该项的系数,同理设置一个数组p[2001]来储存结果,乘法操作过程中,先用一个数组n[20]储存一个多项式的Ni,这样便于查找不为0的项数。
2思路:用链表储存,
#include<stdio.h>
int main()
{
int K1,K2,i,j,n[20],M=0;
double a[1001]={0},p[2001]={0};
scanf("%d",&K1);
for(i=0;i<K1;i++){
scanf("%d",&n[i]);
scanf("%lf",&a[n[i]]);
}
scanf("%d",&K2);
for(i=0;i<K2;i++){
int xx;
double x;
scanf("%d %lf",&xx,&x);
for(j=0;j<K1;j++){
p[n[j]+xx]+=x*a[n[j]];
}
}
for(i=0;i<2001;i++){
if(p[i])n[M]=i,M++;
}
printf("%d",M);
if(M){
printf(" ");
for(i=M-1;i>0;i--)printf("%d %.1lf ",n[i],p[n[i]]);
printf("%d %.1lf",n[0],p[n[0]]);
}
return 0;
}
链表储存:第0个测试点未通过?????
#include<stdio.h>
#include<malloc.h>
typedef struct polynomial{
int n;
double a;
struct polynomial *next;
struct polynomial *pre;
}polynomial;
typedef polynomial* list;
int main()
{
int K,i;
list head1,p;
head1=(list)malloc(sizeof(polynomial));
head1->next=NULL;
head1->pre=NULL;
p=head1;
scanf("%d",&K);
for(i=0;i<K;i++){ //建立第一个多项式链表 ,
list q=(list)malloc(sizeof(polynomial));
scanf("%d %lf",&q->n,&q->a);
q->next=NULL;
q->pre=p;
p->next=q;
p=q;
}
list head=(list)malloc(sizeof(polynomial));
list last=(list)malloc(sizeof(polynomial));
last->next=NULL;
last->pre=head;
head->next=last;
head->pre=NULL;
scanf("%d",&K);
int M=0;
for(i=0;i<K;i++){
int n;
double a;
scanf("%d %lf",&n,&a);
list q=head1->next;
while(q){
int nn;
double aa;
nn=n+q->n;
aa=a*q->a;
if(aa!=0){
p=head->next;
while(p->next&&p->n>nn)p=p->next;
if(p->n==nn)
{
p->a+=aa;
if(p->a==0){
p->pre->next=p->next;
p->next->pre=p->pre;
M--;
}
}
else{
list m=(list)malloc(sizeof(polynomial));
m->n=nn;
m->a=aa;
m->pre=p->pre;
m->next=p;
p->pre->next=m;
p->pre=m;
M++;
}
}
q=q->next;
}
}
p=head->next;
printf("%d",M);
if(M){
printf(" ");
while(p->next){
printf("%d %.1lf",p->n,p->a);
p=p->next;
if(p->next)printf(" ");
}
}
return 0;
}