LoginSignup
1
0

More than 1 year has passed since last update.

二分探索動画のコード

Last updated at Posted at 2022-07-31

# 入力の受け取り
N,Q=map(int,input().split())
A=list(map(int,input().split()))
 
# Aをソート
A.sort()
 
# Q回
for i in range(Q):
    # 入力の受け取り
    x=int(input())
 
    # xがAの中で最小の要素以下である場合
    if x<=A[0]:
        # N人
        print(N)

    # xがAの中で最大の要素より大きい場合
    elif A[N-1]<x:
        # 0人
        print(0)

    # 二分探索
    else:
        # 左
        l=0
        # 右
        r=N-1
    
        # 1<右-左の間
        while 1<r-l:
            # 中央
            c=(l+r)//2
    
            # A[c]<xならば(条件を満たさない場合)
            if A[c]<x:
                # 左=中央と更新
                l=c
            # そうでなければ(x≤A[c] 条件を満たす場合)
            else:
                # 右=中央と更新
                r=c

        # 答え:(N-r)人
        print(N-r)

ライブラリあり

# 入力の受け取り
N,Q=map(int,input().split())
A=list(map(int,input().split()))
 
# Aをソート
A.sort()

# ライブラリをインポート
import bisect

# Q回
for i in range(Q):
    # 入力の受け取り
    x=int(input())
 
    # xがAの中で最小の要素以下である場合
    if x<=A[0]:
        # N人
        print(N)

    # xがAの中で最大の要素より大きい場合
    elif A[N-1]<x:
        print(0)

    # 二分探索
    else:
        
        r=bisect.bisect_left(A, x)
        
        # 答え:(N-r)人
        print(N-r)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0