Instant Complexity--POJ 1472

1、题目类型:模拟、栈。

2、解题思路:题意,给你一个源程序,要你计算出程序运行的时间复杂度;(1)定义结构体Node,并根据需要重载其运算符"+"和"*";(2)模拟程序的执行顺序,"LOOP"和"OP"便进栈,"END"则弹出栈;(3)出栈过程中,对"OP"进行"+",对"LOOP"进"*"操作并记录在 ans 中;(4)ans 结构体,表示一个长度为11数组,第 i 位表示为 n 的 i 次方为多少;(5)Print()输出多项式形式,注意多项式系数为 0 的情况,和 n 的 1 次方 和 0 次方两种特殊情况输出的表现形式。

3、注意事项:注意为出栈进行操作时,对Node结构体中运算符的重载。

4、实现方法:

#include<iostream>
#include
<stack>
#include
<string>
using namespace std;

struct Node{
int num[11];
bool flag;
struct Node operator+(Node p)
{
Node t;
for(int i=0;i<11;i++)
t.num[i]
=p.num[i]+num[i];
return t;
}
struct Node operator*(Node p)
{
Node t;
memset(t.num,
0,sizeof(t.num));
for(int i=0;i<11;i++)
for(int j=0;j<11;j++)
{
if(i+j>10) continue;
t.num[i
+j]+=num[i]*p.num[j];
}
return t;
}
};

Node ans;
stack
<Node>sta;

void Solve()
{
while(!sta.empty())
sta.pop();
char str[10],t[10];
scanf(
"%s",str);
Node tmp,t1;
memset(tmp.num,
0,sizeof(tmp.num));
tmp.num[
0]=1;
tmp.flag
=1;
sta.push(tmp);
while(!sta.empty())
{
scanf(
"%s",str);
memset(tmp.num,
0,sizeof(tmp.num));
if(strcmp(str,"LOOP")==0)
{
scanf(
"%s",t);
if(strcmp(t,"n")==0)
{
tmp.num[
1]=1;
tmp.flag
=1;
}
else
{
int a;
sscanf(t,
"%d",&a);
tmp.num[
0]=a;
tmp.flag
=1;
}
sta.push(tmp);
continue;
}

if(strcmp(str,"OP")==0)
{
scanf(
"%s",t);
if(strcmp(t,"n")==0)
{
tmp.num[
1]=1;
tmp.flag
=0;
}
else
{
int a;
sscanf(t,
"%d",&a);
tmp.num[
0]=a;
tmp.flag
=0;
}
sta.push(tmp);
continue;
}

if(strcmp(str,"END")==0)
{
t1
=sta.top();
sta.pop();
while(t1.flag!=1)
{
tmp
=tmp+t1;
t1
=sta.top();
sta.pop();
}
tmp
=tmp*t1;
tmp.flag
=0;
if(sta.empty())
{
ans
=tmp;
return;
}
sta.push(tmp);
continue;
}
}
}

void Print()
{
int i;
bool judge=1;
for(i=10;i>=0;i--)
{
if(ans.num[i] && judge)
{
judge
=0;
if(i==1)
{
if(ans.num[i]!=1)
printf(
"%d*n",ans.num[i]);
else
printf(
"n");
}
else
if(i)
{
if(ans.num[i]!=1)
printf(
"%d*n^%d",ans.num[i],i);
else
printf(
"n^%d",i);
}
else printf("%d",ans.num[0]);
}
else
{
if(ans.num[i] && !judge)
{
if(i==1)
{
if(ans.num[i]!=1)
printf(
"+%d*n",ans.num[i]);
else
printf(
"+n");
}
else
if(i)
{
if(ans.num[i]!=1)
printf(
"+%d*n^%d",ans.num[i],i);
else
printf(
"+n^%d",i);
}
else
printf(
"+%d",ans.num[0]);
}
}
}
if(judge)
printf(
"0");
cout
<<endl<<endl;
}

int main()
{
int c,i;
cin
>>c;
for(i=1;i<=c;i++)
{
Solve();
printf(
"Program #%d\n",i);
printf(
"Runtime = ");
Print();
}
return 0;
}

 

posted @ 2010-10-06 15:19  勇泽  阅读(994)  评论(0编辑  收藏  举报