设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
0 0
。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
#include <stdio.h>
typedef struct Type
{
int index;
int num;
} Type;
int main()
{
Type L1[200];
Type L2[200];
Type Lsum[400];
Type Lmul[400];
int n1, n2, i, j, k = 1;
scanf("%d", &n1);
for(i = 1; i <= n1; ++i)
{
scanf(" %d %d", &L1[i].num, &L1[i].index);
}
scanf("%d", &n2);
for(i = 1; i <= n2; ++i)
{
scanf(" %d %d", &L2[i].num, &L2[i].index);
}
if(n1 == 0 && n2 == 0)
{
printf("0 0\n");
printf("0 0");
return 0;
}
else if(n1 == 0 && n2 != 0)
{
printf("0 0\n");
int cnt = 0;
for(i = 1; i <= n2; ++i)
{
if(L2[i].num != 0)
{
if(cnt)
printf(" ");
printf("%d %d", L2[i].num, L2[i].index);
cnt++;
}
}
}
else if(n1 != 0 && n2 == 0)
{
printf("0 0\n");
int cnt = 0;
for(i = 1; i <= n1; ++i)
{
if(L1[i].num != 0)
{
if(cnt)
printf(" ");
printf("%d %d", L1[i].num, L1[i].index);
cnt++;
}
}
}
else
{
//乘法
//复制到新数组
for(i = 1; i <= n1; i++)
for(j = 1; j <= n2; j++,k++)
{
Lmul[k].num = L1[i].num * L2[j].num;
Lmul[k].index = L1[i].index + L2[j].index;
}
//去重
for(i = 1; i <= k; i++)
{
for(j = i + 1; j <= k; j++)
{
if(Lmul[i].index == Lmul[j].index)
{
Lmul[i].num += Lmul[j].num;
//删除数据
Lmul[j].num = Lmul[j].index = 0;
}
}
}
//排序
for(i = 1; i <= k; ++i)
for(j = i + 1; j <= k; ++j)
{
if(Lmul[i].index < Lmul[j].index)
{
Type temp;
temp = Lmul[i];
Lmul[i] = Lmul[j];
Lmul[j] = temp;
}
}
//复制到信数组
for(i = 1; i <= n1; i++)
{
Lsum[i] = L1[i];
}
for(; i <= n1 + n2; i++)
{
Lsum[i] = L2[i - n1];
}
//数组去重加和
for(i = 1; i <= n1 + n2; i++)
{
for(j = i + 1; j <= n1 + n2; j++)
{
if(Lsum[i].index == Lsum[j].index)
{
Lsum[i].num += Lsum[j].num;
//删除数据
Lsum[j].num = Lsum[j].index = 0;
}
}
}
//数组排序
for(i = 1; i <= n1 + n2; ++i)
for(j = i + 1; j <= n1 + n2; ++j)
{
if(Lsum[i].index < Lsum[j].index)
{
Type temp;
temp = Lsum[i];
Lsum[i] = Lsum[j];
Lsum[j] = temp;
}
}
int cnt = 0;
for(i = 1; i <= k; ++i)
{
if(Lmul[i].num != 0)
{
if(cnt)
printf(" ");
printf("%d %d", Lmul[i].num, Lmul[i].index);
cnt++;
}
}
if(cnt == 0)
printf("0 0");
printf("\n");
cnt = 0;
for(i = 1; i <= n1 + n2; ++i)
{
if(Lsum[i].num != 0)
{
if(cnt)
printf(" ");
printf("%d %d", Lsum[i].num, Lsum[i].index);
cnt++;
}
}
if(cnt == 0)
printf("0 0");
}
}
标签:200,20,int,多项式,加法,Type,输入,乘法
From: https://blog.51cto.com/u_16129621/6350110