题解
坑点:
- 1、多组输入测试,写单组的过不了
- 2、需要稳定pai
- 自带的sort是非稳定排序,题目要求是稳定排序
- sort在数据量多的话是不稳定排序,stable_sort是稳定排序
01.无法AC的代码『sort』
#include<bits/stdc++.h> using namespace std; struct node { string name; int val; }; //升序 bool one(node a, node b) { return a.val<b.val; } bool zero(node a, node b) { return a.val>b.val; } int main() { int n; int select; while(cin>>n>>select) { vector<node> solve(n); for(int i=0; i<n; ++i) { cin>> solve[i].name >> solve[i].val; } if( 0==select ) { sort( solve.begin(), solve.end(), zero ); } else if( 1==select ) { sort( solve.begin(), solve.end(), one ); } //cout<<"n==="<<n<<endl; for(int i=0; i<n; ++i) { cout << solve[i].name << " " << solve[i].val << endl; } } return 0; }
02.AC的代码『stable_sort』
- 用的stable_sort
#include<bits/stdc++.h> using namespace std; struct node { string name; int val; }; //升序 bool one(node a, node b) { return a.val<b.val; } bool zero(node a, node b) { return a.val>b.val; } int main() { int n; int select; while(cin>>n>>select) { vector<node> solve(n); for(int i=0; i<n; ++i) { cin>> solve[i].name >> solve[i].val; } if( 0==select ) { stable_sort( solve.begin(), solve.end(), zero ); } else if( 1==select ) { stable_sort( solve.begin(), solve.end(), one ); } //cout<<"n==="<<n<<endl; for(int i=0; i<n; ++i) { cout << solve[i].name << " " << solve[i].val << endl; } } return 0; }