欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C语言连续子向量的最大和及时间度量实例

时间:2021-06-09 08:09:02|栏目:C代码|点击:

本文实例分析了C语言连续子向量的最大和及时间度量,分享给大家供大家参考之用。具体方法如下:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define SCALE 3000
int maxnum(int a, int b);
int main(int argc, char const *argv[])
{
 FILE *fp;
 fp = fopen("maximum.in", "r");
 // int x[] = {1,12,-11,10,-65,54,22,-9,21,5,48,5,-8,-2,56,54,-88,-5,2,-8,554,-56,35,-55,555,-65,-545,-23,48,-5,88,-56,16,-8};
 int *x = (int *)malloc(sizeof(int)*(SCALE+1));
 int xi = SCALE,a = 0,num_in = 0;
 while(xi--){
  fscanf(fp, "%d", &x[a++]);
 }
 clock_t start, end;

 // ***Algorithm-1 cube***
 start = clock();

 int max = 0;
 int length = SCALE;
 int i,j,k;
 for (i = 0; i < length; ++i)
 {
  for (j = i; j < length; ++j)
  {
   int sum = 0;
   for (k = i; k <= j; ++k)
   {
    sum += x[k];
   }
   max = maxnum(max, sum);
  }
 }
 
 // long num = 10000000L;
 // while(num--);

 end = clock();
 double times = (double)(end - start)/CLOCKS_PER_SEC;
 double dend = (double)end;
 printf("\n***Algorithm-1 cube***\n");
 printf("end: %f\n", dend);
 printf("Time consuming: %f\n", times);
 printf("%d\n", max);
 // ***Algorithm-2 square***
 start = clock();
 max = 0;
 for (i = 0; i < length; ++i)
 {
  int sum = 0;
  for (j = i; j < length; ++j)
  {
   sum += x[j];
   max = maxnum(max, sum);
  }
 }
 end = clock();
 times = (double)(end - start)/CLOCKS_PER_SEC;
 dend = (double)end;
 printf("\n***Algorithm-2 square***\n");
 printf("end: %f\n", dend);
 printf("Time consuming: %f\n", times);
 printf("%d\n", max);
 // ***Algorithm-3 linear***
 start = clock();
 max = 0;
 int max_end_here = 0;

 for (i = 0; i < length; ++i)
 {
  max_end_here = maxnum(max_end_here + x[i], 0);
  max = maxnum(max, max_end_here);
 }
 end = clock();
 times = (double)(end - start)/CLOCKS_PER_SEC;
 dend = (double)end;
 printf("\n***Algorithm-3 linear***\n");
 printf("end: %f\n", dend);
 printf("Time consuming: %f\n", times);
 printf("%d\n", max);
 free(x);
 x = NULL;
 return 0;
}
int maxnum(int a, int b)
{
 return a > b ? a : b;
}

感兴趣的朋友可以测试运行一下本文实例以加深理解。希望本文所述对大家C程序设计的学习有所帮助。

上一篇:C语言中将日期和时间以字符串格式输出的方法

栏    目:C代码

下一篇:C语言实现单词小助手

本文标题:C语言连续子向量的最大和及时间度量实例

本文地址:http://www.codeinn.net/misctech/138730.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有