又见神模拟题。。。。。
虽然处理起来感觉比较麻烦,但是思路还是比较清晰的,就是一个普通的栈。代码写的挫了一点....
注意 LOOP 0 的情况。
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <cmath>
#include <algorithm>
using namespace std;
struct N
{
int ty,coe,ind;
}st[10000000];
bool cmp(N a,N b)
{
if(a.ty == b.ty)
{
return a.ind > b.ind;
}
return a.ty < b.ty;
}
int main()
{
int icase = 0;
int T;
int top;
int i,j,len;
int mark,w;
char kw[20];
scanf("%d",&T);
while(T--)
{
top = 0;
mark = 1;
scanf("%s",kw);
while(mark)
{
scanf("%s",kw);
if(strcmp(kw,"LOOP") == 0)
{
mark++;
scanf("%s",kw);
for(i = 0;kw[i] == ' '; ++i)
;
if(kw[i] == 'n')
{
st[top].ty = 0;
st[top].coe = 1;
st[top].ind = 1;
top++;
}
else
{
for(w = 0,len = strlen(kw);i < len; ++i)
{
w += kw[i] - '0';
w *= 10;
}
w /= 10;
st[top].coe = w;
st[top].ind = 0;
st[top].ty = 1;
top++;
}
}
else if(strcmp(kw,"END") == 0)
{
mark--;
if(mark == 0)
break;
for(i = top-1;i >= 0; --i)
{
if(st[i].ty <= 1)
break;
}
for(j = i+1;j < top; ++j)
{
st[j].ind += st[i].ind;
st[j].coe *= st[i].coe;
}
if(i+1 != top)
st[i].ty = 100;
else st[i].ty = 2;
}
else if(strcmp(kw,"OP") == 0)
{
scanf("%d",&w);
st[top].ty = 2;
st[top].coe = w;
st[top].ind = 0;
top++;
}
}
for(i = 0;i < top; ++i)
{
if(st[i].coe == 0)
st[i].ind = 0;
}
sort(st,st+top,cmp);
for(i = 1;i < top && st[i].ty != 100; ++i)
{
if(st[i].ind == st[i-1].ind)
{
st[i].coe += st[i-1].coe;
st[i-1].ty = 100;
}
}
sort(st,st+top,cmp);
printf("Program #%d\n",++icase);
printf("Runtime = ");
for(i = 0;i < top && st[i].ty != 100; ++i)
{
if(i != 0)
printf("+");
if(st[i].coe != 1 || st[i].ind == 0)
{
printf("%d",st[i].coe);
}
if(st[i].coe != 1 && st[i].ind != 0)
{
printf("*n");
}
if(st[i].coe == 1 && st[i].ind != 0)
{
printf("n");
}
if(st[i].ind > 1)
{
printf("^%d",st[i].ind);
}
}
printf("\n\n");
}
return 0;
}