# HKOI 2005 Junior Q1 Pattern Matching ( 模式匹配 ). Question Given a target value (Sum of pattern P), find a sub-block with size equal to P having sum closest.

## Presentation on theme: "HKOI 2005 Junior Q1 Pattern Matching ( 模式匹配 ). Question Given a target value (Sum of pattern P), find a sub-block with size equal to P having sum closest."— Presentation transcript:

HKOI 2005 Junior Q1 Pattern Matching ( 模式匹配 )

Question Given a target value (Sum of pattern P), find a sub-block with size equal to P having sum closest to the target value

Partial Solution Use 4 For-loop to calculate the sum of each sub-block. For “Top” from 1 to (M – N + 1) For “Left” from 1 to (M – N + 1) Calculate Sum of Sub-Block(Top, Left) If Sum < MinSum Update Complexity: O(M²  N²)

Characteristic Two adjacent sub-block is overlap! Can we make use of this characteristic? Sum of Sub-Block(x, y) = Sum of Sub-Block(x – 1, y) - Sum of Column(1) of Sub-Block(x – 1, y) + Sum of Column(N) of Sub-Block(x, y) Improve a little bit only x-1, y x, y

Further Improvement Define a array SumFromTopLeft SumFromTopLeft(x, y) means the sum from Top-Left (1, 1) to (x, y) SumFromTopLeft(0, y) = 0 SumFromTopLeft(x, 0) = 0 SumFromTopLeft(x, y) = SumFromTopLeft(x, y - 1) + SumFromTopLeft(x - 1, y) - SumFromTopLeft(x - 1, y - 1) + PixelValue(x, y)

Con’t Sum of Sub-Block(x, y) x,y  M – N + 1 = SumFromTopLeft(x + N - 1, y + N - 1) - SumFromTopLeft(x, y + N - 1) - SumFromTopLeft(x + N - 1, y) + SumFromTopLeft(x, y) Complexity: O(M²)

Download ppt "HKOI 2005 Junior Q1 Pattern Matching ( 模式匹配 ). Question Given a target value (Sum of pattern P), find a sub-block with size equal to P having sum closest."

Similar presentations