多项式相乘
| Time Limit: | 1000MS | Memory Limit: | 65536KB |
|---|---|---|---|
| Total Submissions: | 311 | Accepted: | 119 |
Description:
编程实现若干个多项式相乘。多项式的输入输出格式为:系数在前,指数在后,各项按指数递增排列,每个多项式输入时以两个0结束。系数为0的项不输出。例如:1+4X3-9X5输入格式为:1 0 0 1 0 2 4 3 0 4 -9 5 0 0或者 1 0 4 3 -9 5 0 0,其输出只能是:
1 0 4 3 -9 5
Input:
输入每行为一个多项式,多项式输入时以两个0结束。数据为若干行的多项式,例如: 1 0 1 1 0 0 1 0 -1 1 0 0 1 0 1 2 0 0 表示 (1+x)(1-x)(1+x2) 所有系数、指数均为整数(int类型)
Output:
输出包含1行,为上述多项式相乘结果。上例的输出为: 1 0 -1 4 表示1-x4
Sample Input:
1 0 1 1 0 0
1 0 -1 1 0 0
1 0 1 2 0 0
Sample Output:
1 0 -1 4
Hint:
数据保证不超过十个多项式相乘,单个多项式以上述方式表示的长度不超过一百,指数最大可达到一百万,结果保证在int范围内。
Source:
#include "stdio.h"
typedef struct node
{ int e,c;
node *next;
}ND;
ND *createLink()
{ ND* head=new ND, *p;
int c,e;
p=head;
while( true )
{ if( scanf("%d%d", &c, &e)!=2 ) break;
if( c==0 && e==0 ) break;
if( c==0 ) continue;
p->next=new ND;
p=p->next;
p->e=e;
p->c=c;
}
p->next=NULL;
return head;
}
void printLink( ND *head )
{ ND *p=head->next;
while( p )
{
printf("%d %d ", p->c, p->e );
p=p->next;
}
printf("\n");
}
void freeLink( ND *head )
{ ND *p=head;
while( p )
{ head=head->next;
delete p;
p=head;
}
}
ND *addLink( ND *ha, ND *hb )
{ ND *hc, *pc, *pa=ha->next, *pb=hb->next;
int c,e;
hc=new ND;
pc=hc;
while( pa || pb )
{ if( pa && ( pb==NULL || pa->e<pb->e ) )
{ c=pa->c;
e=pa->e;
pa=pa->next;
}
else if( pb && ( pa==NULL || pb->e<pa->e ) )
{ c=pb->c;
e=pb->e;
pb=pb->next;
}
else
{ c=pa->c+pb->c;
e=pa->e;
pa=pa->next;
pb=pb->next;
}
if( c )
{ pc->next=new ND;
pc=pc->next;
pc->c=c;
pc->e=e;
}
}
pc->next=NULL;
return hc;
}
ND *multyXmulty( ND *ha, ND *hb )
{ ND *hc=new ND, *pa=ha->next, *ht;
ND *oneXmulty( ND *pa, ND *hb );
hc->next=NULL;
while( pa )
{ ht=oneXmulty( pa, hb );
hc=addLink( hc, ht );
freeLink(ht);
pa=pa->next;
}
return hc;
}
ND *oneXmulty( ND *pa, ND *hb )
{ ND *hc=new ND, *pc=hc, *pb=hb->next;
while( pb )
{ pc->next=new ND;
pc=pc->next;
pc->c=pa->c*pb->c;
pc->e=pa->e+pb->e;
pb=pb->next;
}
pc->next=NULL;
return hc;
}
int main()
{ ND *ha, *hb, *hc;
// freopen("1063.in", "r", stdin);
ha=createLink();
hb=createLink();
while( hb->next )
{ hc=multyXmulty( ha, hb);
freeLink( ha );
freeLink( hb );
ha=hc;
hb=createLink();
}
printLink( hc );
freeLink( hc );
freeLink( hb );
return 0;
}
\