这类题目归结于常用技巧与算法,有很鲜明的套路,重在理解其规则,通常写起来不算太复杂。
题目描述:
题目大致意思:
输出在年龄(a,b)段内的m个富豪。
大致思路:
用一个结构体数组来接收N个输入,对结构体数组按财富值进行排序,如果财富值相等,则按年龄进行排序,如果年龄也相等,则按姓名进行排序。排序好后,针对每一个查询,对结构体数组进行一次遍历,查找符合年龄条件的结构体,并进行输出。
提交结果:
提交代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
struct Node
{
string name;
int age;
int worth;
};
vector<Node> arr;
bool cmp(Node node1, Node node2)
{
if (node1.worth != node2.worth)
return node1.worth > node2.worth;
else if (node1.age != node2.age)
return node1.age < node2.age;
else
return node1.name < node2.name;
}
int main()
{
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++)
{
Node node;
cin >> node.name >> node.age >> node.worth;
arr.push_back(node);
}
sort(arr.begin(), arr.end(), cmp);
for (int i = 0; i < k; i++)
{
int m, min, max;
cin >> m >> min >> max;
int index = 0;
cout << "Case #" << i + 1 <<":"<< endl;
for (int j = 0; j < arr.size(); j++)
{
if (index == m)
break;
if (arr[j].age >= min && arr[j].age <= max)
{
cout << arr[j].name << " " << arr[j].age << " " << arr[j].worth << endl;
index++;
}
}
if (index == 0)
cout << "None" << endl;
}
}
本次提交后累计得分548,排名为13941。