#include <iostream> #include <queue> using namespace std; class People { private: int index; string name; short age; public: People(int index, string &name, short age) : index(index), name(move(name)), age(age){} bool operator >(const People& p) const { if (age > p.age ) return true; else if (age == p.age && index > p.index) return true; else if (age == p.age && index == p.index && name > p.name) return true; else return false; } friend ostream& operator <<(ostream &out, const People &p) { out << p.index << ' ' << p.name << ' ' << p.age << endl; return out; } }; int main() { int num; cin >> num; priority_queue<People, vector<People>, greater<People>> heap_p; while (num-- > 0) { int index; string name; short age; cin >> index >> name >> age; heap_p.emplace(index, name, age); } for (int i = 0; i < 3; i++) { cout << heap_p.top(); heap_p.pop(); } } // 64 位输出请用 printf("%lld")
使用小顶堆完成top k问题