LoginSignup
0
0

More than 1 year has passed since last update.

ローカルでの実行はうまくいくが、コードテストでRuntime Error

Last updated at Posted at 2021-10-16

AOJのITP2_1_Bにて問題発生

https://onlinejudge.u-aizu.ac.jp/courses/lesson/8/ITP2/all/ITP2_1_B
を下のコードで実装。

#include <iostream>
#include <vector>
using namespace std;

const int MAX = 400005;
vector<int> queue(MAX);
int tail = 0,head = 0;


void init(){
    head = 0 , tail = 0;
}

bool isEmpty(){
    return head == tail;
}

bool isFull(){
    return  (tail + 1)%MAX == head ;
}

void push_head(int x){
    if(isFull()){
        cout << "error : queue is full." << endl;
    }
    else{
        queue[head] = x;
        head = (head-1)%MAX;
    }
}

void push_tail(int x){
    if(isFull()){
        cout << "error : queue is full." << endl;
    }
    else{
        tail = (tail + 1)%MAX;
        queue[tail] = x;
    }
}

int randomAccess(int p){
    return queue[(head+p+1)%MAX];
}

void pop(int d){
    if(isEmpty()){
        cout << "error : queue is full." << endl;
    }
    else if(d == 0) head = (head+1)%MAX;
    else tail = (tail - 1)%MAX;
}

//headの挿入: queue[head]に値を入れてからhead <- (head-1)%MAX
//taiilの挿入 : (tail+1)%MAXとしてからqueue[tail]
int main(){
    init();
    int q;
    cin >> q;
    vector<int> query(q),num_1(q,-1);
    vector<int> num_2(q,-1);
    for(int i=0;i<q;i++){
        cin >> query[i];
        if(query[i]==1||query[i]==2) cin >> num_1[i];
        else cin >> num_1[i] >> num_2[i];
    }
    for(int i=0;i<q;i++){
        if(query[i]==0){
            if(num_1[i]==0) push_head(num_2[i]);
            else push_tail(num_2[i]);
        }
        else if(query[i]==1) cout << randomAccess(num_1[i]) << endl;
        else pop(num_1[i]);
    }
    return 0;
}

ローカルでの実行はうまくいったが、AOJのジャッジではRuntime Error...

解決までの道筋

Atcoderのコードテストに通してみると、出力はうまくいくがエラーコード139が出る。
→調べてみると、これは配列の範囲外にアクセスしていることが原因の一つとして考えられるらしい。
→下のコードが怪しい...

else tail = (tail - 1)%MAX;

C++では(負の値)%nは負の値を返す!!

これに注意して下のように変更すると、無事ACできました。

if(tail==0) tail = tail -1 + MAX;
else tail = (tail-1)%MAX;

(modintを使うとこのような心配もなくなるかも)

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0