Prog/Algo_practice_190401

17 篇文章 0 订阅
16 篇文章 0 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值