PAT - 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 a~N1~ N2 a~N2~ … NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (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…Nk aNk
K - 非零项的个数
Ni - 指数
aNi - 系数
注意每行的末尾没有额外的空格。保留一位小数。

数据范围:1 <= K <= 10,0 <= Nk < … < N2 < N1 <=1000

aNi没有给范围???

解题思路:用结构体保存每一项。循环检查,指数相等的系数加到 A,B 中指数置 -1表示加过,结束后把 B 中指数非 -1 的项加到 A 后面。然后把 A 中系数为 0 的项指数置 -1 表示没有该项。最后根据指数从大到小排序,输出。


#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100+10;
const int INF = 0x3f3f3f3f;
struct Node {
    int zs;
    double xs;
}A[30], B[30];
bool cmp(Node a, Node b) {
    return a.zs > b.zs;
} 
int main() {
    int n1, n2;
    scanf("%d", &n1);
    for (int i = 0; i < n1; i++) {
        scanf("%d%lf", &A[i].zs, &A[i].xs); 
    }
    scanf("%d", &n2);
    for (int i = 0; i < n2; i++) {
        scanf("%d%lf", &B[i].zs, &B[i].xs); 
    }
    for (int i = 0; i < n1; i++) {
        for (int j = 0; j < n2; j++) {
            if (A[i].zs == B[j].zs) {
                A[i].xs += B[j].xs;
                B[j].zs = -1;
            }
        }
    }
    for (int i = 0; i < n2; i++) {
        if (B[i].zs != -1) {
            A[n1].zs = B[i].zs;
            A[n1++].xs = B[i].xs;
        }
    }
    int cnt = 0;
    for (int i = 0; i < n1; i++)
        if (A[i].xs == 0) 
            A[i].zs = -1;
    for (int i = 0; i < n1; i++)
        if (A[i].zs != -1) cnt++;
    sort(A, A+n1, cmp);
    printf("%d", cnt);
    for (int i = 0; i < cnt; i++) {
        printf(" %d %.1lf", A[i].zs, A[i].xs);
    } 
    printf("\n");

    return 0;
}

提交时间状态分数题目编译器耗时
2018/7/5 22:38:55答案正确251002C++ (g++)3 ms
2018/7/5 22:33:21部分正确171002C++ (g++)3 ms
2018/7/5 22:24:19部分正确171002C++ (g++)3 ms
2018/7/5 22:23:34部分正确171002C++ (g++)2 ms

没注意到相加后可能出现系数为 0 的项,WA了几个

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值