C語言連續(xù)子向量的最大和及時(shí)間度量實(shí)例
更新時(shí)間:2014年09月16日 11:10:50 投稿:shichen2014
這篇文章主要介紹了C語言連續(xù)子向量的最大和及時(shí)間度量,需要的朋友可以參考下
本文實(shí)例分析了C語言連續(xù)子向量的最大和及時(shí)間度量,分享給大家供大家參考之用。具體方法如下:
#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; }
感興趣的朋友可以測試運(yùn)行一下本文實(shí)例以加深理解。希望本文所述對大家C程序設(shè)計(jì)的學(xué)習(xí)有所幫助。
您可能感興趣的文章:
相關(guān)文章
Qt6.3 + Clion +MSVC2019環(huán)境配置詳解
本文主要介紹了Qt6.3 + Clion +MSVC2019環(huán)境配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01C語言中關(guān)于庫函數(shù) qsort 快排的用法
快速排序Qsort是所有學(xué)習(xí)算法和數(shù)據(jù)結(jié)構(gòu)最基礎(chǔ)的一個(gè)部分,也是考試題和面試的一個(gè)小重點(diǎn)。本片文章帶你了解Qsort的詳細(xì)用法規(guī)則2021-09-09VC運(yùn)用OPENGL加載BMP紋理圖的實(shí)現(xiàn)方法匯總
這篇文章主要介紹了VC運(yùn)用OPENGL加載BMP紋理圖的實(shí)現(xiàn)方法,對于更好的了解OpenGL很有幫助,需要的朋友可以參考下2014-07-07C/C++實(shí)現(xiàn)快速排序(兩種方式)圖文詳解
這篇文章主要介紹了C/C++實(shí)現(xiàn)快速排序的方法,這幾天在找工作,被問到快速排序,結(jié)果想不出來快速排序怎么弄的;回來搜索了一下,現(xiàn)在記錄下來,方便以后查看2021-08-08