我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED
原题链接:
PAT-BASIC1059:https://pintia.cn/problem-sets/994805260223102976/problems/994805269828059136
PAT-ADVANCED1116:https://pintia.cn/problem-sets/994805342720868352/problems/994805355358306304
题目描述:
PAT-BASIC1059:
PAT-ADVANCED1116:
知识点:素数
思路一:用一个大小为10000的数组记录排名
时间复杂度是O(N)。空间复杂度是O(10000)。
C++代码:
#include<iostream>
#include<cmath>
using namespace std;
int ranks[10000];
bool isPrime(int num);
int main() {
fill(ranks, ranks + 10000, 0);
int N;
scanf("%d", &N);
int num;
for(int i = 1; i <= N; i++) {
scanf("%d", &num);
ranks[num] = i;
}
int K;
scanf("%d", &K);
for(int i = 0; i < K; i++) {
scanf("%d", &num);
printf("%04d: ", num);
if(ranks[num] == -1){
printf("Checked\n");
}else if(ranks[num] == 1) {
printf("Mystery Award\n");
ranks[num] = -1;
} else if(ranks[num] == 0) {
printf("Are you kidding?\n");
} else if(isPrime(ranks[num])) {
printf("Minion\n");
ranks[num] = -1;
} else {
printf("Chocolate\n");
ranks[num] = -1;
}
}
return 0;
}
bool isPrime(int num) {
if(num == 1) {
return false;
}
for(int i = 2; i <= sqrt(num); i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
C++解题报告:
思路二:埃氏筛法判断素数
除了在素数的判断上和思路一不同,其余和思路一均相同。
先用埃氏筛法对[1, 10000]中的每个数据做判断,判断其是否为数据,用一个数组flag[10001]记录判断结果。如果flag[i] == true,表示i是素数,否则,i不是素数。之后查询是否是素数的时间复杂度就成了O(1)。
时间复杂度是O(10000loglog(10000))。空间复杂度是O(10000)。
C++代码:
#include<iostream>
#include<cmath>
using namespace std;
int ranks[10000];
bool flag[10001];
void findPrime();
int main() {
fill(ranks, ranks + 10000, 0);
fill(flag, flag + 10001, true);
findPrime();
int N;
scanf("%d", &N);
int num;
for(int i = 1; i <= N; i++) {
scanf("%d", &num);
ranks[num] = i;
}
int K;
scanf("%d", &K);
for(int i = 0; i < K; i++) {
scanf("%d", &num);
printf("%04d: ", num);
if(ranks[num] == -1){
printf("Checked\n");
}else if(ranks[num] == 1) {
printf("Mystery Award\n");
ranks[num] = -1;
} else if(ranks[num] == 0) {
printf("Are you kidding?\n");
} else if(flag[ranks[num]]) {
printf("Minion\n");
ranks[num] = -1;
} else {
printf("Chocolate\n");
ranks[num] = -1;
}
}
return 0;
}
void findPrime(){
flag[1] = false;
flag[2] = true;
for(int i = 2; i < 10001; i++){
if(flag[i]){
for(int j = i + i; j < 10001; j += i){
flag[j] = false;
}
}
}
}
C++解题报告: