查找学生信息(结构体sort+二分查找)

题目描述
输入N个学生的信息,然后进行查询。

输入描述:
输入的第一行为N,即学生的个数(N<=1000)
接下来的N行包括N个学生的信息,信息格式如下:
01 李江 男 21
02 刘唐 男 23
03 张军 男 19
04 王娜 女 19
然后输入一个M(M<=10000),接下来会有M行,代表M次查询,每行输入一个学号,格式如下:
02
03
01
04


输出描述:
输出M行,每行包括一个对应于查询的学生的信息。
如果没有对应的学生信息,则输出“No Answer!”


示例1
输入
4
01 李江 男 21
02 刘唐 男 23
03 张军 男 19
04 王娜 女 19
5
02
03
01
04
03
输出
02 刘唐 男 23
03 张军 男 19
01 李江 男 21
04 王娜 女 19
03 张军 男 19
 

 

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
#include <stack>
using namespace std;


typedef struct Student {
    string no; // 若int   则输入01 --> 变成1
    string name;
    string sex;
    int age;

} Student;

vector<Student> res;

bool compare(Student& a, Student& b) {
    int x = atoi(a.no.c_str());
    int y = atoi(b.no.c_str());
    return x < y;

    /*
    string a > string b
    (应该是)比起来不看长度  只看第一个char。
    */
}

// 普通查找,不用
void query(string no) {
    for(int i = 0; i <= res.size() - 1; i++) {
        if (res[i].no == no) {
            cout << res[i].no << " " << res[i].name << " " << res[i].sex << " " << res[i].age << endl;
            return ;
        }
    }
    cout << "No Answer" << endl;
}


int toInt(string s) {
    return atoi(s.c_str());
}


void binarySearch(int low, int high, string no) {

    if (low > high) {
        cout << "No Answer" << endl;
    } else {
// 0001  002 003
        int mid = (low + high) / 2;
        if (res[mid].no == no) {
            cout << res[mid].no << " " << res[mid].name << " " << res[mid].sex << " " << res[mid].age << endl;
        } else if(toInt(no) < toInt(res[mid].no)) {
            return binarySearch(low, mid - 1, no);
        } else if(toInt(no) > toInt(res[mid].no)) {
            return binarySearch(mid + 1, high, no);
        }
    }
}


int main() {
    int n;
    cin >> n;

    while(n--) {
        Student t;
        cin >> t.no >> t.name >> t.sex >> t.age;
        res.push_back(t);
    }
    sort(res.begin(), res.end(), compare);
    int m;
    cin >> m;
    while(m--) {
        string t;
        cin >> t;
        binarySearch(0, res.size() - 1, t);
    }


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值