Created
April 1, 2013 07:32
-
-
Save leaveye/5283668 to your computer and use it in GitHub Desktop.
a max subsequence summary online judge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* \file sumsubseq.c | |
* \brief Maximum sub-sequence summary | |
* | |
* \version 0.1.0 | |
* \author Levi G | |
* \date 2013/04/01 | |
* | |
* \sa http://acm.hdu.edu.cn/showproblem.php?pid=1003 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
long max_subseqsum( long a[], size_t n, size_t *start, size_t *end ) { | |
int l, ml, mr, i; | |
long s = 0, m = LONG_MIN; | |
l = -1; | |
for ( i=0; i<n; i++ ) { | |
s += a[i]; | |
if ( s > m ) | |
ml = l, mr = i, m = s; | |
if ( s < 0 ) | |
s = 0, l = i; | |
} | |
if ( start ) | |
*start = ml + 1; | |
if ( end ) | |
*end = mr + 1; | |
return m; | |
} | |
int ezread_main( int argc, char **argv ) { | |
int ncase, n, c, i; | |
long m, *a = NULL; | |
size_t asize = 0, lbound, rbound; | |
const char *prefix; | |
scanf( "%d", &ncase ); | |
for ( c=1, prefix=""; c<=ncase; c++, prefix="\n" ) { | |
scanf( "%d", &n ); | |
if ( n > asize ) | |
a = realloc( a, ( asize = n ) * sizeof( long ) ); | |
for ( i=0; i<n; i++ ) | |
scanf( "%ld", &a[i] ); | |
m = max_subseqsum( a, n, &lbound, &rbound ); | |
printf( "%sCase %d:\n%ld %u %u\n", prefix, c, m, lbound + 1, rbound ); | |
} | |
free( a ); | |
return 0; | |
} | |
int geti( void ) { | |
int r = 0, c = getc( stdin ); | |
if ( c == '-' ) | |
for ( c = getc( stdin ); c >= '0' && c <= '9'; c = getc( stdin ) ) | |
r = r * 10 - ( c - '0' ); | |
for ( ; c >= '0' && c <= '9'; c = getc( stdin ) ) | |
r = r * 10 + ( c - '0' ); | |
return r; | |
} | |
int optimized_main( int argc, char **argv ) { | |
const char *p; | |
int nc = geti(), c; | |
for ( c=1, p=""; c<=nc; c++, p="\n" ) { | |
int i, l = -1, ml, mr, n = geti(); | |
long s = 0, m = LONG_MIN; | |
for ( i=0; i<n; i++ ) { | |
int a = geti(); | |
s += a; | |
if ( s > m ) | |
ml = l + 1, mr = i + 1, m = s; | |
if ( s < 0 ) | |
s = 0, l = i; | |
} | |
printf( "%sCase %d:\n%ld %u %u\n", p, c, m, ml + 1, mr ); | |
} | |
return 0; | |
} | |
int main( int argc, char **argv ) { | |
return optimized_main( argc, argv ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment