/*
	A more efficient approach. (Okay after testing turns out this is exactly the same solution)

	row_offset -- the index of the first row of the tree we're traversing (0 is first)
	col_offset -- the index of the first column of the tree we're traversing
	
	Basically, keep splitting into sub-trees and take the sub-tree that's larger.
	
	Extremely efficient, runs in 0.02 seconds.
 */
long triangle_sum(int row_offset, int col_offset)
{
	
	call_count++;
	
	//Out of bounds: too far left or too far down
	if(col_offset > row_offset || col_offset < 0 || row_offset > ROWS)
	{
		//just stop
		printf("ERROR\n");
		return -1;
	}
	//if on the last row
	if(row_offset == ROWS)
	{
		//return the value of this node
		return TRIANGLE[row_offset][col_offset];
	}
	
	
	int left = triangle_sum(row_offset + 1, col_offset);
	int right = triangle_sum(row_offset + 1, col_offset + 1);
	return TRIANGLE[row_offset][col_offset] + (left > right ? left : right);

	
	
}
int main(void)
{
	long sum = triangle_sum(0, 0);
	
	printf("Largest sum found: %ld\nCalled %d times.\n", sum, call_count);
	
	return 0;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]){
    char *line, *tokptr;
    size_t len = 0, read;
    uint64_t tok_n, sum, l_len = 0, i = 0, line_n = 0;
    uint64_t **triangle = malloc(sizeof(uint64_t*) * 100);
    FILE *input = NULL;

    if(argc == 2){  // we are reading from file
        if(access(argv[1], R_OK)){
            fprintf(stderr, "Could not access file %s\n", argv[1]);
            return EXIT_FAILURE;
        }
        input = fopen(argv[1], "r");
    } else {
        input = stdin;
    }

    while((read=getline(&line, &len, input)) != EOF){
        uint64_t *n_field;
        tok_n = 0;
        read = read - 1;
        line[read] = '\0';
        if(strlen(line) == 0){
            fprintf(stderr, "lol no hahahah\n");
            return EXIT_FAILURE;
        }
        for(i=0; i < read; i++){
            if(line[i] == 0x20){
                tok_n += 1;
            }
        }
        n_field = malloc(sizeof(uint64_t) * tok_n);
        
        tokptr = strtok(line, " ");
        for(i=0; i < tok_n; i++){
            n_field[i] = atoi(tokptr);
            tokptr = strtok(NULL, " ");
        }
        triangle[line_n] = n_field;
        line_n += 1;
    }

    sum = triangle_sum(line_n, triangle);
    
    for(i=line_n; i; i--){
        free(triangle[i]);
    }
    free(triangle);
    printf("%lu\n", sum);
}