35
im4u 봄방학 캠프 DAY 2; Discrete Optimization Problems Part I Part I 구종만 [email protected]

im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

im4u 봄방학 캠프DAY 2; Discrete Optimization Problems Part IPart I

구종만

[email protected]

Page 2: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 알고리즘디자인패러다임공부하기

� 이산최적화문제를대상으로디자인패러다임배우기 Part I

� 전체탐색 (exhaustive search)

오늘 할 얘기

� 전체탐색 (exhaustive search)

� 분할정복 (divide-and-conquer)

� .. With many many sample problems.

Page 3: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

병합 정렬 (Merge Sort)

(Image from Wikipedia)

Page 4: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

이분 검색 (Binary Search)

� 정렬된배열에서 27 찾기

Page 5: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 병합정렬과이분검색� 문제를해결하기위해입력을두개의작은입력으로분할

(paradigm) :

‘패턴’ 이 보이나요?

� 디자인패러다임 (paradigm) : 알고리즘이문제를풀기위해취하는전략의형태� 전략을공부하는것은새로운알고리즘을개발하는능력을쌓기위한좋은방법이된다

Page 6: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� “어떤한시대사람들의견해나사고를지배하고있는이론적틀이나개념의집합체.”

� Definition a la Thomas Kuhn

패러다임 (paradigm)

� 여기에서는, 일종의 ‘설계방식’ 정도로이해하면좋습니다.

� 알고리즘의분류수단으로볼수도있구요.

Page 7: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 결론부터말하자면: 연습이킹왕짱� 수많은예제문제를풀다보면, 일종의패턴을알아내는직관이발달하게되는데..

디자인 패러다임 공부하기

Page 8: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 여러개의답 (solution) 이있는문제

� 구성요소� 가능한 답의집합들 (feasible solutions)

� 답의적합도기준 (measure)

최적화 문제들 (Optimization Problems)

� 답의적합도기준 (measure)

� 여러개의답중가장적합도가높은답을찾아내는문제 !

Page 9: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 2008 컴바라기-SM엔터 4:4 미팅

Assignment Problem

연희 태연 윤아 아라

영정 82 42 88 56

재현 92 64 94 84

재영 50 91 64 47

� 컴바라기 4인의호감도합을최대화하는파트너배정방법은?

재영 50 91 64 47

재두 80 83 89 85

(사용된 이름은 모두 가명입니다)

Page 10: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

Traveling Salesman Problem

� 모든점을한번씩방문하는가장짧은경로는?

Page 11: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

최적화 문제를 해결하는 다양한 방법들

Page 12: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

최적화 문제를 해결하는 다양한 방법들

Page 13: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 모든답을다만들어보는거죠!

� 입력의크기가작거나, 답의개수가작을경우가장먼저떠올라야하는해법� 답의개수의상한을예측하는것이가장어려운부분

완전 탐색 (Exhaustive Search)

� 답의개수의상한을예측하는것이가장어려운부분

� 답의구조에대한 “직관” 을필요로한다

� 가끔은작은케이스를풀어봄으로써직관을얻을수도있다

� 거의항상재귀호출로구현된다!

� next_permutation() 을쓸때도있음

Page 14: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 세계최악(?) 의정렬알고리즘:

� 입력받은수열의모든배열 (permutation) 을구하고, 그중에정렬된배열을반환한다

적나라한 완전 탐색의 예

)!(nO

� 물론죽을때까지쓸일은없겠지만, 대충무슨뜻인지이해하시라고.. ^^;

Page 15: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 같은글자가인접해있지않은문자열을행운의문자열이라고하자.

� “abhazpqrx” 를재배열해서얻을수있는행운의문자열의수는?

The Lucky String

?

� (입력문자열의크기 <= 10)

From TopCoder SRM482 Div 2 Medium

Page 16: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� n 개의서로다른문자를재배열해서얻을수있는문자열의수: n!

� 답은언제나 n! 보다작다.

� 10! = 3,628,800

“Can We Brute-Force It?”

10! = 3,628,800

� n! 개의순서를모두시도하고이중 Lucky String 의수를센다. => Solved!

Page 17: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

Synchronizing Clocks

스위치스위치스위치스위치 번호번호번호번호 시계시계시계시계 번호번호번호번호

0 0,1,2

1 3,7,9,11

2 4,10,14,15

3 0,4,5,6,7

4 6,7,8,10,12

5 0,2,12,14,15

� 16개의시계: 12시, 3시, 6시, 9시만가리킨다

� 10개의스위치: 연결된시계를 3시간씩전진시킨다

From IOI ’94 Day 2, Clocks

5 0,2,12,14,15

6 3,14,15

7 4,5,7,14,15

8 1,2,3,4,5

9 3,4,5,9,13

Page 18: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 완전탐색에의한아이디어:

� 16개의시계가가질수있는모든상태를완전탐색하면어떨까?

“Can We Brute-Force It?”

� .. 어떻게할지는그렇다치더라도, 모든상태의수는전부몇개일까?

Page 19: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 한개의시계에는 4개의상태가있음

� 16개의시계가있으므로, 전체상태의수는

Synchronizing Clocks

296,967,294,424 3216==

� 당연히계산불가능한수 ! 어떻게해야하나?

Page 20: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� Key Observation 1

� 스위치를누르는순서는중요하지않다. 회수만이중요할뿐이다. (*)

� Key Observation 2

Synchronizing Clocks

� 한스위치를 4번누르면, 한번도누르지않은것과다를바가없다.

� 따라서, 0번, 1번, 2번, 3번만이의미가있다.

� 결국, 스위치를누르는방법의수는 576,048,1410 =

Page 21: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

N-Queen

� N x N 크기의체스판위에 N개의퀸을놓되, 서로공격할수없도록하고싶다. 이런경우의수는?

� (N <= 12)

Page 22: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 답의상한에대한첫번째시도:

� …별로도움이안된다…

� 수학적으로답의수를세는것은꽤나어렵다

“Can We Brute-Force It?”

nn4212 212 ≈

� 수학적으로답의수를세는것은꽤나어렵다� 어쨌든가우스도한번틀린문제라고하니까요.

Page 23: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 가장간단한아이디어에서시작하자:

� n < 6 정도까지는세볼만한듯하니, 프로그램을짜서실제로어떻게답의개수가어떻게증가하는지를보자

� 간단한프로그램을짜서아이디어를검증하자.

Smart Ideas Are Plan B

� 간단한프로그램을짜서아이디어를검증하자.

� 실제로해보면, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, ..

� 수학적으로잘검증되고, ‘멋있는’ 모델들은나중으로미뤄두자.

Page 24: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� N (<= 128) 개의성냥개비가있다.

MatchCounting

� 이성냥개비들로만들수없는가장작은양의정수는?

� 예) N=5 이면 6 은만들수없다

� 예) N=9 이면 20 은만들수없다

TopCoder SRM239 Div1 MedImages from ipsc.ksp.sk

Page 25: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 수학적으로해결하기란까다롭다

� n <= 40 정도까지만무식하게돌려볼까?

“Can We Brute-Force It?”

� 거의대부분이 8 로구성되어있네?

� Key Observation: 888 은만들수있고, 8888 은만들수없으면, 답은 4자리.

Page 26: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 알고리즘디자인패러다임의대표격

� 삼국지에서도나오니까말다했죠?

� 병합정렬과이분검색이분할정복의대표적예

Divide & Conquer

� 병합정렬과이분검색이분할정복의대표적예

� 두가지목적� 얼핏보기에오래걸리는문제를빨리해결

� 재귀적으로정의되는문제들을해결

Page 27: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� Given a 100x100 matrix , compute .

� Simple, but with ?

� 행렬곱셈을 으로한다고하면, 곱셈 1000

Fast Matrix Exponentiation

A nA

000,100≤n

)( 3nO� 행렬곱셈을 으로한다고하면, 곱셈 1000번도간신히하겠는걸..

� Strassen알고리즘을써도달라지는건별로없다

)(nO

Page 28: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� Key Observation:

Fast Matrix Exponentiation

nnn AAA ⋅=2

nn AAA 212⋅=

+

� 최대 번의곱셈! 가뿐하다..)(lgnO

Matrix pow(constconstconstconst Matrix& A, intintintint n) {ifififif(n == 0) returnreturnreturnreturn identity();ifififif(n % 2) returnreturnreturnreturn A * pow(A, n-1);Matrix B = pow(A, n/2);returnreturnreturnreturn B*B;

}

Page 29: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 어떤시스템의패스워드는 A글자이상, B글자이하로구성되어야하며, n종류의문자를사용할수있다.

� 예) A = 4, B = 4, n = 10 이면 0000 ~ 9999

Number of Passwords

� 예) A = 4, B = 8, n = 36 이면알파벳소문자 + 숫자

� Given and , return the number of possible passwords (mod 1000000007)

322, ≤BA 128≤n

Page 30: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 실제답의개수를구하기란매우쉽다

Number of Passwords

mnnnnmnf ++++= L32),(

)1,(),( −−= AnfBnfS

� 을계산하는데 시간이걸리면말짱황…

� 어떻게풀까요?

),( mnf )(mO

Page 31: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 또다시, 절반으로나눕니다

Number of Passwords

8765432)8,( nnnnnnnnnf +++++++=

)()( 8765432 nnnnnnnn +++++++=

)()( 43214432 nnnnnnnnn +++++++=

� 따라서,

12)2,()12,( ++=+

ananfanf

)1(),()2,( ananfanf +⋅=

)()( 43214432 nnnnnnnnn +++++++=

)1)(( 4432 nnnnn ++++=

Page 32: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

하노이의 탑

classclassclassclass HanoiTowers {publicpublicpublicpublic:

intintintint getDiscCount() constconstconstconst;intintintint moveDisc(intintintint fromTower, intintintint toTower);

};

voidvoidvoidvoid solveHanoi(HanoiTowers& tower) {// solve here

� 어떻게옮길까?

// solve here}

Page 33: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 가장큰원판과나머지 n-1개의원판으로나눠서생각해보자� 가장큰원판이움직일때는, 다른 n-1개의원판은다른하나에순서대로모여있어야한다

하노이의 탑

Page 34: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 재귀호출을이용해 n-1 개와마지막한개로나눈다

하노이의 탑

// move top n discs from A to Bvoidvoidvoidvoid solveHanoi(HanoiTowers& tower, intintintint A = 0, intintintint B = 2, intintintint n = -1) {

ifififif(n == 0) returnreturnreturnreturn;ifififif(n == -1) n = tower.getDiscCount();ifififif(n == -1) n = tower.getDiscCount();intintintint C = (0+1+2) - A - B;solveHanoi(tower, A, C, n-1); // move n-1 discs to a tem towertower.moveDisc(A, B); // move the largest discsolveHanoi(tower, C, B, n-1); // move n-1 discs to the target

tower }

Page 35: im4u 봄방학캠프 DAY 2; Discrete OptimizationProblems Part Itheyearlyprophet.com/slide02.pdf · Microsoft PowerPoint - slide02.pptx Author: Administrator Created Date: 2/15/2009

� 이산최적화문제를푸는방법들

� 완전탐색� 완전탐색으로풀수있는지를판단하기가어렵다

� 가장간단한방법으로시작해서문제에대한직관을

Lessons Learned

� 가장간단한방법으로시작해서문제에대한직관을얻기

� 분할정복� 익숙해지면어떻게나눠야할지패턴이보이기시작