}
return0;
}
时间复杂度分析:
第二个for的嵌套循环是寻找鞍点的主要程序,假设数组A[m][n],则第一、二个内嵌循环时间代价分别为t1(n)=O(f(n))和t2(m)=O(g(m)),外循环的时间复杂度为t(m)=O(F(m))则整个程序段的时间复杂度为T=t(m)×(t1(n)+t2(m))
因为for语句里if后面语句被执行的平均次数为(n-1)+(n-2)…+1+0=n/2;
所以f(n)=n/2*2+n*3+2=n*4+2;
则t1(n)=O(f(n))=O(n),
同理得t2(m)=O(g(m))=O(m),
而最后的if后面语句被执行的平均次数为(m+1)/2
则T=O((2+2+t1+2+t2+1)×m+2+(m+1)/2)=O(max{m×n,m×m})
4.13所谓回文,是指从前向后顺读和从后向前读都一样的不含空白字符的串。
例如did,madamimadam,pop即是回文。
试编写一个算法,以判断一个串是否是回文。
//stdafx.h
#include
#include
#include
usingnamespacestd;
//结点类
#ifndefstdafx_h
#definestdafx_h
template
structLinkNode
{
Tdata;
LinkNode*link;
LinkNode(constT&item,LinkNode*ptr=NULL)
{data=item;link=ptr;}
LinkNode(LinkNode*ptr=NULL){link=ptr;}
};
#endif
//stack.h
#pragmaonce
template
classCCStack
{
public:
CCStack(void);
~CCStack(void);
protected:
LinkNode*top;
public:
voidPush(constT&x);
boolPop();
boolIsEmpty(void){return(top==NULL)?
true:
false;};
TgetTop();
};
//stack.cpp
#include"StdAfx.h"
#include".\cstack.h"
#using
template
CCStack:
:
CCStack(void)
:
top(NULL)
{
}
template
CCStack:
:
~CCStack(void)
{
}
template
voidCCStack:
:
Push(constT&x)
{
top=newLinkNode(x,top);
}
template
boolCCStack:
:
Pop()
{
if(IsEmpty()==true)returnfalse;
LinkNode*p=top;
top=top->link;
deletep;
returntrue;
}
template
TCCStack:
:
getTop()
{
Tx;
if(IsEmpty()==true)returnNULL;
x=top->data;
returnx;
}
//main.cpp
#include"stdafx.h"
#include".\cstack.cpp"
#using
usingnamespaceSystem;
int_tmain()
{
stringa;
booltemp=true;
inti=0;
CCStackst;
cin>>a;
while(a[i]!
='\0')
{
st.Push(a[i]);
i++;
}
i=0;
while(a[i]!
='\0')
{
if(a[i]==st.getTop())
{
st.Pop();
i++;
}
else
{
temp=false;
break;
}
}
if(temp)
cout<<"此字符是回文"<else
cout<<"此字符不是回文"<return0;
}
4.15编写一个算法frequency,统计在一个输入字符串中各个不同字符出现的频度。
用适当的测试数据来验证这个算法。
//stdafx.h
#include
#include
#include
usingnamespacestd;
//main.cpp
#include"stdafx.h"
#using
usingnamespaceSystem;
int_tmain()
{
stringa;
intk,*num;
char*A;
cin>>a;
k=a.length();
A=newchar[k];
num=newint[k];
frequency(a,A,num,k=0);
for(inti=0;i{
cout<"<}
delete[]A;
delete[]num;
return0;
}
voidfrequency(strings,charA[],intC[],int&k)
{
inti,j,len=s.length();
A[0]=s[0];C[0]=1;
//种类数
k=1;
for(i=1;iC[i]=0;
for(i=1;i