ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

1182๋ฒˆ: ๋ถ€๋ถ„์ˆ˜์—ด์˜ ํ•ฉ

์ฒซ์งธ ์ค„์— ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” N๊ณผ ์ •์ˆ˜ S๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) ๋‘˜์งธ ์ค„์— N๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ์ •์ˆ˜์˜ ์ ˆ๋Œ“๊ฐ’์€ 100,000์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค.

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/1182
package main

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

var (
	count int
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n, s int
	fmt.Fscanln(reader, &n, &s)
	var seq = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &seq[i])
	}
	computeSubsequenceCount(0, 0, s, seq)
	fmt.Fprintln(writer, count)
}

func computeSubsequenceCount(index, sum, aim int, seq []int) {
	if index > len(seq)-1 {
		return
	}
	sum += seq[index]
	if sum == aim {
		count++
	}
	computeSubsequenceCount(index+1, sum, aim, seq)            // ํ˜„์žฌ ์ธ๋ฑ์Šค ๊ฐ’์„ ๋”ํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ
	computeSubsequenceCount(index+1, sum-seq[index], aim, seq) // ํ˜„์žฌ ์ธ๋ฑ์Šค ๊ฐ’์„ ๋”ํ•˜๋Š” ๊ฒฝ์šฐ
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/1182
import sys

count = 0
seq = []

def compute_subsequence_count(index, sum, aim):
    global count
    if index > len(seq)-1:
        return
    sum += seq[index]
    if sum == aim:
        count += 1
    compute_subsequence_count(index+1, sum, aim)
    compute_subsequence_count(index+1, sum-seq[index], aim)

if __name__ == "__main__":
    n, s = list(map(int, sys.stdin.readline().split()))
    seq = list(map(int, sys.stdin.readline().split()))
    compute_subsequence_count(0, 0, s)
    print(count)
728x90
๋Œ“๊ธ€