Program/Algorithm_practice 1
利用 二分法/dynamic array 实现子列最大和问题
#include <stdio.h>
#include <time.h>
#include<math.h>
#include<stdlib.h>
#include<malloc.h>
//FUNC1
//output is only three states : left(A);mid(B);right(C)
int max3(int A, int B, int C){
return A>B?A>C?A:C:B>C?B:C;
}//find the max value in three numbers
//FUNC2
//divide from the middle by recursive
int divideandconquer(int list[],int left,int right){
//分治法求List[left]到List[right]的最大子列和
int maxlsum,maxrsum;
//save the result of list left and right
int maxlbordersum,maxrbordersum;
//save the result cross the left and right border
int lbors,rbors;
int center,i;
//the end of recursive is the list only have one member
if(right==left){
if(list[left]>0) return list[left];
else return 0;
}
center=(left+right)/2;//find the mid location
//begin the recursive
maxlsum=divideandconquer(list,left,center);
maxrsum=divideandconquer(list,center+1,right);
//scan to calculate the result when cross the border
maxlbordersum=lbors=0;
for(i=center;i>=left;i--){
lbors+=list[i];
if(maxlbordersum<lbors)
maxlbordersum=lbors;
}//left scan ending
maxrbordersum=rbors=0;
for(i=center+1;i<=right;i++){
rbors+=list[i];
if(maxrbordersum<rbors)
maxrbordersum=rbors;
}//right scan ending
//feedback the result of the recursive
printf("maxrbordersum=%d maxlbordersum=%d maxrbordersum:%d=%d + %d\n",maxlsum,maxrsum,maxrbordersum+maxlbordersum,maxlbordersum,maxrbordersum);//
return max3(maxlsum,maxrsum,maxrbordersum+maxlbordersum);
}//divideandconquer function ending
//FUNC3
int maxsubsequsum(int list[],int N){
//printf("%d\n",divideandconquer(list,0,N-1));
return (divideandconquer(list,0,N-1));
}
int main(){
int N,i,result ;
printf("please input your N:\n");//
scanf("%d",&N);
int *p;
p=(int*)malloc(sizeof(int)*N);
if(p!=NULL)
{
printf("input numbers divided by space:\n");//
for(int i=0;i<=(N-1);i++) scanf("%d",p+i);
//this for getting input
printf("\n");
printf("your list is :\n");
for(i=0;i<=(N-1);i++) printf("%d\t",p[i]);
//this for print this dynamic array,divided by tab(\t)
printf("\n\n");
}
else printf("error!\n");
result =maxsubsequsum(p, N);
printf ("\nthe result is %d",result);
free(p);
p=NULL;
}
help_text here