█████████ ████ ███░░░░░███ ░░███ ███ ░░░ ██████ ███████ ██████ ██████ ░███ ███░░███ ███░░███ ███░░███ ███░░███ ░███ ░███ ░███░███ ░███ ░███████ ░███ ░███ ░░███ ███░███ ░███░███ ░███ ░███░░░ ░███ ░███ ░░█████████ ░░██████ ░░████████░░██████ ░░██████ ░░░░░░░░░ ░░░░░░ ░░░░░░░░ ░░░░░░ ░░░░░░

Envío 583

Problema 0x25 - Suma de un subarreglo grande

  • Autor: Mejibyte
  • Fecha: 2020-09-08 03:33:08 UTC (Hace más de 4 años)
Caso # Resultado Tiempo Memoria
#1
Correcto
0.004 s 5 KBi
#2
Correcto
0.004 s 6 KBi
#3
Correcto
0.004 s 5 KBi
#4
Correcto
0.005 s 5 KBi
#5
Correcto
0.004 s 5 KBi
#6
Correcto
0.005 s 50 KBi
#7
Correcto
0.005 s 4 KBi
#8
Correcto
0.034 s 6 KBi
#9
Correcto
0.132 s 6 KBi
#10
Correcto
0.125 s 8 KBi
#11
Correcto
0.149 s 6 KBi
#12
Correcto
0.144 s 6 KBi
#13
Correcto
0.177 s 6 KBi
#14
Correcto
0.151 s 6 KBi
Puntos totales: 100 / 100

Código

// Solution to https://codeo.app/problemas/0x25-suma-de-un-subarreglo
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func solve(a, s []int, p, q int) {
	// O(1)
	sum := s[q] // a[0] + a[1] + ... + a[q]
	if p-1 >= 0 {
		sum -= s[p-1]
	}

	// Alternatively, this works too, and some people might like it more.
	// sum := s[q] - s[p] + a[p];
	fmt.Println(sum)
}

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	a := make([]int, n)
	s := make([]int, n)
	sum := 0
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i], _ = strconv.Atoi(scanner.Text())
		sum += a[i]
		s[i] = sum
	}

	// s[i] = sum of a[0] + ... + a[i]
	var c int
	scanner.Scan()
	c, _ = strconv.Atoi(scanner.Text())

	for k := 0; k < c; k++ {
		var p, q int

		scanner.Scan()
		p, _ = strconv.Atoi(scanner.Text())
		scanner.Scan()

		q, _ = strconv.Atoi(scanner.Text())
		solve(a, s, p, q)
	}
}