PAT 1002 A+B for Polynomials
阿新 • • 發佈:2021-07-08
PAT 1002 A+B for Polynomials
題目含義
就是兩個指數多項式相加,然後輸出結果。
結果第一個數是多項式中元素的個數,然後就是按照指數從大到小輸出各個元素。
題解
這裡需要注意的是第一個數的輸出。聯絡常識,如果兩個數相加為0,那麼是不需要輸出的,所以元素的個數有可能會比輸入的要少。
還有就是注意輸入的指數是從大到小的,也就是單看每一個輸入都是有序的。這裡的相加相當於廣義上的兩個有序序列合併起來。
網上題解很多,但是很少使用連結串列這種資料結構來解決,其實使用連結串列是比較合適的。把第一個序列固定,第二個遍歷插入到第一個序列中即可。
這裡為了方便,使用了STL中的list。這也是我第一次使用list,其實還是蠻好用的。
好的資料結構能省很多事。
程式碼
對於列表主要就是看如何插入和刪除。
歡迎評論交流!#include<cmath> #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<stack> #include<queue> #include<map> #include<set> #include<list> #include<sstream> typedef long long ll; using namespace std; const double eps=1e-6; const int inf=0x3f3f3f3f; const int MAXN=1E1+7; struct Node{ int n; double a; }; typedef list<Node> lnd; lnd nodes; int n, k; int main() { cin>>k; Node tmp; for(int i=0; i<k; i++){ scanf("%d%lf", &tmp.n, &tmp.a); nodes.push_back(tmp); } // for(lnd::iterator i = nodes.begin(); i!=nodes.end(); i++){ // cout<<(*i).n<<" "<<(*i).a<<endl; // } cin>>k; lnd::iterator rs = nodes.begin(); for(int i=0; i<k; i++){ scanf("%d%lf", &tmp.n, &tmp.a); for(;; rs++){ if(rs==nodes.end()){ nodes.insert(rs, tmp); break; } if((*rs).n==tmp.n){ (*rs).a += tmp.a; if((*rs).a==0.0) rs = nodes.erase(rs); //返回當前刪除元素的下一個位置 break; } else if((*rs).n < tmp.n){ lnd::iterator j = nodes.insert(rs, tmp); //insert函式是有返回值的,返回新插入的位置,就是rs的上一個位置。 // printf("%d *** %d\n", (*rs).n, (*j).n); break; } } } n = nodes.size(); cout<<n; lnd::iterator i = nodes.begin(); while(i!=nodes.end()){ printf(" %d %.1f", (*i).n, (*i).a); i++; } printf("\n"); return 0; }