当前位置: 代码迷 >> 综合 >> d1t2 时间复杂度
  详细解决方案

d1t2 时间复杂度

热度:24   发布时间:2024-01-28 08:24:08.0

洛谷
想法参考大佬:
大佬

#include <iostream>
#include <algorithm>
#include <sstream>using namespace std;typedef pair<char, int> PCI;const int N = 110;int tt;
PCI stk[N];int get_number(string number)
{int res = 0;for (int i = 0; i < number.size(); i ++ ) res = res * 10 + number[i] - '0';return res;
}int get_time(string str)
{if (str == "O(1)") return 0;int t = str.find('^');string number = str.substr(t + 1);number.pop_back();return get_number(number);
}bool have(char c)
{for (int i = 1; i <= tt; i ++ )if (stk[i].first == c)return true;return false;
}int get_for_time(string x, string y)
{if (x == "n"){if (y == "n") return 0;return -1;}if (y == "n") return 1;int a = get_number(x), b = get_number(y);if (a > b) return -1;return 0;
}int main()
{int T;cin >> T;while (T -- ){int n;string str;cin >> n >> str;int O = get_time(str);getline(cin, str);tt = 0;int max_time = 0;bool error = false;while (n -- ){getline(cin, str);if (error) continue;//有语法错误,直接不执行下面的了if (str == "E"){//栈内是否有循环语句,如果有的话,就弹出 .没有就是语法错if (tt) tt -- ;else error = true;}else{stringstream sin(str);string F, i, x, y;sin >> F >> i >> x >> y;//如果局部变量重复,语法错误if (have(i[0])) error = true;else{// 如果语法正确// 找到当前的循环语句的 O的次方数int tm = get_for_time(x, y);// 上语句如果合法,就入栈,并且累积之前的次方数if (tm >= 0 && stk[tt].second >= 0) tm += stk[tt].second; // 如果逻辑不合法,令为-1,让max_time保持不变else tm = -1;stk[ ++ tt] = make_pair(i[0], tm);max_time = max(max_time, tm); // 统计最大的次方数}}}if (tt) error = true;//栈未出完if (error) puts("ERR");// 如果和之前小明给出的一致,那么就输出yeselse if (max_time == O) puts("Yes");else puts("No");}return 0;
}