问题代码。。改了一下午。。。示例程序结果没问题。。没事干的大神帮忙瞅瞅挑挑刺~
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
#include <stdlib.h>
#include <string.h>
bool printRslt(int n, int arr[])
{
cout << "Runtime = ";
if(n==0)
{
cout<<arr[0]<<endl;
return true;
}
if(n==1)
{
if(arr[1]==1)cout<<"n";
else
cout<<arr[1]<<"*n";
n--;
}
//highest bit
if(n>1)
{
if(arr[n]==1)cout<<"n^"<<n;
else
cout<<arr[n]<<"*n^"<<n;
n--;
for(;n>1;n--)
{
if(arr[n]==0)continue;
if(arr[n]==1)cout<<"+n^"<<n;
else
cout<<"+"<<arr[n]<<"*n^"<<n;
}
}
if(n==1)
{
if(arr[1]==1)cout<<"+n";
else if(arr[1]>1)
cout<<"+"<<arr[1]<<"*n";
n--;
}
if(n==0)
{
if(arr[0]!=0)
cout<<"+"<<arr[0];
cout<<endl;
}
return true;
}
int main()
{
int tstNum;
cin>>tstNum;
int iter=0;
while ( iter++ < tstNum )
{
string tmpStr = "" ;
int tmpNum = 0;
cin >> tmpStr;
if (tmpStr!="BEGIN")
{
cerr<<"Not legal program! ";
}
int opStack[1000][2];
int top = 0;
opStack[top][0] = 0;//begin
top ++;
int arrParam[10] = {0};//save the final result
int tmp = 0;//current ^
while(top)
{
cin >> tmpStr;
if (tmpStr=="LOOP")
{
opStack[top][0] = 2;//LOOP
cin >> tmpStr;
tmpNum = (tmpStr[0] == 'n') ? -1 :atoi(tmpStr.c_str());
opStack[top][1] = tmpNum;
top ++;
}else if (tmpStr=="OP")
{
opStack[top][0] = 1;//op
cin >> tmpNum;
opStack[top][1] = tmpNum;
top ++;
}else
{
while(top>0)//pop until meet loop
{
top --;
if (opStack[top][0]==0)//begin
{
cout<<"Program #" << iter << endl;
printRslt(tmp,arrParam);
cout<<endl;
}
else if (opStack[top][0]==1)//op
{
arrParam[0] += opStack[top][1];
}
else if(opStack[top][0]==2)//loop
{
if(opStack[top][1]==-1)
{
tmp ++;
for(int i=tmp; i>0; i--)
{
arrParam[i] = arrParam[i-1];
}
arrParam[0] = 0;
}
else
{
for(int i=tmp; i>=0; i--)
{
arrParam[i] *= opStack[top][1];
}
}
break;
}
}
}
}
}
return 0;
}