C++分而治之算法题

C++ Divide and conquer algorithm problems

我刚刚学习了分而治之算法,对此我有点困惑。问题是我的作业,我尝试了很多方法来修复我的代码,但没有 运行。

#include <iostream>
using namespace std;

void inputArray(int* a, int& n)
{
    cout << "Input n:";
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cout << "input a[" << i << "]= ";
        cin >> a[i];
    }
}

int sumeven(int* a, int l, int r)
{
    if (l == r  && a[l] % 2 == 0)
    {
        return a[l];
    }

    int mid = (l + r) / 2;
    int s1 = sumeven(a, l, mid);
    int s2 = sumeven(a, mid + 1, r);
    return s1 + s2;

}

int main()
{
    int n;
    int a[20];
    inputArray(a, n);
    cout<<sumeven(a, 0,n-1);
    return 0;
}

先尝试在没有用户输入的情况下测试您的程序:

#include <iostream>
using namespace std;
int sumeven(int* a, int l, int r)
{
    if (r >= 6) return 0;
    if (l > r ) return 0;
    if (l >= r)
    {
        if (a[l] % 2 == 0)
        {
            return a[l];
        }
        else
        {
            return 0;
        }
    }

    int mid = (l + r) / 2;
    int s1 = sumeven(a, l, mid);
    int s2 = sumeven(a, mid + 1, r);
    return s1 + s2;

}
int main()
{
    int n=6;
    int a[6]={1,2,3,48,5,6};
    cout<<sumeven(a,0,n-1);
    return 0;
}