UVA 586 Instant Complexity
给出一段程序,求运行时间。
现在只考虑一层LOOP,不妨用数组a[i]来表示n的i次方的系数。如果输入OP m,那么就在a[0]上加m,遇到END,就说明循环结束了,需要在系数上乘以循环次数。如果次数为数字,那么每个系数都乘以它;如果为n,那么全部右移一位(是指把n^2的系数给n^3),记得a[0] = 0。
当有多层LOOP时,递归调用即可。
输出的时候需要注意几个错误:如 1*n^3 (应该为n^3), 2*n^1 (应该为n^2), 注意n^0的系数,只要不是0,就要输出。
#include<algorithm> #include<iostream> #include<cstring> #include<cstdio> #include<vector> #include<string> #include<queue> #include<cmath> #include<set> #include<map> ///LOOP #define REP(i, n) for(int i = 0; i < n; i++) #define FF(i, a, b) for(int i = a; i < b; i++) #define FFF(i, a, b) for(int i = a; i <= b; i++) #define FD(i, a, b) for(int i = a - 1; i >= b; i--) #define FDD(i, a, b) for(int i = a; i >= b; i--) ///INPUT #define RI(n) scanf("%d", &n) #define RII(n, m) scanf("%d%d", &n, &m) #define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k) #define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p) #define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q) #define RFI(n) scanf("%lf", &n) #define RFII(n, m) scanf("%lf%lf", &n, &m) #define RFIII(n, m, k) scanf("%lf%lf%lf", &n, &m, &k) #define RFIV(n, m, k, p) scanf("%lf%lf%lf%lf", &n, &m, &k, &p) #define RS(s) scanf("%s", s) ///OUTPUT #define PN printf("\n") #define PI(n) printf("%d\n", n) #define PIS(n) printf("%d ", n) #define PS(s) printf("%s\n", s) #define PSS(s) printf("%s ", n) ///OTHER #define PB(x) push_back(x) #define CLR(a, b) memset(a, b, sizeof(a)) #define CPY(a, b) memcpy(a, b, sizeof(b)) #define display(A, n, m) {REP(i, n){REP(j, m)PIS(A[i][j]);PN;}} using namespace std; typedef long long LL; typedef pair<int, int> P; const int MOD = 100000000; const int INFI = 1e9 * 2; const LL LINFI = 1e17; const double eps = 1e-6; const double pi = acos(-1.0); const int N = 15; const int M = 1111111; const int move[8][2] = {0, 1, 0, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1}; char s1[N], s2[N]; int ans[N]; void solve(int *a, int p, int q) { int n; while(RS(s1), s1[0] != 'E') { if(s1[0] == 'O') { RI(n); a[0] += n; } else { RS(s2); if(s2[0] == 'n')n = -1; else sscanf(s2, "%d", &n); int b[N] = {0}; solve(b, p + 1, n); REP(i, N)a[i] += b[i]; } } if(q == -1) { FD(i, 12, 1)a[i] = a[i - 1]; a[0] = 0; } else FD(i, 12, 0)a[i] *= q; } void print() { int f = 0; FD(i, 12, 1)if(ans[i]) { if(!f)f = 1; else putchar('+'); if(ans[i] > 1)printf("%d*", ans[i]); if(i == 1)putchar('n'); else printf("n^%d", i); } if(ans[0]) { if(!f)f = 1; else putchar('+'); printf("%d", ans[0]); } if(!f)printf("0"); printf("\n\n"); } int main() { //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int t, cas = 1; RI(t); while(t--) { CLR(ans, 0); RS(s1); solve(ans, 0, 1); printf("Program #%d\nRuntime = ", cas++); print(); } return 0; }