[注] 下面粘贴的代码中会出现 “undefined” 这个是多余的,自行删去,我在编辑界面看不到,只有在浏览界面看见,不知道是什么原因。
【问题描述】
编写一个实验程序,利用STL中的priority_queue(优先队列)求出包含n个元素的无序整数序列中第k小的元素,其中n和k由用户输入。
【输入形式】第一行为一个整数,表示n的值。
第二行为n个整数,每个整数之间以一个空格间隔。
第三行为一个整数,表示k的值。
【输出形式】第k小的元素。
【样例输入1】5
1 2 4 3 5
3
【样例输出1】3
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
struct myComp
{
bool operator() (const long long &a,const long long &b)
{
//由小到大采用 ">" 号,由大到小则采用 "<" 号
return a>b;
}
};
int main()
{
int N,k,i;
int cin_value;
priority_queue<int,vector<int>,greater<int> > q; //greater升序
cin >> N;
for (i=1;i<=N;i++)
{
cin >> cin_value;
q.push(cin_value);
}
cin >> k;
for (i=1;i<=N;i++)
{
if(i==k)
{
cout << q.top() << endl; ;
break;
}
else
{
q.pop();
}
}
return 0;
}
运行结果
2.
代码
#include<bits/stdc++.h>
using namespace std;
class Student { //学生类
public:
int Tall; //身高
int Weight; //体重
bool operator<(const Student &other) const {//重载“<”符,定义出优先队列次序。
if (Tall > other.Tall){
return true;
}
else if (Tall == other.Tall) {
//身高相同,看体重。 '>'代表重载符号,不代表大于
//由小到大采用 ">" 号,由大到小则采用 "<" 号
return Weight > other.Weight ;// 填空1
} else {
return false;
}
}
};
int main()
{ //
priority_queue<Student> q; //利用优先队列
int m;
Student Stu;
cin >> m;
for( int i=0; i<m; i++){
cin >> Stu.Tall;
cin >> Stu.Weight;
q.push(Stu) ; //(填空)2
}
for( int i=0; i<m; i++){
Stu = q.top() ; //(填空)3
q.pop();
cout << Stu.Tall << " " << Stu.Weight << endl;
}
return 0;
}
运行结果
3.按指定规则order(升序/降序)对若干组数列进行排序。
注:输入数据可能有多组。
【输入形式】
每组,第1行,1个整数(order:1,升序;-1,降序;0,结束) 。 第2行, 1个整数n。第3行,n个整数(组成待排序数列),用空格分隔。
【输出形式】
完成排序后的该数列,每个数之间用空格分隔(各个整数<=10^9)。
【样例输入】
1
3
2 1 3
-1
4
1 3 2 4
0
【样例输出】
1 2 3
4 3 2 1
分析:使用STL sort排序
int A[100];
bool cmp1(int a,int b)//int为数组数据类型
{
return a>b;//降序排列
//return a<b;//默认的升序排列
}
sort(A,A+100,cmp1); //数组太大会导致栈溢出
sort(a,a+n,compare); // 降序需要传第三个参数
sort(a,a+n); // 升序不需要传第三个参数
代码如下:
#include<iostream>
#include<algorithm>
using namespace std;
const int size=1001;
int a[size];
bool compare( int a, int b)
{
return a>b;//降序 * 填空1 *
}
int main()
{
#if 1
int order;
cin>>order;
while( 0 != order ){
int n;
cin>>n;
for( int i=0; i<n; i++){
cin>>a[i];
}
if( order < 0 ){
//* 填空2 * 不能用 a+size,因为数组太大,栈溢出。
sort(a,a+n,compare); // 降序(定义排序规则),在这里就不需要对compare函数传入参数了。
cout<< "降序" << endl;
//
}else{
//* 填空3 *不能用 a+size,因为数组太大,栈溢出
sort(a,a+n); // 升序(默认)。
cout<< "升序" << endl;
}
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cin>>order;
}
#endif
return 0;
}
运行结果