标签:
Description
< Program > ::= "BEGIN" < Statementlist > "END" < Statementlist > ::= < Statement > | < Statement > < Statementlist > < Statement > ::= < LOOP-Statement > | < OP-Statement > < LOOP-Statement > ::= < LOOP-Header > < Statementlist > "END" < LOOP-Header > ::= "LOOP" < number > | "LOOP n" < OP-Statement > ::= "OP" < number >
Input
Output
Sample Input
2 BEGIN LOOP n OP 4 LOOP 3 LOOP n OP 1 END OP 2 END OP 1 END OP 17 END BEGIN OP 1997 LOOP n LOOP n OP 1 END END END
Sample Output
Program #1 Runtime = 3*n^2+11*n+17 Program #2 Runtime = n^2+1997
计算时间复杂度,只有执行语句和循环,执行语句OP后为一个非负整数,循环LOOP后为一个非负整数或n,计算整个程序的复杂度。
做一个栈,记录下当前的复杂度,没遇到OP就计算出当前的复杂度,累加起来。控制输出、
#include <cstdio> #include <cstring> #include <algorithm> #include <stack> using namespace std ; stack <int> sta ; int c[15] , a , b ;// char str[10] ; int main() { int t , tt , temp , k , i , j , l ; scanf("%d", &t) ; for( tt = 1 ; tt <= t ; tt++ ) { while( !sta.empty() ) sta.pop() ; memset(c,0,sizeof(c)) ; a = 1 ; b = 0 ; temp = 0 ; scanf("%s", str) ; while( temp >= 0 ) { scanf("%s", str) ; if( strcmp(str,"LOOP") == 0 ) { temp++ ; scanf("%s", str) ; if( str[0] == 'n' ) { b++ ; sta.push(-1) ; } else { k = 0 ; l = strlen(str) ; for(i = 0 ; i < l ; i++) { k = k*10 + str[i] - '0' ; } if( k == 0 ) sta.push(a) ; a *= k ; sta.push(k) ; } } else if( strcmp(str,"OP") == 0 ) { scanf("%s", str) ; k = 0 ; l = strlen(str) ; for(i = 0 ; i < l ; i++) k = k*10 + str[i] - '0' ; c[b] += k*a ; } else { temp-- ; if( temp == -1 ) continue ; if( sta.top() == 0 ) { sta.pop() ; a = sta.top() ; sta.pop() ; } else if( sta.top() == -1 ) { sta.pop() ; b-- ; } else { a /= sta.top() ; sta.pop() ; } } } printf("Program #%d\n", tt) ; printf("Runtime = ") ; int flag = 0 ; for(i = 14 ; i >= 0 ; i--) { if( c[i] == 0 ) continue ; if( flag ) printf("+") ; if( i == 0 ) { printf("%d", c[i]); } else { if( c[i] > 1 ) printf("%d", c[i]) ; if( i != 0 ) { if( c[i] > 1 ) printf("*"); printf("n") ; if( i > 1 ) printf("^%d", i) ; } } flag = 1 ; } if( flag == 0 ) printf("0") ; printf("\n") ; if( tt < t ) printf("\n") ; } return 0; }
poj1472--Instant Complexity(模拟)
标签:
原文地址:http://blog.csdn.net/winddreams/article/details/43338615