程序时间复杂度的计算,一眼看过去就是要用栈来搞,不过思路要正确,逻辑要清晰再动手写,事半功倍,最后的格式化输出又恶心了我下,搞这么复杂为毛
#include<iostream>
#include<vector>
#include<cstdlib>
#include<cstdio>
using namespace std;
namespace
{
int *array()
{
int *p = new int[11];
for (int i = 0; i < 11; i++)
p[i] = 0;
return p;
}
void print(int *a)
{
printf("Runtime = ");
bool zero = true;
for (int i = 10; i >= 0; i--)
if (a[i])
{
if (!zero)
putchar('+');
zero = false;
if (i)
{
if (a[i] != 1)
printf("%d*", a[i]);
putchar('n');
if (i != 1)
printf("%c%d", '^', i);
}
else
printf("%d", a[i]);
}
if (zero)
putchar('0');
puts("\n");
}
}
int main()
{
int n;
cin >> n >> ws;
string s;
vector<pair<int, int*> > V;
for (int k = 0; k < n; k++)
{
printf("Program #%d\n", k + 1);
while (cin >> s)
{
if (s == "BEGIN")
V.push_back(make_pair(1, array()));
else if (s == "LOOP")
{
cin >> s;
int num = s[0] == 'n' ? -1 : atoi(s.c_str());
V.push_back(make_pair(num, array()));
}
else if (s == "OP")
{
cin >> s;
V.back().second[0] += atoi(s.c_str());
}
else if (s == "END")
{
pair<int, int*> p = V.back();
V.pop_back();
if (p.first == -1)
{
for (int i = 10; i > 0; i--)
p.second[i] = p.second[i - 1];
p.second[0] = 0;
}
else
for (int i = 0; i < 11; i++)
p.second[i] *= p.first;
if (!V.empty())
{
for (int i = 0; i < 11; i++)
V.back().second[i] += p.second[i];
delete p.second;
}
else
{
print(p.second);
delete p.second;
break;
}
}
}
}
return 0;
}