演算法學習筆記-暴力搜尋和分治法

badwell發表於2018-07-04

1.今天學習了一個簡單的求最大連續子陣列的問題,給定一個陣列A[0,…,n-1],求A的連續子數 組,使得該子陣列的和最大。例如:陣列: 1, -2, 3, 10, -4, 7, 2, -5

Python暴力求解法:

dest_arry = [1,-2,3,10,-4,7,-2,5,12]
max_val = dest_arry[0]
cuur_val = 0

start = 0
end = 0


print (len(dest_arry))

count = len(dest_arry)
#暴力法
for i in range(0, count):
    for j in range(i, count):
        cuur_val = 0
        for k in range(i, j+1):          #這個需要特別注意,在這裡這句話的意思相當於是for( k=i,k<(j+1),k++),在python中沒有'<='這個符號
            cuur_val = cuur_val + dest_arry[k]
            if(cuur_val > max_val):
                max_val = cuur_val
                start = i
                end = k

print (max_val, start,end)

Python分治法:

#分治法
dest_arry = [1,-2,3,10,-4,7,-2,5,12]

max_val = dest_arry[0]
cuur_val = 0

start = 0
end = 0


print (len(dest_arry))

count = len(dest_arry)

def max_sub_add(fr, to):
    global start
    global end

    if fr == to:
        return dest_arry[fr]
    mid = int((fr + to)/2)
    m1 = max_sub_add(fr, mid)
    m2 = max_sub_add(mid+1, to)


    left = dest_arry[mid]
    now = dest_arry[mid]

    i = mid - 1
    while(i>=fr):
        now = now + dest_arry[i]
        if(now > left):
            left = now
            start = i
        i = i - 1

    right = dest_arry[mid+1]
    now = dest_arry[mid+1]

    i = mid+2
    while(i <= to):
        now = now + dest_arry[i]
        if (now> right):
            right = now
            end = i
        i = i + 1
    # for i in range(mid+2, to+1):
    #     now = now + dest_arry[i]
    #     if (now> right):
    #         right = now
    #         end = i


    m3 = right + left
    return max(m1, m2, m3)

start = 0
end = 0

result = max_sub_add(0, (count)-1)
print(result, start, end)

C/C++暴力法:

#include "stdio.h"
#include "stdlib.h"

void baoli()
{
    int dest_arry[] = {1,-2,3,10,-4,7,-2,5,-12};

    int max_val = dest_arry[0] , cuur_val = 0, start_nbr = 0, end_nbr = 0;
    int count =  sizeof(dest_arry) / sizeof(int);

    int i = 0, j = 0, k = 0;

    printf("count: %d \n", count);

    for( i = 0; i < count; i++)
    {
        for (j=i;j<count; j++)
        {
            cuur_val = 0;
            for (k=i; k<=j; k++)
            {
                cuur_val = cuur_val + dest_arry[k];
                if(cuur_val > max_val)
                {
                    max_val = cuur_val;
                    start_nbr = i;
                    end_nbr = k;
                   
                }
            }
        }
    }
   

    printf("start: %d  end_nbr: %d  max_val: %d\n", start_nbr, end_nbr, max_val);
   
}
int main()
{ 

    baoli();
    
}

 

相關文章