九度OJ 1069 查找学生信息(二分查找)

原题地址:http://ac.jobdu.com/problem.php?pid=1069

题目描述:

 输入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!”
样例输入:
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
来源:

2003年清华大学计算机研究生机试真题

本题是查找里面最基础的水题了,复习了一下复杂度为O(logn)的二分查找

AC代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>
#define MAXN 1001
using namespace std;

typedef struct node
{
    string id,name,sex; //id格式是字符串
    int age;
    bool operator < (const node & A) const //学号升序,重载小于
    {
        return id < A.id;
    }
}STUDENT;
STUDENT s[MAXN];
int N;

int binary_search(const string &num) //二分搜索匹配id
{
    int l=0, r=N-1, mid, ans = -1;
    while (l<=r)
    {
        mid = (l+r)/2;
        if (s[mid].id == num)
        {
            ans = mid;
            break;
        }
        if (num < s[mid].id) r = mid-1;
        else l = mid+1;
    }
    return ans;
}

int main()
{
    int M, index;
    string num;
    while (cin >> N)
    {
        for (int i = 0; i < N; ++i)
            cin >> s[i].id >> s[i].name >> s[i].sex >> s[i].age;
        sort(s, s+N);
        cin >> M;
        while (M--)
        {
            cin >> num;
            index = binary_search(num);
            if (index != -1)
                cout << s[index].id << ' ' << s[index].name << ' ' << s[index].sex << ' ' << s[index].age << endl;
            else cout << "No Answer!" << endl;
        }
    }
    return 0;
}

内存占用:1560Kb 耗时:170ms

算法复杂度: O(logn)

posted @ 2017-03-25 20:30  Lecholin  阅读(207)  评论(0编辑  收藏  举报