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

 

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

 

1920๋ฒˆ: ์ˆ˜ ์ฐพ๊ธฐ

์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N(1≤N≤100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ ์ค„์—๋Š” N๊ฐœ์˜ ์ •์ˆ˜ A[1], A[2], …, A[N]์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ ์ค„์—๋Š” M(1≤M≤100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ ์ค„์—๋Š” M๊ฐœ์˜ ์ˆ˜๋“ค์ด ์ฃผ์–ด์ง€๋Š”๋ฐ, ์ด ์ˆ˜๋“ค์ด A์•ˆ

www.acmicpc.net


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

๐ŸŽจ Go

// https://www.acmicpc.net/problem/1920
// ๋ฐฐ์—ด์„ ์ •๋ ฌํ•œ ํ›„ ์ด๋ถ„ ํƒ์ƒ‰์œผ๋กœ ๊ฐ’์„ ์ฐพ์•„ ๋ด…์‹œ๋‹ค.
package main

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

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

	var n, m int
	fmt.Fscanln(reader, &n)

	var a = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &a[i])
	}

	fmt.Fscanln(reader, &m)
	var b = make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d ", &b[i])
	}

	sort.Ints(a) // ์ •๋ ฌ
	for i := 0; i < m; i++ {
		if binarySearch(a, b[i]) {
			fmt.Fprintln(writer, 1)
		} else {
			fmt.Fprintln(writer, 0)
		}
	}
}

// binarySearch
// array: sorted array
// val: value to be searched
func binarySearch(array []int, val int) bool {
	low := 0               // lower bound
	high := len(array) - 1 // upper bound

	for low <= high {
		mid := (low + high) / 2

		if array[mid] < val {
			low = mid + 1
		} else {
			high = mid - 1
		}
	}

	if low == len(array) || array[low] != val {
		return false
	}
	return true
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/1920
# ๋ฐฐ์—ด์„ ์ •๋ ฌํ•œ ํ›„ ์ด๋ถ„ ํƒ์ƒ‰์œผ๋กœ ๊ฐ’์„ ์ฐพ์•„ ๋ด…์‹œ๋‹ค.
import sys
import bisect

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    a = list(map(int, sys.stdin.readline().split()))
    a.sort()    # ์ •๋ ฌ
    m = int(sys.stdin.readline())
    b = list(map(int, sys.stdin.readline().split()))

    for v in b:
        i = bisect.bisect_left(a, v)    # bisect ๋ชจ๋“ˆ ์ด์šฉํ•˜์—ฌ ์ด๋ถ„ํƒ์ƒ‰
        if i < len(a) and a[i] == v:
            print(1)
        else:
            print(0)

cf. ์ด๋ถ„ํƒ์ƒ‰(์ด์ง„ํƒ์ƒ‰)์˜ ์‹œ๊ฐ„๋ณต์žก๋„ = O(logN)

728x90
๋Œ“๊ธ€