PAT 1002 A+B for Polynomials (25) HERODING的PAT之路

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 coeficients, respectively. It is given that 1 <= K <= 10,0
<= NK < … < N2 < N1 <=1000.
#include
using namespace std;
int main() {
int a, b;
cin >> a >> b;
string s = to_string(a + b);
int len = s.length();
for (int i = 0; i < len; i++) {
cout << s[i];
if (s[i] == ‘-’) continue;
if ((i + 1) % 3 == len % 3 && i != len - 1) cout << “,”;
}
return 0; } 123456789
10
11
12
13
14

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

题目大意:
老实说这道题审题就老费劲了,其实就是两个多项式对应项数相加,每一行第一个输入的是该行有多少项数,紧接着输入项的位置和该项大小。

解题思路:
设立一个最大指数长度的数组,保存每项的值,分别遍历每行输入的项数并整合到数组中,接着遍历数组,统计非0项的个数,并用vector保存项的位置,最后从后往前遍历vector,输出所有系数不为0的指数和系数即可,代码如下:

#include<iostream>
#include<vector>

using namespace std;

int main() {
    
    
    float arr[1001] = {
    
    0};
    // 定义输入的两个数组的长度,下标和数值
    int len1, len2, index; 
    float num;
    cin >> len1;
    for(int i = 0; i < len1; i ++) {
    
    
        cin >> index >> num;
        arr[index] += num;
    }
    cin >> len2;
    for(int i = 0; i < len2; i ++) {
    
    
        cin >> index >> num;
        arr[index] += num;
    }
    int count = 0;
    vector<int> res;
    for(int i = 0; i < 1001; i ++) {
    
    
        if(arr[i] != 0) {
    
    
            res.push_back(i);
            count ++;
        }
    }
    cout << count;
    for(int i = res.size() - 1; i >= 0; i --) {
    
    
        printf(" %d %.1f", res[i], arr[res[i]]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/114109224