SlideShare uma empresa Scribd logo
1 de 12
Binary Search
Binary Search란?

• 정렬된 시퀀스에서 빠르게 값을 찾는데 사용되는 알고리즘
  – 목표값을 검색공간의 중간값과 비교한다.
  – 목표값이 중간값보다 작으면 중간값의 왼쪽 서브시퀀스를, 중간값보다
    크면 오른쪽 서브시퀀스를 새로운 검색공간으로 한다.
  – 목표값을 찾을 때까지 이 과정을 반복한다.
Binary Search란?

Target value: 55

      z     5      13   19   22   41   55    68   72   81   98




                                       55    68   72   81   98

                                            원소의 개수가 짝수일 때 중간값은?

                                       55    68
Complexity

•   O(log N)
•   단, 시퀀스에 대한 Random access가 가능할 경우에 한함
Discrete Binary
    Search
• 배열을 인덱스를 해당 값에 사상하는 함수로 생각할 수 있음
• 배열이 정렬되어있다는 것은 단조함수(Monotonic function) 라는 것
  을 의미
• 따라서, 정의역이 정수 집합에 속하는 임의의 단조함수 f(x)에 대해
  이진 탐색을 적용하는 것이 가능
• 장점
  – 목표값을 찾기 위해 최대 O(log N)의 비교가 필요
  – 함수값을 그렇게 많이 계산할 필요없음
  – 배열과 달리 메모리에 제한을 받지 않음
Discrete Binary
    Search
• f(x) = x^8 + x^4 + x^2 + 1 (단조 증가 함수)
• 검색공간(정의역): 1~1024
• 목표값: 277
   –   f(512) > 277
   –   f(256) > 277
   –   f(128) > 277
   –   ...
   –   …
   –   f(4) > 277
   –   f(2) = 277
Main Theorem

• Predictate(술어) p: 검색 공간에 대해 Boolean 값을 반환하는 함수
  로 정의. EX) Is A[x] greater than or equal to the target value?
• Main theorem: 어떤 문제의 해를 찾을 때, 모든 y>x에 대해 p(x)를
  통해 p(y)의 값을 추정할 수 있다면 이진 탐색을 사용할 수 있다.
• EX) p(x)가 true인 가장 작은 x를 찾아라
   – 검색 공간이 이미 정렬되어 있다면 Main theorem을 만족하므로 이직 탐색 적용
     가능
   – p(x)가 true인 첫번째 x가 답
Main Theorem

• 특정한 값을 탐색하는 형태로는 모델링할 수 없지만 어
  떤 predictate를 정의하고 이를 평가하는 방식으로 바꿔
  서 풀 수 있는 문제들이 많음
SRM 169
Division1 Level2
• 일렬로 늘어선 캐비닛이 있고 각 캐비닛 안에 있는 폴더의 개수가
  배열로 주어져 있을 때, N 명의 직원으로 특정한 폴더를 찾고자 한
  다. 늘어선 캐비닛을 N개의 섹션으로 나누고(각 섹션의 캐비닛의
  개수가 같을 필요는 없다.) 각 직원이 자신의 섹션에 그 폴더가 있는
  지 찾게 할 때, 한 직원이 뒤져야 하는 폴더의 최대 개수의 최소값을
  구하여라. 단, 캐비닛은 안에 들어있는 폴더의 개수로 정렬되어 있
  다.
• EX)
  –   {10, 20, 30, 40, 50, 60, 70, 80, 90}
  –   직원 수: 3
  –   10 20 30 40 50 | 60 70 | 80 90
  –   return 170
SRM 169
Division1 Level2
• 한 직원이 뒤져야 하는 폴더의 최대 개수가 MAX로 주어질 때 필요
  한 직원의 수를 구하면?
• 앞의 문제는 결국 필요한 직원의 수가 이용할 수 있는 직원의 수(N)
  보다 작거나 같을 때, MAX의 최소값을 구하는 문제
  – Predicate p: 이용할 수 있는 직원의 수가 주어질 때, 각 직원들이 담당해야 하는
    폴더의 최대 개수가 x가 되도록 섹션을 나눌 수 있는가?
     •   필요한 직원의 수와 x는 반비례(단조 감소)
     •   low 의 초기값: 캐비닛에 들어있는 폴더의 최대 개수
     •   High의 초기값: 폴더 개수의 총 합
            – x = (low + high)
            – 필요한 직원의 수가 이용할 수 있는 직원의 수보다 크면 x를 증가(low = x + 1)
            – 아니면 x를 감소(hi = x)
            – 필요한 직원의 수와 이용 가능한 직원의 수가 같은 최소의 x를 찾을 때까지(low == high) 이 과
               정을 반복
SRM 169
Division1 Level2
int getMostWork( vector<int> folders, int workers ) {
  int n = folders.size();
  int lo = *max_element( folders.begin(), folders.end() );
  int hi = accumulate( folders.begin(), folders.end(), 0 );

    while ( lo < hi ) {
      int x = lo + (hi-lo)/2;
      int required = 1, current_load = 0;
      for ( int i=0; i<n; ++i ) {
         if ( current_load + folders[i] <= x ) {
            // the current worker can handle it
            current_load += folders[i];
         }
         else {
            // assign next worker
            ++required;
            current_load = folders[i];
         }
      }
      if ( required <= workers )
         hi = x;
      else
         lo = x+1;
    }
    return lo;
}
Binary Search in
      STL
•   bool binary_search (ForwardIterator beg, ForwardIterator end, const T& value)

•   ForwardIterator upper_bound (ForwardIterator beg, ForwardIterator end, const T& value)

•   ForwardIterator lower_bound (ForwardIterator beg, ForwardIterator end, const T& value)

•   pair<ForwardIterator,ForwardIterator> equal_range (ForwardIterator beg, ForwardIterator end,
    const T& value)

Mais conteúdo relacionado

Mais procurados

[Swift] Data Structure - Heap
[Swift] Data Structure - Heap[Swift] Data Structure - Heap
[Swift] Data Structure - HeapBill Kim
 
R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작Terry Cho
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1happychallenge
 
[Swift] Data Structure - Queue
[Swift] Data Structure - Queue[Swift] Data Structure - Queue
[Swift] Data Structure - QueueBill Kim
 
R 기본-데이타형 소개
R 기본-데이타형 소개R 기본-데이타형 소개
R 기본-데이타형 소개Terry Cho
 
[C++adv] STL 사용법과 주의 사항
[C++adv] STL 사용법과 주의 사항[C++adv] STL 사용법과 주의 사항
[C++adv] STL 사용법과 주의 사항MinGeun Park
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search TreeBill Kim
 
R 기초 : R Basics
R 기초 : R BasicsR 기초 : R Basics
R 기초 : R BasicsYoonwhan Lee
 
05_STL컨테이너정리
05_STL컨테이너정리05_STL컨테이너정리
05_STL컨테이너정리noerror
 
단순 Linked list
단순 Linked list단순 Linked list
단순 Linked listKimDaeho
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary TreeBill Kim
 
02. data structure and stl
02. data structure and stl02. data structure and stl
02. data structure and stl승혁 조
 
R과 기초통계 : 02.기술통계-자료나타내기
R과 기초통계 : 02.기술통계-자료나타내기R과 기초통계 : 02.기술통계-자료나타내기
R과 기초통계 : 02.기술통계-자료나타내기Yoonwhan Lee
 
Python 강좌 발표 자료
Python 강좌 발표 자료Python 강좌 발표 자료
Python 강좌 발표 자료Soobin Jung
 
Hash table
Hash tableHash table
Hash tableSeoYeong
 
Stl vector, list, map
Stl vector, list, mapStl vector, list, map
Stl vector, list, mapNam Hyeonuk
 
성공적인웹프로그래밍
성공적인웹프로그래밍성공적인웹프로그래밍
성공적인웹프로그래밍dgmong
 
[0326 석재호]상호배타적 집합의 처리
[0326 석재호]상호배타적 집합의 처리[0326 석재호]상호배타적 집합의 처리
[0326 석재호]상호배타적 집합의 처리Jaeho Seok
 

Mais procurados (20)

[Swift] Data Structure - Heap
[Swift] Data Structure - Heap[Swift] Data Structure - Heap
[Swift] Data Structure - Heap
 
R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1
 
[Swift] Data Structure - Queue
[Swift] Data Structure - Queue[Swift] Data Structure - Queue
[Swift] Data Structure - Queue
 
R 기본-데이타형 소개
R 기본-데이타형 소개R 기본-데이타형 소개
R 기본-데이타형 소개
 
C++ stl
C++ stlC++ stl
C++ stl
 
[C++adv] STL 사용법과 주의 사항
[C++adv] STL 사용법과 주의 사항[C++adv] STL 사용법과 주의 사항
[C++adv] STL 사용법과 주의 사항
 
Example
ExampleExample
Example
 
[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree[Swift] Data Structure - Binary Search Tree
[Swift] Data Structure - Binary Search Tree
 
R 기초 : R Basics
R 기초 : R BasicsR 기초 : R Basics
R 기초 : R Basics
 
05_STL컨테이너정리
05_STL컨테이너정리05_STL컨테이너정리
05_STL컨테이너정리
 
단순 Linked list
단순 Linked list단순 Linked list
단순 Linked list
 
[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree[Swift] Data Structure - Binary Tree
[Swift] Data Structure - Binary Tree
 
02. data structure and stl
02. data structure and stl02. data structure and stl
02. data structure and stl
 
R과 기초통계 : 02.기술통계-자료나타내기
R과 기초통계 : 02.기술통계-자료나타내기R과 기초통계 : 02.기술통계-자료나타내기
R과 기초통계 : 02.기술통계-자료나타내기
 
Python 강좌 발표 자료
Python 강좌 발표 자료Python 강좌 발표 자료
Python 강좌 발표 자료
 
Hash table
Hash tableHash table
Hash table
 
Stl vector, list, map
Stl vector, list, mapStl vector, list, map
Stl vector, list, map
 
성공적인웹프로그래밍
성공적인웹프로그래밍성공적인웹프로그래밍
성공적인웹프로그래밍
 
[0326 석재호]상호배타적 집합의 처리
[0326 석재호]상호배타적 집합의 처리[0326 석재호]상호배타적 집합의 처리
[0326 석재호]상호배타적 집합의 처리
 

Destaque

Plan lector en la muerte surge el nacimiento
Plan lector   en la muerte surge el nacimientoPlan lector   en la muerte surge el nacimiento
Plan lector en la muerte surge el nacimientoKAtiRojChu
 
Práctica calificada n° 2 (2)
Práctica calificada n° 2 (2)Práctica calificada n° 2 (2)
Práctica calificada n° 2 (2)KAtiRojChu
 
Derechos humanos
Derechos humanosDerechos humanos
Derechos humanosKAtiRojChu
 
Estructura del universo
Estructura del universoEstructura del universo
Estructura del universoKAtiRojChu
 
Práctica calificada n° 2 (3)
Práctica calificada n° 2 (3)Práctica calificada n° 2 (3)
Práctica calificada n° 2 (3)KAtiRojChu
 
Animals in winter
Animals in winterAnimals in winter
Animals in winterEmily Ott
 
BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247
BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247
BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247Paola Bichara
 
人生成功的40条黄金定律
人生成功的40条黄金定律人生成功的40条黄金定律
人生成功的40条黄金定律V V
 
Biomagnetismo revolucionando la medicina
Biomagnetismo revolucionando la medicinaBiomagnetismo revolucionando la medicina
Biomagnetismo revolucionando la medicinaAngel Hernandez
 
One thing 24 july16
One thing 24 july16One thing 24 july16
One thing 24 july16SSMC
 
Práctica calificada n° 2
Práctica calificada n° 2Práctica calificada n° 2
Práctica calificada n° 2KAtiRojChu
 

Destaque (12)

Plan lector en la muerte surge el nacimiento
Plan lector   en la muerte surge el nacimientoPlan lector   en la muerte surge el nacimiento
Plan lector en la muerte surge el nacimiento
 
Cv2
Cv2Cv2
Cv2
 
Práctica calificada n° 2 (2)
Práctica calificada n° 2 (2)Práctica calificada n° 2 (2)
Práctica calificada n° 2 (2)
 
Derechos humanos
Derechos humanosDerechos humanos
Derechos humanos
 
Estructura del universo
Estructura del universoEstructura del universo
Estructura del universo
 
Práctica calificada n° 2 (3)
Práctica calificada n° 2 (3)Práctica calificada n° 2 (3)
Práctica calificada n° 2 (3)
 
Animals in winter
Animals in winterAnimals in winter
Animals in winter
 
BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247
BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247
BOOK_ConferenceProceedings2015_FinalCHECKEDwithAppendixp.240-247
 
人生成功的40条黄金定律
人生成功的40条黄金定律人生成功的40条黄金定律
人生成功的40条黄金定律
 
Biomagnetismo revolucionando la medicina
Biomagnetismo revolucionando la medicinaBiomagnetismo revolucionando la medicina
Biomagnetismo revolucionando la medicina
 
One thing 24 july16
One thing 24 july16One thing 24 july16
One thing 24 july16
 
Práctica calificada n° 2
Práctica calificada n° 2Práctica calificada n° 2
Práctica calificada n° 2
 

Semelhante a Binary Search

GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)Kyoungchan Lee
 
Python programming for Bioinformatics
Python programming for BioinformaticsPython programming for Bioinformatics
Python programming for BioinformaticsHyungyong Kim
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary SearchBill Kim
 
하스켈로 알고리즘 문제 풀기
하스켈로 알고리즘 문제 풀기하스켈로 알고리즘 문제 풀기
하스켈로 알고리즘 문제 풀기민석 이
 
Python+numpy pandas 1편
Python+numpy pandas 1편Python+numpy pandas 1편
Python+numpy pandas 1편Yong Joon Moon
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Yong Joon Moon
 
프로젝트#6 (오탈자 검사)보고서
프로젝트#6 (오탈자 검사)보고서프로젝트#6 (오탈자 검사)보고서
프로젝트#6 (오탈자 검사)보고서mil23
 
JVM 메모리 해부학
JVM 메모리 해부학JVM 메모리 해부학
JVM 메모리 해부학Greg Lee
 
Algorithms summary korean
Algorithms summary koreanAlgorithms summary korean
Algorithms summary koreanYoung-Min kang
 
[Commit Again] 1주차 STL study
[Commit Again] 1주차 STL study[Commit Again] 1주차 STL study
[Commit Again] 1주차 STL study경 송
 
개경프 1주차 Stl study
개경프 1주차 Stl study개경프 1주차 Stl study
개경프 1주차 Stl study경 송
 
Linq to object using c#
Linq to object using c#Linq to object using c#
Linq to object using c#병걸 윤
 
자료구조 06 최종 보고서
자료구조 06 최종 보고서자료구조 06 최종 보고서
자료구조 06 최종 보고서pkok15
 
2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdf2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdfkd19h
 
2012 Ds B2 02
2012 Ds B2 022012 Ds B2 02
2012 Ds B2 02chl132435
 
Coursera Machine Learning (by Andrew Ng)_강의정리
Coursera Machine Learning (by Andrew Ng)_강의정리Coursera Machine Learning (by Andrew Ng)_강의정리
Coursera Machine Learning (by Andrew Ng)_강의정리SANG WON PARK
 
자료구조 Project2
자료구조 Project2자료구조 Project2
자료구조 Project2KoChungWook
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304Yong Joon Moon
 

Semelhante a Binary Search (20)

GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
 
Python programming for Bioinformatics
Python programming for BioinformaticsPython programming for Bioinformatics
Python programming for Bioinformatics
 
[Algorithm] Binary Search
[Algorithm] Binary Search[Algorithm] Binary Search
[Algorithm] Binary Search
 
자료구조02
자료구조02자료구조02
자료구조02
 
하스켈로 알고리즘 문제 풀기
하스켈로 알고리즘 문제 풀기하스켈로 알고리즘 문제 풀기
하스켈로 알고리즘 문제 풀기
 
Python+numpy pandas 1편
Python+numpy pandas 1편Python+numpy pandas 1편
Python+numpy pandas 1편
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815
 
프로젝트#6 (오탈자 검사)보고서
프로젝트#6 (오탈자 검사)보고서프로젝트#6 (오탈자 검사)보고서
프로젝트#6 (오탈자 검사)보고서
 
JVM 메모리 해부학
JVM 메모리 해부학JVM 메모리 해부학
JVM 메모리 해부학
 
Algorithms summary korean
Algorithms summary koreanAlgorithms summary korean
Algorithms summary korean
 
[Commit Again] 1주차 STL study
[Commit Again] 1주차 STL study[Commit Again] 1주차 STL study
[Commit Again] 1주차 STL study
 
개경프 1주차 Stl study
개경프 1주차 Stl study개경프 1주차 Stl study
개경프 1주차 Stl study
 
Linq to object using c#
Linq to object using c#Linq to object using c#
Linq to object using c#
 
자료구조 06 최종 보고서
자료구조 06 최종 보고서자료구조 06 최종 보고서
자료구조 06 최종 보고서
 
2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdf2012 Ds B2 02 Pdf
2012 Ds B2 02 Pdf
 
2012 Ds B2 02
2012 Ds B2 022012 Ds B2 02
2012 Ds B2 02
 
Coursera Machine Learning (by Andrew Ng)_강의정리
Coursera Machine Learning (by Andrew Ng)_강의정리Coursera Machine Learning (by Andrew Ng)_강의정리
Coursera Machine Learning (by Andrew Ng)_강의정리
 
자료구조 Project2
자료구조 Project2자료구조 Project2
자료구조 Project2
 
Mahout
MahoutMahout
Mahout
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304
 

Mais de skku_npc

Maximum Flow
Maximum FlowMaximum Flow
Maximum Flowskku_npc
 
Computational Complexity
Computational ComplexityComputational Complexity
Computational Complexityskku_npc
 
String Searching Algorithms
String Searching AlgorithmsString Searching Algorithms
String Searching Algorithmsskku_npc
 
disjoint-set data structures
disjoint-set data structuresdisjoint-set data structures
disjoint-set data structuresskku_npc
 
Line sweep algorithms
Line sweep algorithmsLine sweep algorithms
Line sweep algorithmsskku_npc
 
Prime numbers, factorization
Prime numbers, factorizationPrime numbers, factorization
Prime numbers, factorizationskku_npc
 
Mathematics
MathematicsMathematics
Mathematicsskku_npc
 
Greedy is Good
Greedy is GoodGreedy is Good
Greedy is Goodskku_npc
 
How to find a solution
How to find a solutionHow to find a solution
How to find a solutionskku_npc
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingskku_npc
 
An introduction to recursion
An introduction to recursionAn introduction to recursion
An introduction to recursionskku_npc
 
Algorithm Games
Algorithm GamesAlgorithm Games
Algorithm Gamesskku_npc
 
Introduction to Graphs
Introduction to GraphsIntroduction to Graphs
Introduction to Graphsskku_npc
 

Mais de skku_npc (13)

Maximum Flow
Maximum FlowMaximum Flow
Maximum Flow
 
Computational Complexity
Computational ComplexityComputational Complexity
Computational Complexity
 
String Searching Algorithms
String Searching AlgorithmsString Searching Algorithms
String Searching Algorithms
 
disjoint-set data structures
disjoint-set data structuresdisjoint-set data structures
disjoint-set data structures
 
Line sweep algorithms
Line sweep algorithmsLine sweep algorithms
Line sweep algorithms
 
Prime numbers, factorization
Prime numbers, factorizationPrime numbers, factorization
Prime numbers, factorization
 
Mathematics
MathematicsMathematics
Mathematics
 
Greedy is Good
Greedy is GoodGreedy is Good
Greedy is Good
 
How to find a solution
How to find a solutionHow to find a solution
How to find a solution
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
An introduction to recursion
An introduction to recursionAn introduction to recursion
An introduction to recursion
 
Algorithm Games
Algorithm GamesAlgorithm Games
Algorithm Games
 
Introduction to Graphs
Introduction to GraphsIntroduction to Graphs
Introduction to Graphs
 

Binary Search

  • 2. Binary Search란? • 정렬된 시퀀스에서 빠르게 값을 찾는데 사용되는 알고리즘 – 목표값을 검색공간의 중간값과 비교한다. – 목표값이 중간값보다 작으면 중간값의 왼쪽 서브시퀀스를, 중간값보다 크면 오른쪽 서브시퀀스를 새로운 검색공간으로 한다. – 목표값을 찾을 때까지 이 과정을 반복한다.
  • 3. Binary Search란? Target value: 55 z 5 13 19 22 41 55 68 72 81 98 55 68 72 81 98 원소의 개수가 짝수일 때 중간값은? 55 68
  • 4. Complexity • O(log N) • 단, 시퀀스에 대한 Random access가 가능할 경우에 한함
  • 5. Discrete Binary Search • 배열을 인덱스를 해당 값에 사상하는 함수로 생각할 수 있음 • 배열이 정렬되어있다는 것은 단조함수(Monotonic function) 라는 것 을 의미 • 따라서, 정의역이 정수 집합에 속하는 임의의 단조함수 f(x)에 대해 이진 탐색을 적용하는 것이 가능 • 장점 – 목표값을 찾기 위해 최대 O(log N)의 비교가 필요 – 함수값을 그렇게 많이 계산할 필요없음 – 배열과 달리 메모리에 제한을 받지 않음
  • 6. Discrete Binary Search • f(x) = x^8 + x^4 + x^2 + 1 (단조 증가 함수) • 검색공간(정의역): 1~1024 • 목표값: 277 – f(512) > 277 – f(256) > 277 – f(128) > 277 – ... – … – f(4) > 277 – f(2) = 277
  • 7. Main Theorem • Predictate(술어) p: 검색 공간에 대해 Boolean 값을 반환하는 함수 로 정의. EX) Is A[x] greater than or equal to the target value? • Main theorem: 어떤 문제의 해를 찾을 때, 모든 y>x에 대해 p(x)를 통해 p(y)의 값을 추정할 수 있다면 이진 탐색을 사용할 수 있다. • EX) p(x)가 true인 가장 작은 x를 찾아라 – 검색 공간이 이미 정렬되어 있다면 Main theorem을 만족하므로 이직 탐색 적용 가능 – p(x)가 true인 첫번째 x가 답
  • 8. Main Theorem • 특정한 값을 탐색하는 형태로는 모델링할 수 없지만 어 떤 predictate를 정의하고 이를 평가하는 방식으로 바꿔 서 풀 수 있는 문제들이 많음
  • 9. SRM 169 Division1 Level2 • 일렬로 늘어선 캐비닛이 있고 각 캐비닛 안에 있는 폴더의 개수가 배열로 주어져 있을 때, N 명의 직원으로 특정한 폴더를 찾고자 한 다. 늘어선 캐비닛을 N개의 섹션으로 나누고(각 섹션의 캐비닛의 개수가 같을 필요는 없다.) 각 직원이 자신의 섹션에 그 폴더가 있는 지 찾게 할 때, 한 직원이 뒤져야 하는 폴더의 최대 개수의 최소값을 구하여라. 단, 캐비닛은 안에 들어있는 폴더의 개수로 정렬되어 있 다. • EX) – {10, 20, 30, 40, 50, 60, 70, 80, 90} – 직원 수: 3 – 10 20 30 40 50 | 60 70 | 80 90 – return 170
  • 10. SRM 169 Division1 Level2 • 한 직원이 뒤져야 하는 폴더의 최대 개수가 MAX로 주어질 때 필요 한 직원의 수를 구하면? • 앞의 문제는 결국 필요한 직원의 수가 이용할 수 있는 직원의 수(N) 보다 작거나 같을 때, MAX의 최소값을 구하는 문제 – Predicate p: 이용할 수 있는 직원의 수가 주어질 때, 각 직원들이 담당해야 하는 폴더의 최대 개수가 x가 되도록 섹션을 나눌 수 있는가? • 필요한 직원의 수와 x는 반비례(단조 감소) • low 의 초기값: 캐비닛에 들어있는 폴더의 최대 개수 • High의 초기값: 폴더 개수의 총 합 – x = (low + high) – 필요한 직원의 수가 이용할 수 있는 직원의 수보다 크면 x를 증가(low = x + 1) – 아니면 x를 감소(hi = x) – 필요한 직원의 수와 이용 가능한 직원의 수가 같은 최소의 x를 찾을 때까지(low == high) 이 과 정을 반복
  • 11. SRM 169 Division1 Level2 int getMostWork( vector<int> folders, int workers ) { int n = folders.size(); int lo = *max_element( folders.begin(), folders.end() ); int hi = accumulate( folders.begin(), folders.end(), 0 ); while ( lo < hi ) { int x = lo + (hi-lo)/2; int required = 1, current_load = 0; for ( int i=0; i<n; ++i ) { if ( current_load + folders[i] <= x ) { // the current worker can handle it current_load += folders[i]; } else { // assign next worker ++required; current_load = folders[i]; } } if ( required <= workers ) hi = x; else lo = x+1; } return lo; }
  • 12. Binary Search in STL • bool binary_search (ForwardIterator beg, ForwardIterator end, const T& value) • ForwardIterator upper_bound (ForwardIterator beg, ForwardIterator end, const T& value) • ForwardIterator lower_bound (ForwardIterator beg, ForwardIterator end, const T& value) • pair<ForwardIterator,ForwardIterator> equal_range (ForwardIterator beg, ForwardIterator end, const T& value)