Day3 排序和逆序对------sort

it2022-05-05  181

sort

题目: 给你n个整数,请按从大到小的顺序输出其中前m大的数。 Input 每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。 Output 对每组测试数据按从大到小的顺序输出前m大的数。

Sample Input 5 3 3 -35 92 213 -644 Sample Output 213 92 3

思路: 逆序排序,输出前m个数

代码:

#include <iostream> #include <algorithm> using namespace std; bool cmp(int a,int b) { return a>b; } int a[1000005]; int main() { int n,m; ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); while( cin >> n >> m) { for(int i = 0; i < n; i++) cin >> a[i]; sort(a,a+n,cmp); for(int i = 0; i < m; i++) { if(i == m-1) cout << a[i]; else cout << a[i] << " "; } cout << endl; } return 0; }

最新回复(0)