计算程序时间复杂度的
有可能出现 loop 0的情况
所以给每一个块带一个coe系数,块中如果内嵌块,则把外面的块的coe系数传递过去.
#include <iostream>
#include <cstdio>
#include <memory.h>
#include <vector>
#include <string>
using namespace std;
#define pb push_back
const int maxn=11;
bool poly[maxn];
int coe[maxn];
string buf;
struct BLOCK{
string bName;
int nTimes,cons,coef;
BLOCK(const string &bbName="",int nnTimes=0,int ccons=0){
bName=bbName,nTimes=nnTimes,cons=ccons;
coef=1;
}
};
vector<BLOCK> stak;
int main(){
int t,cas=1;
scanf("%d",&t);
while (t--){
int f=0;
memset(coe,0,sizeof(coe));
memset(poly,0,sizeof(poly));
while (1){
cin>>buf;
if(buf=="BEGIN"){
BLOCK b(buf);
stak.push_back(b);
}else if(buf=="LOOP"){
char ch;
cin>>ch;
BLOCK b(buf);
if(ch=='n'){
b.nTimes=stak.back().nTimes+1;
b.coef=stak.back().coef;
}else{
cin.putback(ch);
int tm;
cin>>tm;
b.nTimes=stak.back().nTimes;
b.coef=stak.back().coef*tm;
}
stak.push_back(b);
}else if(buf=="OP"){
int tm;
cin>>tm;
stak.back().cons+=tm;
}else if(buf=="END"){
BLOCK t=stak.back();
stak.pop_back();
poly[t.nTimes]=1;
coe[t.nTimes]+=t.coef*t.cons;
if(t.bName=="BEGIN")break;
}
}
printf("Program #%d\nRuntime = ",cas++);
int cnt=0;
for (int i=maxn-1;i>=0;--i){
if(coe[i]&&poly[i]){
if(cnt>0)printf("+");
if(i==0&&coe[i]&&poly[i]){
printf("%d",coe[i]);
}else if(i==1&&coe[i]&&poly[i]){
if(coe[i]>1)
printf("%d*n",coe[i]);
else
printf("n");
}else if(coe[i]&&poly[i]){
if(coe[i]>1)
printf("%d*n^%d",coe[i],i);
else
printf("n^%d",i);
}
cnt++;
f=1;
}
}
if(f==0){
printf("0\n");
}else{
printf("\n");
}
printf("\n");
}
return 0;
}