题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000
思路:分别收录两个多项式(vector<pair<int,double> >),进行归并操作。
收获: pair 头文件 utility ; pair<int,int> p = make_pair(a,b); 可用pair替代结构体。
1 #include<stdio.h> 2 #include<map> 3 #include<vector> 4 #include<utility> 5 using namespace std; 6 7 vector<pair<int,double> >p1,p2,p3; 8 int main(){ 9 int m,n; 10 scanf("%d",&m); 11 for(int i = 0; i < m ; i++){ 12 int a; 13 double b; 14 scanf("%d %lf",&a,&b); 15 p1.push_back(pair<int,double>(a,b)); 16 } 17 scanf("%d",&n); 18 for(int i = 0; i < n ; i++){ 19 int a; 20 double b; 21 scanf("%d %lf",&a,&b); 22 p2.push_back(pair<int,double>(a,b)); 23 } 24 int i , j ; 25 for (i = 0, j = 0; i < m&&j < n; ){ 26 if(p1[i].first == p2[j].first){ 27 if(p1[i].second + p2[j].second){ 28 p3.push_back(pair<int,double>(p1[i].first,p1[i].second + p2[j].second)); 29 } 30 i++; 31 j++; 32 }else if(p1[i].first > p2[j].first){ 33 p3.push_back(p1[i]); 34 i++; 35 }else{ 36 p3.push_back(p2[j]); 37 j++; 38 } 39 } 40 while(i < m){ 41 p3.push_back(p1[i]); 42 i++; 43 } 44 while(j < n){ 45 p3.push_back(p2[j]); 46 j++; 47 } 48 int p = p3.size(); 49 printf("%d",p); 50 for(int k = 0; k < p; k++){ 51 printf(" %d %.1f",p3[k].first,p3[k].second); 52 } 53 return 0; 54 }