Cod sursa(job #2446648)

Utilizator samuelnituNitu Daniel-Samuel samuelnitu Data 10 august 2019 11:28:22
Problema Subsecventa de suma maxima Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main(){
	ifstream f;
	f.open("ssm.in");
	vector<int> a;
	int x, i, l;
	f >> l;
	for(i = 0; i < l; i++){
		f >> x;
		a.push_back(x);
	}
	f.close();
	ofstream g;
	g.open("ssm.out");
	int ok1 = 0, ok2 = 0, ok3 = 0, maxSum = -1000, max = 0, sumOfPos = 0, sumOfNeg = 0;
	int start = 0;
	int end = 0, m = 0, p = 0;
	for(i = 0; i < l; i++){
		if(ok1 == 1 && a[i] >= 0){
			if(ok2 == 0){
				m = i;
			}
			ok2 = 1;
			// m = i;
		}
		if (a[i] < 0 && ok1 == 0){
			if(max > maxSum){
				maxSum = max;
				end = i - 1;
			}
			ok1 = 1;
			//p = i;
		}
		if(ok1 == 0 && ok2 == 0){
			max += a[i];
		}
		if(ok1 == 1 && ok2 == 0){
			sumOfNeg -= a[i];
		}
		if(ok1 == 1 && ok2 == 1 && a[i] >= 0){
			sumOfPos += a[i];
			ok3 = 1;
		}
		if(a[i] < 0 && a[i + 1] >= 0){
			p = i + 1;
		}
		if(ok1 == 1 && ok2 == 1 && (a[i + 1] < 0 || i + 1 == l)){
			ok1 = 0;
			ok2 = 0;
			if(sumOfNeg >= sumOfPos){
				if(sumOfPos > maxSum){
					max = sumOfPos;
					start = m;
					end = i;
				}
				max = sumOfPos;
			} else {
				if(max - sumOfNeg <= 0){
					if(sumOfPos > maxSum){
						start = m;
						end = i;
						maxSum = sumOfPos;
						max = maxSum;
					} else {
						max = sumOfPos;
					}
				} else {
					if(maxSum < max + (sumOfPos -sumOfNeg)){
						maxSum = max + (sumOfPos - sumOfNeg);
						max = maxSum;
						//start = p;
						end = i;
					} else {
						max = sumOfPos;
					}
					
				}
			}
			sumOfPos = 0;
			sumOfNeg = 0;
		}
	}
	g << maxSum << " " << start + 1 << " " << end + 1 << " ";
	g.close();
}