1002. A+B for Polynomials (25)

1002. A+B for Polynomials (25)

This time, you are supposed to find A+B where A and B are two polynomials.

Input

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

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

题意:多组数据,每组数据有两行,分别表示多项式A和B,求A和B的和。每行第一个数K代表多项式非零项的个数,接下来是N1 aN1 N2 aN2 ... NK aNK,Ni是指数,Ai是系数,听起来有点乱是吧。
通俗的意思就是多项式A或B=N1*aN1+N2*aN2+.....+NK*aNK。其中1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.然后求A+B的和,要求以同样的方式输出,什么同样方式,就是先输出结果是多少项,K,然后Ni从大到小,为零的项不输出。
题解:可以用结构体数组存储A和B的项,然后用C数组存储A+B的每一个项,比如c[i]存储了项i*c[i],c数组要初始化为0,i的最高项是A和B中指数最高的项,我的程序中遍历了两遍A和B,其实应该比较a[0].x和b[0].x就可以了。而c[i]需要遍历A和B,出现以i为系数的项,就加到c[i]上。有两个坑点,一是只输出所有的非零项,个数也只算非零项,二是注意格式,结尾没有空格,结尾没有空格,结尾没有空格!wa多了都是泪
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
    int x; double y;
}a[50];
node b[50]; double c[1001];
bool cmp(node a, node b)
{
    return a.x > a.y;
}
int main()
{
    int k1, k2, i, j, temp,h;
    while (scanf("%d", &k1) != EOF)
    {
        h = 0;
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        memset(c, 0, sizeof(c));
        for (i = 0; i < k1; i++)
        {
            scanf("%d%lf", &a[i].x, &a[i].y);
            if (h < a[i].x) h = a[i].x;
        }
        scanf("%d", &k2);
        temp = 0;
        for (i = 0; i < k2; i++)
        {
            scanf("%d%lf", &b[i].x, &b[i].y);
            if (h <b[i].x) h = b[i].x;
        }
        for (j = h; j >= 0; j--)
        {
            for (i = 0; i < k1; i++)
                if (a[i].x == j) c[j] += a[i].y;
            for (i = 0; i < k2; i++)
                if (b[i].x == j) c[j] += b[i].y;
        }
        for (i = 0; i <= h; i++)
            if (c[i] != 0) temp++;
        if (temp== 0) printf("0");
        else printf("%d ", temp);
        int count = 0;
        for (i = h; i >=0; i--)
        {
            if (c[i] != 0)
            {
                count++;
                printf("%d %.1lf", i, c[i]);
                if (count!=temp) printf(" ");
            }
        }
        printf("\n");
    }
}

 

 
posted @ 2017-04-18 22:23  请刷题2017  阅读(140)  评论(0)    收藏  举报