时间复杂度 给出若干个循环语句嵌套关系及其时间复杂度,判断是否具有语法错误,若无,给出的时间复杂度是否正确。
模拟。 纯粹模拟,思路简单,就不说明了。读入整行和边读边处理各有千秋。
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <stack>
#define Max(u, v) ((v) < (u)? u: v)
const int MAXL = 101;
int t; bool vis[26]; char nil[MAXL];
struct Bnd { int f, s; char t; inline int ly() { return f? f + s - 1: 0; }
Bnd(int f = 0, int s = 0, char t = '\0'): f(f), s(s), t(t) {}};
std::stack<Bnd> zhan;
struct Read {
Read& operator >>(char& ip) {
do ip = getchar(); while(!isalpha(ip)); return *this; }
Read& operator >>(int& re) {
char ip; re = 0; do ip = getchar(); while(!isgraph(ip));
if(!isdigit(ip)) { re = -1; return *this; }
else do re = (re << 3) + (re << 1) - '0' + ip;
while(isdigit(ip = getchar())); return *this; }} myin;
int main() {
scanf("%d", &t); while(t--) {
int l, an; bool flg = true; char ans[MAXL], ta[MAXL];
scanf("%d%s", &l, ans); memset(vis, 0, sizeof vis);
while(!zhan.empty()) zhan.pop(); zhan.push(Bnd(1));
for(int i = 0; i < l; i++) {
char ip; int x, y; myin >> ip;
if(ip == 'F') { myin >> ip; if(vis[ip - 'a']) flg = false;
vis[ip - 'a'] = true; myin >> x >> y;
zhan.push(Bnd(x != y? (~y && x > y) || !~x? 0: !~y? 2: 1: 1, 0, ip)); }
else { Bnd top; if(zhan.size() < 2) { flg = false; continue; }
top = zhan.top(); vis[top.t - 'a'] = false;
zhan.pop(); zhan.top().s = std::max(zhan.top().s, top.ly()); }}
if(zhan.size() != 1) flg = false;
else an = zhan.top().ly(), sprintf(ta, "O(n^%d)", an);
puts(flg? !an? strcmp(ans, "O(1)")? "No": "Yes":
strcmp(ans, ta)? "No": "Yes": "ERR"); }
return 0; }