本章由两个问题引开,并证明了一些算法基础的数学公式。
1. 两个问题
a. 求N个数中的前K个最大值问题。从全部排序法,到维持一个K个元素的数组方法,再到2叉堆法,一步一步说明算法重要性。
b. 字谜问题。
2. 数学公式
指数问题,对数问题,级数和问题。
3. 一些数学证明方法
a.数学归纳法。 两要素:基准情形成立,当n=N成立时,n=N+1也成立,得证。
b.递归方法。两要素:停止条件,不断推进
4. 大O表示法
单循环为O(N),嵌套两层为O(N2),分治2分为logN. 斐波拉契为(5/3)N次方
例子:最大子序列最大和问题的求解。
穷举法,穷举所有数列,2分法还有一个用技巧的O(N)算法。代码如下:
#include
int maxSubSeqence(const int A[],unsigned int n)
{
int i,j,k=0;
int sum,maxsum=0;
for(i=0;imaxsum)
maxsum = sum ;
}
return maxsum;
}
int maxSubSeqence2(const int A[],unsigned int n)
{
int i,j,k=0;
int sum,maxsum=0;
for(i=0;imaxsum)
maxsum = sum ;
}
}
return maxsum;
}
int maxSubSeqence3(const int A[],int begin, int end)
{
if (begin==end)
{
if (A[begin]>0)
return A[begin];
else
return 0;
}
int middle =(begin+end)/2;
int leftsum,rightsum;
leftsum = maxSubSeqence3(A,begin,middle);
rightsum = maxSubSeqence3(A,middle+1,end);
int maxleftbordersum=0,maxrightbordersum=0, bordersum=0;
int i;
for(i = middle+1;i<=end; i++)
{
bordersum = bordersum+ A[i];
if (bordersum>maxrightbordersum)
maxrightbordersum = bordersum;
}
bordersum =0;
for(i = middle;i>=begin; i--)
{
bordersum = bordersum+ A[i];
if (bordersum>maxleftbordersum)
maxleftbordersum = bordersum;
}
int max = leftsum;
if (maxmax)
max= sum;
if(sum<0)
sum =0;
}
return max;
}
int main()
{
int A[] = {1,-3, 9,2,1, -10,6,-7,8} ;
int maxsum = maxSubSeqence(A,sizeof(A)/sizeof(int));
printf("maxsum=%d\n",maxsum);
int maxsum2 = maxSubSeqence2(A,sizeof(A)/sizeof(int));
printf("maxsum2=%d\n",maxsum2);
int maxsum3 = maxSubSeqence3(A,0,sizeof(A)/sizeof(int)-1);
printf("maxsum3=%d\n",maxsum3);
int maxsum4 = maxSubSeqence4(A,sizeof(A)/sizeof(int));
printf("maxsum4=%d\n",maxsum4);
return 0;
}
#include
int gcd(int m, int n)
{
while(n>0)
{
int rem = m%n;
m = n;
n = rem;
}
return m;
}
int main()
{
int m = 1345, n = 9745;
printf("gcd = %d\n", gcd(m,n));
}
~
#include
int power(int x,int n)
{
if (n==0)
return 1;
if (n==1)
return x;
if (n%2==0)
return power(x*x,n/2);
else
return power(x*x,(n-1)/2)* x;
}
int main()
{
int m = power(2,10);
printf("power 2,10=%d\n", m);
}