PAT甲級本題1009 Product of Polynomials(25点)C++実装(mapを使用し、テストポイント0のピットに注意)

8914 ワード

タイトル
This time, you are supposed to find A*B where A and B are two polynomials. Input Specification: 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 Specification: For each test case you should output the product 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 up to 1 decimal place. Sample Input 2 1 2.4 0 3.2 2 2 1.5 1 0.5 Sample Output 3 3 3.6 2 6.0 1 1.6
構想
配列でそれぞれ1つ目の多項式の指数と係数を格納し、2つ目の多項式を読み込むと、指数、係数のセットを読むたびに、1つ目の多項式の各項目と演算されます.
結果はmapに格納され、指数はkey、係数はvalue(valueのデフォルト初期値は0であり、直接加算すればよい).係数が0の項があればmapから削除する.
最後に、map.size()は非0係数項の個数であり、mapkeyおよびvalueを逆配列することは、指数降順配列の結果である(mapはkey昇順に自動的に配列される).
注意:
  • の結果は1桁の小数を保持しなければならない.
  • 係数が0の場合(問題は係数の入力に制限がない)は、それを除外する必要があります.そうしないと、テストポイント0は合格できません.

  • コード#コード#
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int main(){
        map<int, double> mmap;
    
        int k1, k2;
        cin >> k1;
        vector<int> exp(k1);
        vector<double> coef(k1);
        for (int i=0; i<k1; i++){
            cin >> exp[i] >> coef[i];
        }
    
        cin >> k2;
        for (int i=0; i<k2; i++){
            int tempExp;
            double tempCoef;
            cin >> tempExp >> tempCoef;
            for (int j=0; j<k1; j++){
                int newExp = tempExp + exp[j];
                mmap[newExp] += (tempCoef * coef[j]);
                if (mmap[newExp]==0){
                    mmap.erase(newExp);
                }
            }
        }
    
        cout << mmap.size();
        for (auto it=mmap.rbegin(); it!=mmap.rend(); ++it){
            cout << " " << it->first << " " << setprecision(1) << fixed << it->second;
        }
        cout << endl;
        return 0;
    }