无法通过测试(Kadane算法)

时间:2020-03-11 13:40:10

标签: c++ algorithm

我必须在整数(| a | <= 4000)的一维数组(1 <= N <= 500000)中找到最大和。

如果有多个子数组具有相同的最大和,我必须打印最短的一个。如果有多个最短的子数组,我必须打印最左边的一个。

该代码通过了大多数测试,除了一个,而且我不知道我做错了什么。 enter image description here

代码:

#include <bits/stdc++.h>

using namespace std;

vector<int> adj;
int kStart = 0, kEnd = 0;

void getOutput()
{
    ofstream output("max.out");
    output << kStart + 1 << " " << kEnd + 1;
    output.close();
}

void kadane()
{
    int max_global = INT_MIN, max_current = 0, kS = 0;

    for(int i = 0; i < adj.size(); i++)
    {
        max_current += adj[i];

        if(max_current > max_global || (max_current == max_global && i - kS < kEnd - kStart))
        {
            max_global = max_current;
            kStart = kS;
            kEnd = i;
        }

        if(max_current < 0)
        {
            max_current = 0;
            kS = i + 1;
        }
    }
}

void getData()
{
    ifstream input("max.in");

    int n; input >> n;

    for(int i = 0; i < n; i++)
    {
        int num; input >> num;
        adj.push_back(num);
    }

    input.close();
}

int main()
{
    getData();
    kadane();
    getOutput();

    system("pause");
}

0 个答案:

没有答案