【Codeup】1935: 查找学生信息

时间限制: 1 Sec  内存限制: 32 MB

题目描述

输入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!”

样例输入

5
001 张三 男 19
002 李四 男 20
003 王五 男 18
004 赵六 女 17
005 刘七 女 21
7
003
002
005
004
003
001
006

样例输出

003 王五 男 18
002 李四 男 20
005 刘七 女 21
004 赵六 女 17
003 王五 男 18
001 张三 男 19
No Answer!

这里由于学号的唯一性,故采用字符串学号转整型数字下标的方法存储在学生数据数组中,从而查找更快,效率更高。
#include <cstdio>
#include <string.h>
#include <cmath>
const int MAXN = 1010;
int ID(char a[])	//字符串转化成整型数字
{
	int temp[100] = { 0 };
	int num = 0;
	int j = 0;
	for (int i = 0; i < strlen(a); i++)
	{
		if (a[i] != '0')
		{
			while (i < strlen(a))
			{
				temp[j] = a[i] - '0';
				j++;
				i++;
			}
			break;
		}
	}
	int k = j;
	for (int i = 0; i < j; i++)
	{
		num += temp[i] * pow(10, --k);
	}
	return num;
}
struct student{
	char id[100];
	char name[200];
	char gender[10];
	int age;
	student(){
		strcpy(id, "0");
	}
}stu[MAXN];
int main()
{
	int N, M;
	char t[100] = { '0' };
	while (~scanf("%d", &N))
	{
		while (N--)
		{
			scanf("%s", &t);
			int idd = ID(t);
			strcpy(stu[idd].id, t);
			scanf("%s %s %d", &stu[idd].name, &stu[idd].gender, &stu[idd].age);
		}
		scanf("%d", &M);
		while (M--)
		{
			scanf("%s", &t);
			int idd = ID(t);
			strcmp(stu[idd].id, "0") == 0 ? printf("No Answer!\n") : printf("%s %s %s %d\n", stu[idd].id, stu[idd].name, stu[idd].gender, stu[idd].age);
		}
	}
	return 0;
}

在线OJ测试时间为10ms,比传统的遍历方式(43ms)显著提升了速度。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值