题目链接:
https://pintia.cn/problem-sets/994805260223102976/problems/994805269828059136
AC代码:
#include <iostream>
#include <map>
#include <set>
#include <cmath>
#include <cstdio>
#include <string>
using namespace std;
int isPrime(int n)
{ //返回1表示判断为质数,0为非质数,在此没有进行输入异常检测
float n_sqrt;
if(n==2 || n==3) return 1;
if(n%6!=1 && n%6!=5) return 0;
n_sqrt=floor(sqrt((float)n));
for(int i=5;i<=n_sqrt;i+=6)
{
if(n%(i)==0 | n%(i+2)==0) return 0;
}
return 1;
}
bool IsPrime(int x){
if(x<=1) return false;
int sqr=sqrt(x*1.0);
for(int i=2;i<sqr;i++){
if(x%i==0)
return false;
}
return true;
}
int main()
{
map<string,int> m;
int N;
scanf("%d",&N);
for(int i=1;i<=N;i++){
string ID;
cin>>ID;
m[ID]=i;
}
int K;
set<string> s;
scanf("%d",&K);
for(int i=0;i<K;i++){
string ID;
cin>>ID;
if(s.count(ID)!=0){//已经查询过了
cout<<ID<<": Checked"<<endl;
}
else if(m[ID]==1){//冠军
cout<<ID<<": Mystery Award"<<endl;
}
else if(isPrime(m[ID])){//是素数
cout<<ID<<": Minion"<<endl;
}
else if(m[ID]==0){//不存在的ID
cout<<ID<<": Are you kidding?"<<endl;
}
else{
cout<<ID<<": Chocolate"<<endl;
}
if(m[ID]!=0)//在存在的情况下,再检查是否查询过
s.insert(ID);
}
}
二刷:
#include <iostream>
#include <string>
#include <cstdio>
#include <map>
#include <cmath>
using namespace std;
const int maxn=10010;
int hashtable[maxn]={0};
map<int,string> m;
int N;
bool isprime(int n){
if(n<=1) return false;
int sqr=(int)sqrt(1.0*n);
for(int i=2;i<=sqr;i++){
if(n%i==0)
return false;
}
return true;
}
int main()
{
scanf("%d",&N);
for(int i=1;i<=N;i++){
int id;
scanf("%d",&id);
if(i==1)
m[id]="Mystery Award";
else if(isprime(i))
m[id]="Minion";
else
m[id]="Chocolate";
hashtable[id]=1;//表示存在
}
int M;
scanf("%d",&M);
for(int i=1;i<=M;i++){
int id;
scanf("%d",&id);
if(hashtable[id]==1){//正常查询
printf("%04d: ",id);
cout<<m[id]<<endl;
hashtable[id]=2;
}
else if(hashtable[id]==2){//查询过了
printf("%04d: ",id);
cout<<"Checked"<<endl;
}
else if(hashtable[id]==0) {//不在排名中
printf("%04d: Are you kidding?\n",id);
}
}
return 0;
}