#include #include #include using namespace std; class Complex Eval(const char *str,int start,int end); int GetRightParenthesis(const char *str,int trg); class Complex{ public : int x;// int y;// x + y i Complex(int x,int y); void Print(); void Add(Complex &c); void Sub(Complex &c); void Mul(Complex &c); bool IsOverflow(); }; class Overflow{}; Complex::Complex(int x,int y){ this->x = x; this->y = y; } void Complex::Print(){ if(x==0 && y==0){ printf("0\n"); }else if(x==0){ printf("%di\n",y); }else if(y==0){ printf("%d\n",x); }else{ printf("%d%c%di\n",x,(y>0?'+':'-'),(y>0?y:-y)); } } void Complex::Add(Complex &c){ this->x += c.x; this->y += c.y; } void Complex::Sub(Complex &c){ this->x -= c.x; this->y -= c.y; } void Complex::Mul(Complex &c){ int tmp; tmp = (this->x * c.x) - (this->y * c.y); this->y = (this->x * c.y) + (this->y * c.x); this->x = tmp; } bool Complex::IsOverflow(){ return (x<-10000 || x>10000 || y<-10000 || y>10000); } Complex Eval(const char *str,int start,int end){ list lc; list::iterator plc; list lr; list::iterator plr; int now,tmp; Complex * ptmpc; now = start; try{ // パーシング while(now<=end){ switch(str[now]){ case '+': case '-' : case '*' : lr.push_back(str[now]); now++; break; case 'i' : lc.push_back(new Complex(0,1)); now++; break; case '(' : tmp = GetRightParenthesis(str,now); lc.push_back(new Complex(Eval(str,now+1,tmp-1))); now = tmp+1; break; default : //残りは数字 tmp = 0; while(now<=end && isdigit(str[now])){ tmp = tmp*10 + str[now] -'0'; now++; if(tmp > 10000) throw Overflow(); } lc.push_back(new Complex(tmp,0)); } } //演算実行 plc = lc.begin(); plr = lr.begin(); while(plr != lr.end()){ if(*plr == '*'){ ptmpc = *plc; plc++; ptmpc->Mul(**plc); plr = lr.erase(plr); lc.erase(plc); plc--; if(ptmpc->IsOverflow()) throw Overflow(); }else{ plr++; plc++; } } plc = lc.begin(); plr = lr.begin(); while(plr != lr.end()){ ptmpc = *plc; plc++; if(*plr == '+'){ ptmpc->Add(**plc); }else{ ptmpc->Sub(**plc); } plr = lr.erase(plr); lc.erase(plc); plc--; if(ptmpc->IsOverflow()) throw Overflow(); } }catch(...){ plc = lc.begin(); while(plc!= lc.end()){ delete *plc; plc++; } throw; } Complex answer(*(lc.front())); plc = lc.begin(); while(plc!= lc.end()){ delete *plc; plc++; } return answer; } int GetRightParenthesis(const char *str,int trg){ int lev=0; int now=trg; while(true){ if(str[now]=='('){ lev++; }else if(str[now]==')'){ lev--; if(lev==0) return now; } now++; } } int main(void){ char buf[128];//最大100文字までですけど。 int end; Complex answer(0,0); while(fgets(buf,sizeof(buf),stdin)!=NULL){ end = strlen(buf); end--; while(buf[end]=='\r'||buf[end]=='\n') end--; try{ answer = Eval(buf,0,end); answer.Print(); }catch(Overflow){ puts("overflow"); } } }