AOJ 2435 : Zero Division Checker
問題リンク:Zero Division Checker | Aizu Online Judge
問題概要:
m個の変数とn個の要素が与えられ、与えられた逆ポーランド記法の擬似コードにそって計算した際に0の割り算が起こる可能性があるなら"error"と出力、それ以外は"correct"と出力せよ
使用した言語 : C++
解法:
実際に計算してみて0割り算が起こるかどうか判定する
n個の要素をもつ式が必ずとも正しいとは限らないみたいなので逆ポーランド記法になっていないものも"error"と出力しなければならない
式が間違っているとは0割り算をしてしまう可能性があること、と定義されていたので文法ミスはないのかと思ったけどなぜかランタイムエラーが出ていたので文法ミスにも"error"を出力したら通った
しかし別の人のコードを読んでみたらそういった処理をせずに通している人がいたりした
自分の実装の仕方がわるいのか
コード;
bool calc(set<int>& B,set<int>& A,string& ope,stack<set<int> >& ele,map<string,set<int> >& index) { set<int> C; for(set<int>::iterator it_A = A.begin();it_A != A.end();it_A++) { for(set<int>::iterator it_B = B.begin();it_B != B.end();it_B++) { if(ope == "+") { C.insert(((*it_A)+(*it_B))%256); } else if(ope == "-") { C.insert(((*it_A)-(*it_B)+256)%256); } else if(ope == "*") { C.insert(((*it_A)*(*it_B))%256); } else if(ope == "/") { if(!(*it_B)) { return false; } C.insert(((*it_A)/(*it_B))%256); } else assert(false); } } index[My] = C; // #define My NEETISGOD ele.push(C); return true; } int main(){ int m,n; map<string,set<int> > index; stack<set<int> > ele; deque<string> st; bool fin = false; cin >> m; for(int i=0;i<m;i++) { string name; int lb,ub; cin >> name >> lb >> ub; for(int j = lb;j <= ub;j++) index[name].insert(j); } cin >> n; for(int i=0;i<n;i++) { string e; cin >> e; if(fin) continue; if(e != "/" && e != "*" && e != "-" && e != "+") { if(index.find(e) != index.end()) { ele.push(index[e]); } else { set<int> FGS; FGS.insert((atoi)(e.c_str())); ele.push(FGS); } } else { set<int> A,B; if(ele.empty()) { fin = true; continue; } B = ele.top(),ele.pop(); if(ele.empty()) { fin = true; continue; } A = ele.top(),ele.pop(); if(!calc(B,A,e,ele,index)) fin = true; } } if(fin) { cout << "error" << endl; return 0; } cout << "correct" << endl; return 0; }