数组实现队列#2#3#9未过的原因
查看原帖
数组实现队列#2#3#9未过的原因
1091709
Cloud_Ivy37楼主2024/4/23 15:44

70 points code:

#include<iostream>
using namespace std;
const int N=1e2+5;
int m,n,queue[N],head,tail=-1,ans;
//入队
void Queue_Push(int x){
    queue[++tail]=x;
}
//出队
void Queue_Pop(){
    head++;
}
//查询队头
int Queue_Head(){
   return queue[head]; 
}
//查询队尾
int Queue_Tail(){
   return queue[tail]; 
}
//判空
bool Queue_Empty(){
    if(head<=tail) return false;
    else return true;
}
//判断队列满
bool Queue_Fill(){
    if(m-tail>1) return false;
    else return true;
}
bool Queue_Travel(int x){
    for(int i=head;i<=tail;i++){
        if(queue[i]==x){
            return true;
        }
    }
    return false;
}
int main(){
    cin>>m>>n;
    while(n--){
        int x;
        cin>>x;
        if(Queue_Empty()){
            Queue_Push(x);
            ans++;
        }
        else{
            if(!Queue_Travel(x)){
                if(Queue_Fill()) Queue_Pop();
                Queue_Push(x);
                ans++;
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

把数组开大一点就能AC:

#include<iostream>
using namespace std;
const int N=1e5+5;
int m,n,queue[N],head,tail=-1,ans;
//入队
void Queue_Push(int x){
    queue[++tail]=x;
}
//出队
void Queue_Pop(){
    head++;
}
//查询队头
int Queue_Head(){
   return queue[head]; 
}
//查询队尾
int Queue_Tail(){
   return queue[tail]; 
}
//判空
bool Queue_Empty(){
    if(head<=tail) return false;
    else return true;
}
//判断队列满
bool Queue_Fill(){
    if(m-tail>1) return false;
    else return true;
}
//查询队列元素值为x
bool Queue_Travel(int x){
    for(int i=head;i<=tail;i++){
        if(queue[i]==x){
            return true;
        }
    }
    return false;
}
int main(){
    cin>>m>>n;
    while(n--){
        int x;
        cin>>x;
        if(Queue_Empty()){
            Queue_Push(x);
            ans++;
        }
        else{
            if(!Queue_Travel(x)){
                if(Queue_Fill()) Queue_Pop();
                Queue_Push(x);
                ans++;
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}
2024/4/23 15:44
加载中...