时间:2021-05-20
本文实例分析了C语言连续子向量的最大和及时间度量,分享给大家供大家参考之用。具体方法如下:
#include <stdio.h>#include <time.h>#include <stdlib.h>#define SCALE 3000int 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程序设计的学习有所帮助。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
求一个向量的任何连续子向量的最大和比如向量(31,-41,59,26,-53,58,97,-93,-23,84);最大和是从59到97即为187?1234567
题目描述HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正
本文实例讲述了PHP实现求连续子数组最大和问题2种解决方法。分享给大家供大家参考,具体如下:问题描述求子数组的最大和题目描述:输入一个整形数组,数组里有正数也有
给定一个整数数组nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。示例:输入:[-2,1,-3,4,-1,2,1,-5,4],输
本文实例讲述了C语言求连续最大子数组和的方法,是非常实用的技巧。分享给大家供大家参考。具体实现方法如下:#includeusingnamespacestd;in