这仍然是一道关于A/B的题,只不过A和B都换成了多项式。你需要计算两个多项式相除的商Q和余R,其中R的阶数必须小于B的阶数。
输入格式:
输入分两行,每行给出一个非零多项式,先给出A,再给出B。每行的格式如下:
N e[1] c[1] … e[N] c[N]
其中N是该多项式非零项的个数,e[i]是第i个非零项的指数,c[i]是第i个非零项的系数。各项按照指数递减的顺序给出,保证所有指数是各不相同的非负整数,所有系数是非零整数,所有整数在整型范围内。
输出格式:
分两行先后输出商和余,输出格式与输入格式相同,输出的系数保留小数点后1位。同行数字间以1个空格分隔,行首尾不得有多余空格。注意:零多项式是一个特殊多项式,对应输出为0 0 0.0。但非零多项式不能输出零系数(包括舍入后为0.0)的项。在样例中,余多项式其实有常数项-1/27,但因其舍入后为0.0,故不输出。
输入样例:
4 4 1 2 -3 1 -1 0 -1
3 2 3 1 -2 0 1
输出样例:
3 2 0.3 1 0.2 0 -1.0
1 1 -3.1
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
using namespace std;
struct node
{
int zhishu;
double xishu;
struct node* next;
};
typedef struct node* list;
list scan()
{
int i, n;
double c;
int e;
list L, tail, p;
L = (list)malloc(sizeof(struct node));//头结点
tail = L;
scanf("%d", &n);
for (i = 0; i < n; i++) { //创建链表
scanf("%d %lf", &e, &c);
p = (list)malloc(sizeof(struct node));
p->zhishu = e;
p->xishu = c;
p->next = NULL;
tail->next = p;
tail = p;
}
return L;//是有头结点的;
}
void div(list l1, list l2, list& S, list& Y)//整个过程可以用整数除法类比
{
list head1, head2, head, tail, p1, p2, p, pp, pp1,pp2, tmp;
int e; double c;
head1 = l1; head2 = l2;
p1 = head2->next;
tmp = l1->next;//初始化
head = (list)malloc(sizeof(struct node));//商的头结点
tail = head;
while (tmp->zhishu >= p1->zhishu&& tmp->zhishu != 0) {//循环条件
head1 = head1->next;//每次往下一位
p = (list)malloc(sizeof(struct node));
p->zhishu = head1->zhishu - p1->zhishu;
p->xishu = head1->xishu / p1->xishu;//相除,得到商的第n位
p->next = NULL;//每次一定要置空
tail->next = p;
tail = p;
pp1 = head1;
for (pp = p1->next; pp; pp = pp->next) {//减数减去商和被除数的乘积
e = pp->zhishu + p->zhishu;
c = pp->xishu * p->xishu; //
while (pp1->next && pp1->next->zhishu > e) {
pp1 = pp1->next;
}
if (pp1->next &&pp1->next->zhishu == e) {
pp1->next->xishu -= c;
}
else {
pp2 = (list)malloc(sizeof(struct node));
pp2->zhishu = e;
pp2->xishu = -c;
pp2->next = pp1->next;
pp1->next = pp2;
}
pp1 = pp1->next;
}
tmp = head1->next;
if (tmp == NULL)break;
}
Y = tmp;
S = head->next;
}
void prin(list l,int len)
{
if (len == 0 || len == 1 && l->xishu == 0)printf("0 0 0.0\n");
else {
list tmp;
tmp = l;
printf("%d", len);
for (tmp = l; tmp->next; tmp = tmp->next) {
if(tmp->xishu!=0)
printf(" %d %.1f", tmp->zhishu, tmp->xishu);
}
if (fabs(tmp->xishu - 0.0) > 0.06)printf(" %d %.1f\n", tmp->zhishu, tmp->xishu);
else printf("\n");
}
}
int len(list L)
{
list p;
int len = 0;
for (p = L; p; p = p->next) {
if (fabs(p->xishu - 0.0) < 0.06);
else len++;
}
return len;
}
int main()
{
list l1, l2, S, Y;
l1 = scan();
l2 = scan();
div(l1, l2, S, Y);
int len1, len2;
len1 = len(S);
len2 = len(Y);
prin(S,len1);
prin(Y,len2);
return 0;
}