其他分享
首页 > 其他分享> > PAT-1002 A+B for Polynomials

PAT-1002 A+B for Polynomials

作者:互联网

1002 A+B for Polynomials

part 1, 1.1

自己解法(未全对)

#include <iostream>
using namespace std;
#include <map>
#include <algorithm>
#include <iomanip>

class MyCompare
{
public:
    bool operator()(int v1, int v2)
    {
        return v1 > v2;
    }
};

int main()
{
    map<int, float, MyCompare> p1;
    int n1;
    cin >> n1;
    while (n1--)
    {
        int N;
        float aN;
        cin >> N;
        cin >> aN;
        p1.insert(make_pair(N, aN));
    }
    map<int, float, MyCompare> p2;
    int n2;
    cin >> n2;
    while (n2--)
    {
        int N;
        float aN;
        cin >> N;
        cin >> aN;
        p2.insert(make_pair(N, aN));
    }

    for (map<int, float>::iterator it = p2.begin(); it != p2.end(); it++)
    {
        map<int, float>::iterator pos = p1.find(it->first);
        if (pos != p1.end())
            pos->second += it->second;
        else
            p1.insert(make_pair(it->first, it->second));
    }

    cout << p1.size() << " ";
    for (map<int, float>::iterator it = p1.begin(); it != p1.end(); it++)
    {
        cout << it->first << " " << fixed << setprecision(1) << it->second;
        if (it->first != 0)
            cout << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

大神解法

#include <iostream>
using namespace std;
int main() {
    float c[1001] = {0};
    int m, n, t;
    float num;
    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.0)
            printf(" %d %.1f", i, c[i]);
    }
    return 0;
}

标签:p1,PAT,int,cin,Polynomials,++,num,include,1002
来源: https://blog.csdn.net/seven_colors/article/details/122796293