最开始自己写了一个栈,后来发现悲剧了。 并列的情况处理不当,改起来很麻烦,突然想起那天多校比较大小的那道模拟。 改成了递归,就过了。 #include<cstdio> #include<cstring> #include<stack> using namespace std; struct opera{ char op; int num; }; stack <opera> S; char op[10],num[10]; int ans[12]; void slove(int lev,int x) { int y,i,cnter,len; scanf("%s",op); while (strcmp(op,"END")!=0){ if (strcmp(op,"LOOP")==0){ scanf("%s",num); if (num[0]=='n') slove(lev+1,x); else { len=strlen(num); cnter=0; for (i=0;i<len;i++){ cnter*=10; cnter+=(num[i]-'0'); } slove(lev,x*cnter); } } else if (strcmp(op,"OP")==0){ scanf("%d",&y); ans[lev]+=x*y; } scanf("%s",op); } } void Print() { int i; bool f=false; for (i=10;i>1;i--) if (ans[i]!=0){ if (f) printf("+"); if (ans[i]!=1) printf("%d*",ans[i]); printf("n^%d",i); f=1; } if (ans[1]!=0){ if (f) printf("+"); if (ans[1]!=1) printf("%d*",ans[1]); printf("n"); f=1; } if (ans[0]!=0){ if (f) printf("+"); printf("%d",ans[0]); f=1; } if (!f) printf("0"); printf("/n/n"); } int main() { int t,ca=1,i; opera tmp; scanf("%d",&t); while (t--){ while (!S.empty()) S.pop(); memset(ans,0,sizeof(ans)); scanf("%s",op); if (strcmp(op,"BEGIN")==0) slove(0,1); printf("Program #%d/nRuntime = ",ca++); Print(); } return 0; } //loop number is no negative /* BEGIN LOOP 0 OP 3 END END BEGIN OP 1997 LOOP n LOOP n OP 0 END END END BEGIN LOOP n OP 1 END END BEGIN LOOP n END END BEGIN LOOP n OP 1 END LOOP n LOOP n OP 1 END END END BEGIN LOOP n OP 1 END OP 9 LOOP n OP 1 LOOP n OP 1 END OP 2 END END BEGIN LOOP n LOOP n OP 1 END LOOP n OP 1 END END END */