Cod sursa(job #1000640)

Utilizator alexx.cosmaCosma Cristian Alexandru alexx.cosma Data 23 septembrie 2013 15:12:27
Problema Subsecventa de suma maxima Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <iostream>
#include <fstream>

using namespace std;

const int maxLength = 6000010;

int a[maxLength];
int best[maxLength];
int main()
{
    ifstream fin("ssm.in");
    ofstream fout("ssm.out");

    if (!fin)
    {
        cout << "There was a problem opening file";
        return 0;
    }
    int arrLength=0;
    int counter=0;

    fin >> arrLength;

    for(int i=0; i < arrLength; i++)
    {
        fin>>a[counter] ;
        counter++;
    }

    int bestSum = a[0];
    int bestEndIndex=0;
    int bestStartIndex=0;
    for (int i = 0; i < arrLength; ++ i)
    {
        best[i] = a[i];
        if (best[i] < best[i-1] + a[i])
            best[i] = best[i-1] + a[i];

        if (bestSum < best[i])
        {
            bestSum = best[i];
            bestEndIndex = i;
        }
    }
    bestStartIndex = bestEndIndex;



    int i=bestEndIndex;
    int tempSum = bestSum;

    while(i >= 0)
    {
        tempSum -= a[i];
        if(tempSum==0)
        {
            if(i<bestStartIndex)
            {
                bestStartIndex=i;
            }
        }
        i--;
    }

    fout << bestSum << " " << bestStartIndex+1 << " " << bestEndIndex+1 << "\n";

    return 0;
}