ZOJ 1246 Instant Complexity(栈应用)

2 篇文章 0 订阅

计算程序时间复杂度的

有可能出现 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值