1002 A+B for Polynomials (25分)
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 … NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000.
Output Specification:
For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
该题是一道多项式加和的问题;
应当注意当系数为零的时候不予显示。
以下有两种方法:
第一种是我最先想到的,用结构体来储存指数和系数;
#include<stdio.h>
typedef struct pol {
int exp;//指数
float cop;//系数
}tpol;
void sort(tpol* tab, int n) {//冒泡排序
int i, flag = 1;
tpol r;
while (flag == 1) {
flag = 0;
for (i = 0; i < n - 1; i++) {
if (tab[i].exp < tab[i + 1].exp) {
flag = 1;
r = tab[i];
tab[i] = tab[i + 1];
tab[i + 1] = r;
}
}
}
}
int merge(tpol* tab, int n) {//将传入数组的指数相同的项和并 ,但鉴于测试用例中并未考察这种情况,所以此子函数可以不用
int i,j,k;
k = n;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (tab[i].cop == 0 && tab[i].exp == 0)
break;
if (i != j) {
if (tab[i].exp == tab[j].exp) {
tab[i].cop = tab[i].cop + tab[j].cop;
tab[j].cop = 0;
tab[j].exp = 0;
k--;
}
}
}
}
sort(tab, n);
return k;
}
int main(void) {
tpol a[1005], b[1005];
int n1, n2, i, j, k = 0, flag = 0;
scanf("%d", &n1);
for (i = 0; i < n1; i++) {
scanf("%d%f", &a[i].exp, &a[i].cop);
}
scanf("%d", &n2);
for (i = 0; i < n2; i++) {
scanf("%d%f", &b[i].exp, &b[i].cop);
}
n1 = merge(a, n1);//可以不使用这个子函数
n2 = merge(b, n2);//可以不使用这个子函数
for (i = 0; i < n1; i++) {
flag = 0;
for (j = 0; j < n2; j++) {
if (a[i].exp == b[j].exp) {
b[j].cop = a[i].cop + b[j].cop;
flag = 1;
}
}
if (flag == 0) {
b[n2 + k] = a[i];
k++;
}
}
k = k + n2;
sort(b, k);
flag=k;
for(i=0;i<k;i++){
if(b[i].cop==0){
k--;
}
}
printf("%d", k);
for (i = 0; i < flag; i++) {
if(b[i].cop!=0)
printf(" %d %.1f", b[i].exp, b[i].cop);
}
}
这种方法颇为繁琐,于是有了第二种更加简洁的办法;
将数组下标当作指数的方法。
#include<stdio.h>
int main(void){
float a[1001]={0},cop;
int i,n,exp,k=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d%f",&exp,&cop);
a[exp]+=cop;
}
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d%f",&exp,&cop);
a[exp]+=cop;
}
for(i=0;i<1001;i++){
if(a[i]!=0)k++;
}
printf("%d",k);
for(i=1000;i>=0;i--){
if(a[i]!=0)
printf(" %d %.1f",i,a[i]);
}
}
这种方法将数组下标当作指数,将系数存入对应的项中,最后遍历数组输出结果,第二种方法更加简洁。