《算法笔记》3.2小节——入门模拟->查找元素
1932 Problem A 统计同成绩学生人数
#include <stdio.h>
#include <string.h>
int main() {
int N = 0;
scanf("%d", &N);
while (N!=0) {
int a[1000] = { 0 }, score = 0, cnt = 0;
for (int i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &score);
for (int i = 0; i < N; i++)
if (a[i] == score) cnt++;
printf("%d\n", cnt);
scanf("%d", &N);
}
return 0;
}
1934 Problem B 找x
#include <stdio.h>
#include <string.h>
int main() {
//简单的hash更快
//数组遍历方法
int N = 0;
while (scanf("%d", &N)!=EOF) {
int a[200] = { 0 }, test = 0;
for (int i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &test);
int flag = 0;
for (int i = 0; i < N; i++)
if (a[i] == test) {
printf("%d\n", i);
flag = 1;
}
if (flag == 0) printf("-1\n");
}
return 0;
}
1935 Problem C 查找学生信息
#include <stdio.h>
#include <string.h>
struct student {
char name[1000];
char sex[100];
int age;
};
int main() {
student stu[1010];
int N = 0, M = 0;
while (scanf("%d", &N) != EOF) {
for (int i = 0; i < N; i++) {
int n = 0;
scanf("%d", &n);
scanf("%s %s %d", &stu[n].name, &stu[n].sex, &stu[n].age);
}
scanf("%d", &M);
while (M--) {
char nchar[1000];
int n = 0;
scanf("%s", &nchar);
//用char型数组存储编号,按原形式输出;
sscanf(nchar, "%d", &n);
if (stu[n].age==NULL) printf("No Answer!\n");
//用age判断是否有学生信息,不要用n>N
else printf("%s %s %s %d\n", nchar, stu[n].name, stu[n].sex, stu[n].age);
}
}
return 0;
}
1937 Problem D 查找
#include <stdio.h>
#include <string.h>
int main() {
int n = 0;
while (scanf("%d", &n) != EOF) {
int m = 0;
int a[110] = { 0 }, b[110] = { 0 };
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int flag = 0;
scanf("%d", &b[i]);
for (int j = 0; j < n; j++) {
if (a[j] == b[i]) {
flag = 1;
break;
}
}
if (flag == 0) printf("NO\n");
else printf("YES\n");
//或者用flag;
}
}
return 0;
}
2020 Problem E 学生查询
#include <stdio.h>
#include <string.h>
struct student {
int id;
char name[100];
char sex[20];
int age;
};
int main() {
int n = 0, m = 0;
student stu[30];
scanf("%d", &m);
while (m--) {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int num;
//直接把3号存入数组a[3]中,不用遍历查找
scanf("%d", &num);
stu[num].id = num;
scanf("%s %s %d",&stu[num].name,&stu[num].sex,&stu[num].age);
}
int mp;
scanf("%d", &mp);
printf("%d %s %s %d\n", stu[mp].id, stu[mp].name, stu[mp].sex, stu[mp].age);
}
return 0;
}