PAT Grade A——1002. A+B for Polynomials (25) (C++)

Problem solving ideas

Create an array float map[1001] = {0.0} as a hash table, use the index of the array to represent the index, and the element stored in the corresponding position to represent the coefficient.
At the beginning I used cin, cout standard input and output (in the standard output to keep 1 decimal point writing: cout << setiosflags(ios::fixed) << setprecision(1) << endl;), and then scanf, printf input and output are more concise.

Implementation code

#include <iostream>
using namespace std;

int main() {
    
    
    float c[1001] = {
    
    0};
    int m, n, t = 0;
    float num = 0.0;
    scanf("%d", &m);
    for (int i = 0; i < m; i++) {
    
    
        scanf("%d%f", &t, &num);
        c[t] += num;
    }
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
    
    
        scanf("%d%f", &t, &num);
        c[t] += num;
    }
    int cnt = 0;
    for (int i = 0; i < 1001; i++) {
    
    
        if (c[i] != 0) cnt++;
    }
    printf("%d", cnt);
    for (int i = 1000; i >= 0; i--) {
    
    
        if (c[i] != 0) {
    
    
            printf(" %d %.1f", i, c[i]);
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/t0be_Better/article/details/108571861