多项式加法
openjudge5467
题目是考察线性表的。我的思路是利用数组记录下两组输入,然后按幂指数从高到低进行排序,然后进行加法运算。已幂指数为-1表示一个多项式的结束。(注意存在幂指数相同的项。)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
long coe;
long exp;
};
typedef struct node element;
element poly_a[301];
element poly_b[301];
element result[602];
//将数组排序;
void array_sort(element poly[])
{
for(int i=0;poly[i+1].exp!=-1;i++)
{
int t = i;
int max = poly[i].exp;
for(int j=i+1;poly[j].exp!=-1;j++)
{
if(poly[j].exp>max)
{
t = j;
max = poly[j].exp;
}
}
int tmp ;
tmp = poly[t].coe;
poly[t].coe = poly[i].coe;
poly[i].coe = tmp;
tmp = poly[t].exp;
poly[t].exp = poly[i].exp;
poly[i].exp = tmp;
}
}
int main()
{
int N;
scanf("%d",&N);
for(int i=0;i<N;i++)
{
int j = 0;
int coe = 0, exp = 0;
scanf("%d%d",&coe,&exp);
while(exp>=0)
{
poly_a[j].coe = coe;
poly_a[j].exp = exp;
j++;
scanf("%d%d",&coe,&exp);
}
poly_a[j].exp = -1;
j = 0;
scanf("%d%d",&coe,&exp);
while(exp>=0)
{
poly_b[j].coe = coe;
poly_b[j].exp = exp;
j++;
scanf("%d%d",&coe,&exp);
}
poly_b[j].exp = -1;
array_sort(poly_a);
array_sort(poly_b);
int m = 0;
int n = 0;
int k = 0;
while(poly_a[m].exp!=-1&&poly_b[n].exp!=-1)
{
if(poly_a[m].exp == poly_b[n].exp)
{
result[k].coe = poly_a[m].coe + poly_b[n].coe;
result[k].exp = poly_a[m].exp;
m++;
n++;
while(poly_a[m].exp == result[k].exp)
{
result[k].coe += poly_a[m].coe;
m++;
}
while(poly_b[n].exp == result[k].exp)
{
result[k].coe += poly_b[n].coe;
n++;
}
k++;
}
else{
if(poly_a[m].exp>poly_b[n].exp)
{
result[k].coe = poly_a[m].coe;
result[k].exp = poly_a[m].exp;
k++;
m++;
}
else
{
result[k].coe = poly_b[n].coe;
result[k].exp = poly_b[n].exp;
k++;
n++;
}
}
}
while(poly_a[m].exp != -1)
{
result[k].coe = poly_a[m].coe;
result[k].exp = poly_a[m].exp;
k++;
m++;
}
while(poly_b[n].exp != -1)
{
result[k].coe = poly_b[n].coe;
result[k].exp = poly_b[n].exp;
k++;
n++;
}
result[k].exp = -1;
// print answer;
for(m=0;result[m].exp!=-1;m++)
{
int n = m+1;
while(result[m].exp == result[n].exp)
{
result[m].coe += result[n].coe;
result[n].coe = 0;
n++;
}
if(result[m].coe!=0)
printf("[ %d %d ] ",result[m].coe,result[m].exp);
}
printf("\n");
}
return 0;
}