📜  用户定义数据类型的多集

📅  最后修改于: 2021-05-31 22:53:19             🧑  作者: Mango

您将获得Q查询。每个查询包含一个整数k和一个人的信息,即名字,姓氏,年龄。对于每个查询,如果所有人员信息均按升序排列,则需要输出其中的第K个人员。
注:某甲来自人B之前,如果A第一个名字是比B的字典小。但是,如果姓氏相同,则我们将比较姓氏;如果姓氏也相同,则我们将必须比较其年龄

给定:K将始终小于或等于在场人数。
例子:

Input : Q = 2
        1
        aa bb 10
        2 
        bb cc 10
Output :
First name:aa
Last name:bb
Age: 10

First name:bb
Last name:cc
Age: 10

方法:下面的算法可以解决上述问题。

  • 基本上,我们为每个查询提供人员详细信息,我们必须告诉Kth人员是否按升序排列。
  • 基本方法:每次查询后,我们对列表进行排序,仅打印第k个人的详细信息。但是,如果我们使用排序解决了上述问题,那么时间复杂度将为O(q * q * log(q))。即,O(qlog(q))用于对每个时间和q个查询进行排序。
  • 优化:我们可以改善上述问题的时间复杂度。众所周知,多集插入可以在log(n)中完成。
  • 因此,只需制作一个可用于存储结构的多重集,然后在每次查询之后,只需将人的详细信息插入我们的多重集中即可。
  • 因此,这似乎是一种更好的方法,我们的整体复杂度将为O(q * log(q))。
// CPP program for queries to find k-th person where
// people are considered in lexicographic order of
// first name, then last name, then age
#include 
using namespace std;
  
struct person {
    string firstName, lastName;
    int age;
};
  
// operator overloading to use multiset for user 
// define data type.
bool operator<(person a, person b)
{
    if (a.firstName < b.firstName)
        return true;
    else if (a.firstName == b.firstName) {
        if (a.lastName < b.lastName)
            return true;
        else if (a.lastName == b.lastName) {
            if (a.age < b.age)
                return true;
            else
                return false;
        }
        else
            return false;
    }
    else
        return false;
}
  
// define function for printing our output
void print(multiset::iterator it)
{
    cout << "First name:" << it->firstName << endl;
    cout << "Last name:" << it->lastName << endl;
    cout << "Age: " << it->age << endl;
}
  
int main()
{
    int q = 2;
  
    // define set for structure
    multiset s;
  
    // declaration of person structure
    person p;
  
    // 1st Query k=1, first-name=aa, last-name=bb, age=10;
    int k = 1;
    p.firstName = "aa";
    p.lastName = "bb";
    p.age = 10;
  
    // now insert this structure in our set.
    s.insert(p);
  
    // now find Kth smallest element in set.
    multiset::iterator it;
    it = s.begin();
  
    // find kth element by increment iterator by k
    std::advance(it, k - 1);
    print(it);
  
    // 2nd Query k=2, first-name=bb, last-name=cc, age=10;
    k = 2;
    p.firstName = "bb";
    p.lastName = "cc";
    p.age = 10;
  
    // now insert this structure in our set.
    s.insert(p);
  
    // now find Kth smallest element in set.
    it = s.begin();
  
    // find kth element by increment iterator by k
    std::advance(it, k - 1);
    print(it);
    return 0;
}
输出:
First name:aa
Last name:bb
Age: 10
First name:bb
Last name:cc
Age: 10
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”