标签:class main opened sort stl str turn else ios
复习了一下STL,写完才想起来可以用map,代码量*3,orz
提交时遇到一次Presentation Error,OJ的空格输出实在是太随性。
思路是分别对两组输入进行排序,再通过k1,k2两个迭代器导入新的容器
注意:
vector<int> a, b; vector<int>::const_iterator k1, k2; if (a.begin() == a.end()) //输出1 cout << ‘1‘; else cout << ‘0‘; if (a.begin() == b.begin()) //输出1 cout << ‘1‘; else cout << ‘0‘; k1 = a.begin(); a.push_back(5); k2 = a.begin(); if (k1 == k2) //输出0 cout << ‘1‘; else cout << ‘0‘;
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 using namespace std; 5 class poly{ //多项式类 6 public: 7 int coe; //系数 8 int item; //项数 9 poly(){} 10 poly(int a, int b): coe(a), item(b){} 11 friend bool operator < (const poly &, const poly &); 12 friend poly operator + (const poly &, const poly &); 13 }; 14 bool operator < (const poly &a, const poly &b){ 15 if (a.item > b.item) 16 return true; 17 else 18 return false; 19 } 20 poly operator + (const poly &a, const poly &b){ 21 return poly(a.coe + b.coe, a.item); 22 } 23 void insert_num(vector<poly> &x){ 24 poly tmp; 25 int a, b; 26 while (cin >> a >> b){ 27 if (b < 0) 28 break; 29 tmp.coe = a; 30 tmp.item = b; 31 x.push_back(tmp); 32 } 33 } 34 int main(){ 35 int n; 36 vector<poly> p1, p2, p3; 37 vector<poly>::iterator k1, k2, k3; 38 cin >> n; 39 for (int i = 0; i < n; ++i){ 40 insert_num(p1); 41 insert_num(p2); 42 sort(p1.begin(), p1.end()); 43 sort(p2.begin(), p2.end()); 44 k1 = p1.begin(); 45 k2 = p2.begin(); 46 while (1){ 47 k3 = p3.end() - 1; //请勿使用p3.rbegin(),对应reverse_iterator 48 if (k1 < p1.end() && k2 < p2.end()){ 49 if ((*k1).item < (*k2).item){ 50 if (!p3.empty() && (*k3).item == (*k2).item) 51 (*k3) = (*k3) + (*k2); 52 else 53 p3.push_back(*k2); 54 k2++; 55 } 56 else if ((*k1).item > (*k2).item){ 57 if (!p3.empty() && (*k3).item == (*k1).item) 58 (*k3) = (*k3) + (*k1); 59 else 60 p3.push_back(*k1); 61 k1++; 62 } 63 else{ 64 if (!p3.empty() && (*k3).item == (*k2).item) 65 (*k3) = (*k3) + (*k2) + (*k1); 66 else 67 p3.push_back((*k1) + (*k2)); 68 k1++; 69 k2++; 70 } 71 } 72 else if (k1 < p1.end() && k2 == p2.end()){ 73 while (k1 < p1.end()){ 74 k3 = p3.end() - 1; 75 if (!p3.empty() && (*k3).item == (*k1).item) 76 (*k3) = (*k3) + (*k1); 77 else 78 p3.push_back(*k1); 79 k1++; 80 } 81 } 82 else if (k1 == p1.end() && k2 < p2.end()){ 83 while (k2 < p2.end()){ 84 k3 = p3.end() - 1; 85 if (!p3.empty() && (*k3).item == (*k2).item) 86 (*k3) = (*k3) + (*k2); 87 else 88 p3.push_back(*k2); 89 k2++; 90 } 91 } 92 else 93 break; 94 } 95 for (k3 = p3.begin(); k3 < p3.end(); k3++){ 96 if ((*k3).coe != 0) 97 cout << "[ " << (*k3).coe << ‘ ‘ << (*k3).item << " ] "; 98 } 99 cout << endl; 100 p1.clear(); 101 p2.clear(); 102 p3.clear(); 103 } 104 return 0; 105 }
标签:class main opened sort stl str turn else ios
原文地址:https://www.cnblogs.com/victorique-de-blois/p/11581823.html