SlideShare a Scribd company logo
1 of 40
Advanced Algorithms
Exercise 3

Group 2
陳右緯、楊翔雲、蔡宗衛、BINAYA KAR、林淑慧
2014/1/3

Q1 Q8

1
Q1
• Given a 2-dimensional n × n matrix of 0/1
integers, design a linear time algorithm to find
a subrectangle with the largest size such that
all the elements in the sub-rectangle are equal
to 1.

2014/1/3

Q1 Q8

2
Q1
Keyword
• Largest Empty Rectangle
• Maximum rectangle area

2014/1/3

Q1 Q8

3
Q1 – efficient algorithm(1)
• 一個最大矩形必然存在壁(邊界上)
• 窮舉一點面對這個壁
• 利用 DP 性質維護對壁距離
以及到壁能拓展的最大寬

•

Picture from http://www.csie.ntnu.edu.tw/~u91029/LargestEmptyRectangle.html#3

2014/1/3

Q1 Q8

4
Q1 – efficient algorithm(1)
• 依序考慮每一行

正解呢 ?

2014/1/3

Q1 Q8

5
Q1 – efficient algorithm(1)
•
•
•
•
•

l[i][j] 表示 (x, y) 向左伸展的最大寬度
r[i][j] 表示 (x, y) 向右伸展的最大寬度
h[i][j] 表示 (x, y) 向下伸展的最大高度
wl[i][j] 表示 (x, y) 最大高度下的最左寬度
wr[i][j] 表示 (x, y) 最大高度下的最右寬度

2014/1/3

Q1 Q8

6
Q1 – efficient algorithm(1)
• l[i][j] express that the size of (x, y) expand
maximum left columns
• r[i][j] express that the size of (x, y) expand
maximum right columns
• h[i][j] express that the height of (x, y) expand
maximum rows (backword)
• wl[i][j] the maximum left width when it has
max height
• wr[i][j] the maximum right width when it has
max height
2014/1/3

Q1 Q8

7
Q1 – efficient algorithm(1)
l [ i ][ j ]

r [ i ][ j ]

h [ i ][ j ]
wl [ i ][ j ]

wr [ i ][ j ]

l [ i ][ j

1,  if  
A[i][j] is empty.

1]

0 ,   otherwise
r [ i ][ j

1,  if  
A[i][j] is empty.

1]

0 ,   otherwise

h [i

1][ j ]

1,  if  
A[i][j] is empty.

0 ,   otherwise
min( wl [ i 1][ j ] 1,   l [ i ][ j ]),   if  
A[i][j] is empty.
0 ,   otherwise

min( wr [ i

area [ i ][ j ]

1][ j ]

1,   r [ i ][ j ]),   if  
A[i][j] is empty.
0 ,   otherwise

( h [ i ][ j ])( wl [ i ][ j ]

wr [ i ][ j ]

1)  if  
A[i][j] is empty.

0 ,   otherwise

Maximum empty area = max(area[i][j]), (0 ≦ i, j < n )
2014/1/3

Q1 Q8

8
Q1 – efficient algorithm(1)
area [ i ][ j ]

( h [ i ][ j ])( wl [ i ][ j ]

wr [ i ][ j ]

1)  if  
A[i][j] is empty.

0 ,   otherwise

• Final result = max(area[i][j]), (0 < i, j ≦ n)

2014/1/3

Q1 Q8

9
Q1 – efficient algorithm(1)
int wl[205] = {}, wr[205] = {};
int r[205] = {}, l[205] = {}, h[205] = {};
int sum;
int ret = 0;
for(i = 0; i < n; i++) {
for(j = 0, sum = 0; j < m; j++) {
if(g[i][j] == 0)
sum = 0;
sum = wl[j] = sum + g[i][j];
}
for(j = m-1, sum = 0; j >= 0; j--) {
if(g[i][j] == 0)
sum = 0;
sum = wr[j] = sum + g[i][j];
}
for(j = 0; j < m; j++) {
if(g[i][j] == 0)
h[j] = 0;
else
h[j]++;
}
for(j = 0; j < m; j++) {
if(l[j] == 0)
l[j] = wl[j];
else
l[j] = min(l[j], wl[j]);
if(r[j] == 0)
r[j] = wr[j];
else
r[j] = min(r[j], wr[j]);
}
for(j = 0; j < m; j++)
ret = max(ret, (l[j]+r[j]-1)*h[j]);
2014/1/3
Q1 Q8
}

10
Q1 – efficient algorithm(2)
• 轉換問題,記錄連續單側最大值

•

Picture from http://www.drdobbs.com/database/the-maximal-rectangle-problem/184410529

2014/1/3

Q1 Q8

11
Q1 – efficient algorithm(2)
• New Problem : Largest Rectangle in a Histogram

• Histogram : (@*#&U(@*U(!*
•

Picture from http://poj.org/problem?id=2559

2014/1/3

Q1 Q8

12
Q1 – efficient algorithm(2)
• 單調堆 ? 單調棧 ? Monotone stack ?
尚且還沒有這個詞
• 維護一個由底至頂元素由小至大 的 stack

2014/1/3

Q1 Q8

13
Q1 – efficient algorithm(2)
int solve(int n, int h[]) {
int ret = 0;
int i, height;
stack< pair<int, int> > stk;// <height, position>
pair<int, int> e;
stk.push(make_pair(-1, 0));
h[n] = 0;// visual height.
for(i = 0; i <= n; i++) {
height = h[i];
e = make_pair(height, i);
while(height < stk.top().first) {
e = stk.top(), stk.pop();
ret = max(ret, (i - e.second)*e.first);
}
if(height > stk.top().first)
stk.push(make_pair(height, e.second));
}
return ret;
}
2014/1/3

Q1 Q8

14
Q1 – more …
• Online Judge
POJ 2559 - Largest Rectangle in a Histogram
ZJ b123 最大矩形 (Area)
• More extended problem …
maximum rectangle with all same element.
O(NM)
maximum rectangle which
|maximum element – minimum element| < L

O(NML)
2014/1/3

Q1 Q8

15
Q2
• Improve the space utilization in the algorithm
of solving the 0/1 knapsack (sum-of-subsets)
problem discussed in the class.

• 優化 0/1 背包問題的記憶體空間

2014/1/3

Q1 Q8

16
Q2
• 額外維護一個新增數值的 queue
• 當 queue.top() 小於當前嘗試的值時,將前
繼.next 指向它,並且 pop()

2014/1/3

Q1 Q8

17
Q2 – efficient algorithm
Queue<int> Q;
Node *head = new Node(0, NULL);
for(i = 0; i < n; i++) {
for(p = q = head; p != NULL; p = (q = p)->next) {
while(Q.front() < p->val)
q = q->next = new Node(Q.front, q->next);
Q.pop();
while(Q.front() == p->val)
Q.pop();
val = p->val + s[i];
Q.push(val);
}
}

2014/1/3

Q1 Q8

18
Q3 – a
• Solve each of the following variations of the
0/1 knapsack problem (sum-of-subsets):
Pack items of given sizes in a given-sized
knapsack fully, but there is an unlimited
supply (無限量供應) of each item.
• 固定大小,無限量供應

2014/1/3

Q1 Q8

19
Q3 – efficient algorithm(a)
f[] : f[0] = 1
For(i = 0; i < n; i++)
For(j = s[i]; j <= K; j++)
f[j] |= f[j-s[i]];

•
•
•
•

Time Complexity : O(nK)
Space Complexity : O(n)
f[i][j] = f[i][j] | f[i-1][j-s[i]]
可以利用 Q2 的答案進行優化

2014/1/3

Q1 Q8

20
Q3 – b
• The assumptions are the same as in v1 (n
items, unlimited supply, fixed-sized knapsack),
but now each item has an associated value.
Design an algorithm to find how to pack the
knapsack fully, such that the items in it have
the maximal value among all possible ways to
pack the knapsack.
• 計算背包容量的方法數
2014/1/3

Q1 Q8

21
Q3 – efficient algorithm(b)
f[] : f[0] = 1
For(i = 0; i < n; i++)
For(j = s[i]; j <= K; j++)
f[j] += f[j-s[i]];

• Time Complexity : O(nK)
• Space Complexity : O(n)
• f[i][j] = f[i][j] + f[i-1][j-s[i]]

• 可以利用 Q2 的答案進行優化
2014/1/3

Q1 Q8

22
Q3 – c
• The assumptions are the same as in v2 (n
items with sizes and values, unlimited supply,
fixed-sized knapsack, and the goal of
maximizing the value), but now we are not
restricted to filling the knapsack exactly to
capacity. We are interested only in maximizing
the total value, subject to the constraint that
there is enough room for the chosen items in
the knapsack.
2014/1/3

Q1 Q8

23
Q3 – efficient algorithm(c)
f[] : f[0] = 0
For(i = 0; i < n; i++)
For(j = s[i]; j <= K; j++)
f[j] = max(f[j], f[j-s[i]]+v[i]);

• Time Complexity : O(nK)
• Space Complexity : O(n)
• f[i][j] = max(f[i-1][j], f[i][j], f[i-1][j-s[i]]+v[i])

• 可以利用 Q2 的答案進行優化
2014/1/3

Q1 Q8

24
Q3 – more
• limited supply, fixed-sized
O(NK)
POJ 1742 - Coins
UVa 711 - Dividing up
• group item choose one with weight and value
O(NKG)
ex. ZJ d682 TOI2010 第三題:職棒簽約問題

2014/1/3

Q1 Q8

25
Q3 – tricky
• 分給 n < 6 個人等值

UVa 1163 - The Right Tip
with another core algorithm.

2014/1/3

Q1 Q8

26
Q4
• Design an algoritm to solve Problem 10482
“The Candayman Can” in the web site:
• http://acm.uva.es/problemset/

• 將物品分成三堆,最大堆與最小堆差最小
為何 ?

2014/1/3

Q1 Q8

27
Q4
• 紀錄兩堆資訊,剩餘一堆不用計算個數
• dp[i][j][k] :
討論前 i 個物品,其中一堆為 j 另一堆為 k

• dp[i][j][k] = dp[i-1][j-s[i]][k] | dp[i-1][j][ks[i]] | dp[i-1][j][k]

2014/1/3

Q1 Q8

28
Q5
• Design an algoritm to solve Problem 10261
“Ferry Loading” in the web site:
• http://acm.uva.es/problemset/

• 依序放入 n 台車於渡口左側或右側,如果
不能放時,則後面的所有車都不能放。
渡口長 L,每台車長度 x。

2014/1/3

Q1 Q8

29
Q5
• 維護其中一側即可,與 Q4 相同。
• dp[i][j] : 表示前 i 台車,左側長 j。
sum = sigma(x[i])
• dp[i][j] = dp[i-1][j-x[i]] |
(sum-j <= L && dp[i-1][j])

2014/1/3

Q1 Q8

30
Q6
• Solve the even partition problem: Given a list
of n positive integers, partition the list into
two sublists, each of size floor(n/2) or ceil(n/2),
such that the difference between the sums of
the integers in the two sublists is minimized.
• 0/1 背包問題

2014/1/3

Q1 Q8

31
Q7
• Given a set of n sticks of various lengths,
design an algorithm to determine if it is
possible to join them end-to-end to form a
square.
• Uva 10364 - Square

2014/1/3

Q1 Q8

32
Q7
• Uva 10364 - Square
↑
由於狀態過大,只能使用 brute force + cut

• 否則使用 dp[i][1st][2nd][3rd]
Let 1st <= 2nd <= 3rd

2014/1/3

Q1 Q8

33
Q8
• Suppose you have one machine and a set of n jobs a1, a2, … ,
an to process on that machine. Each job aj has a processing
time tj, a profit pj, and a deadline dj. The machine can process
only one job at a time, and job aj must run uninterruptedly for
tj consecutive time units. If job aj is completed by its deadline
dj, you receive a profit pj, but if it is completed after its
deadline, you receive a profit of 0. Give an algorithm to find
the schedule that obtains the maximum amount of profit. For
each of the following special case, is it possible to find a more
efficient algorithm (comparing to the general case.) ?
• a) Each job has the same processing time.
• b) Each job has the same profit.
• c) Each job has the same deadline.
2014/1/3

Q1 Q8

34
Q8
• a) P 工作時間相同
最大利益一定先做,Greedy + disjoint set O(nlogn)
從最大利益開始挑,盡可能將它靠近到 deadline。
對於 processing time > 1,則將 deadline in
[processing time, processing time*2] 之間的設定為
deadline = processing time
• b) P 工作利益相同
烏龜塔,前一份作業討論過。
• c) NPC 截止日期相同
最大價值背包問題。
• 當三者都不同時,根據截止日期排序
dp[i][j] 表示討論前 i 個工作,截止日期為 j 的最大獲益。
2014/1/3

Q1 Q8

35
Q9
• Given a weighted directed acyclic graph (DAG;
a directed graph is acyclic if it contains no
directed cycles), and a pair of vertices u and v,
design an algorithm to find a longest and a
shortest path from u to v. Here, the length of a
path is defined as the sum of weights of edges
in the path.

2014/1/3

Q1 Q8

36
Q9
• 類似拓樸排序的 DP
• dp[v] = max(dp[u] + wuv)

• O(V+E)

2014/1/3

Q1 Q8

37
Q10
• Given a weighted directed graph G=(V, E),
design an algorithm to detect if G contains a
negative cycle. Moreover, if G contains no
negative cycles, design an algorithm to find a
cycle in G of minimum weight.

2014/1/3

Q1 Q8

38
Q10
• Floyd - Warshell algorithm
• Let g[i][i] = infinity large
Floyd - Warshell algorithm O(V3)
find minimum weight cycle
• Detect negative cycle by Bellman-ford
algorithm or SPFA(Shortest Path Faster
Algorithm with SLF and LLL strategy)
2014/1/3

Q1 Q8

39
Q10 - more
• Minimum Mean Cycle Problem

2014/1/3

Q1 Q8

40

More Related Content

What's hot

Principal component analysis and matrix factorizations for learning (part 3) ...
Principal component analysis and matrix factorizations for learning (part 3) ...Principal component analysis and matrix factorizations for learning (part 3) ...
Principal component analysis and matrix factorizations for learning (part 3) ...
zukun
 
ICML2013読み会 Large-Scale Learning with Less RAM via Randomization
ICML2013読み会 Large-Scale Learning with Less RAM via RandomizationICML2013読み会 Large-Scale Learning with Less RAM via Randomization
ICML2013読み会 Large-Scale Learning with Less RAM via Randomization
Hidekazu Oiwa
 
論文紹介 Fast imagetagging
論文紹介 Fast imagetagging論文紹介 Fast imagetagging
論文紹介 Fast imagetagging
Takashi Abe
 
SPU Optimizations-part 1
SPU Optimizations-part 1SPU Optimizations-part 1
SPU Optimizations-part 1
Naughty Dog
 

What's hot (20)

Neural Processes Family
Neural Processes FamilyNeural Processes Family
Neural Processes Family
 
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
 
Principal component analysis and matrix factorizations for learning (part 3) ...
Principal component analysis and matrix factorizations for learning (part 3) ...Principal component analysis and matrix factorizations for learning (part 3) ...
Principal component analysis and matrix factorizations for learning (part 3) ...
 
Complex and Social Network Analysis in Python
Complex and Social Network Analysis in PythonComplex and Social Network Analysis in Python
Complex and Social Network Analysis in Python
 
NIPS2017 Few-shot Learning and Graph Convolution
NIPS2017 Few-shot Learning and Graph ConvolutionNIPS2017 Few-shot Learning and Graph Convolution
NIPS2017 Few-shot Learning and Graph Convolution
 
Conditional neural processes
Conditional neural processesConditional neural processes
Conditional neural processes
 
ICML2013読み会 Large-Scale Learning with Less RAM via Randomization
ICML2013読み会 Large-Scale Learning with Less RAM via RandomizationICML2013読み会 Large-Scale Learning with Less RAM via Randomization
ICML2013読み会 Large-Scale Learning with Less RAM via Randomization
 
Overlap Layout Consensus assembly
Overlap Layout Consensus assemblyOverlap Layout Consensus assembly
Overlap Layout Consensus assembly
 
The Uncertain Enterprise
The Uncertain EnterpriseThe Uncertain Enterprise
The Uncertain Enterprise
 
Neural Processes
Neural ProcessesNeural Processes
Neural Processes
 
Data Structures- Hashing
Data Structures- Hashing Data Structures- Hashing
Data Structures- Hashing
 
InfoGAN : Interpretable Representation Learning by Information Maximizing Gen...
InfoGAN : Interpretable Representation Learning by Information Maximizing Gen...InfoGAN : Interpretable Representation Learning by Information Maximizing Gen...
InfoGAN : Interpretable Representation Learning by Information Maximizing Gen...
 
The International Journal of Engineering and Science (IJES)
The International Journal of Engineering and Science (IJES)The International Journal of Engineering and Science (IJES)
The International Journal of Engineering and Science (IJES)
 
Prim algorithm
Prim algorithmPrim algorithm
Prim algorithm
 
論文紹介 Fast imagetagging
論文紹介 Fast imagetagging論文紹介 Fast imagetagging
論文紹介 Fast imagetagging
 
Codes and Isogenies
Codes and IsogeniesCodes and Isogenies
Codes and Isogenies
 
PostgreSQL: Approximated searches
PostgreSQL: Approximated searchesPostgreSQL: Approximated searches
PostgreSQL: Approximated searches
 
Profiling in Python
Profiling in PythonProfiling in Python
Profiling in Python
 
Predicting organic reaction outcomes with weisfeiler lehman network
Predicting organic reaction outcomes with weisfeiler lehman networkPredicting organic reaction outcomes with weisfeiler lehman network
Predicting organic reaction outcomes with weisfeiler lehman network
 
SPU Optimizations-part 1
SPU Optimizations-part 1SPU Optimizations-part 1
SPU Optimizations-part 1
 

Similar to Aaex3 group2

Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracing
zukun
 
Data Structure & Algorithms - Mathematical
Data Structure & Algorithms - MathematicalData Structure & Algorithms - Mathematical
Data Structure & Algorithms - Mathematical
babuk110
 
Ch-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsCh-2 final exam documet compler design elements
Ch-2 final exam documet compler design elements
MAHERMOHAMED27
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
hodcsencet
 

Similar to Aaex3 group2 (20)

Chapter One.pdf
Chapter One.pdfChapter One.pdf
Chapter One.pdf
 
Alex1 group2
Alex1 group2Alex1 group2
Alex1 group2
 
Aaex2 group2
Aaex2 group2Aaex2 group2
Aaex2 group2
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
unit-4-dynamic programming
unit-4-dynamic programmingunit-4-dynamic programming
unit-4-dynamic programming
 
AA_Unit 1_part-I.pptx
AA_Unit 1_part-I.pptxAA_Unit 1_part-I.pptx
AA_Unit 1_part-I.pptx
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
 
Week2-stacks-queues.pptx
Week2-stacks-queues.pptxWeek2-stacks-queues.pptx
Week2-stacks-queues.pptx
 
DAA Notes.pdf
DAA Notes.pdfDAA Notes.pdf
DAA Notes.pdf
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracing
 
Data Structure & Algorithms - Mathematical
Data Structure & Algorithms - MathematicalData Structure & Algorithms - Mathematical
Data Structure & Algorithms - Mathematical
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Ch-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsCh-2 final exam documet compler design elements
Ch-2 final exam documet compler design elements
 
Asymptotic Notations.pptx
Asymptotic Notations.pptxAsymptotic Notations.pptx
Asymptotic Notations.pptx
 
algorithmanalysis and effciency.pptx
algorithmanalysis and effciency.pptxalgorithmanalysis and effciency.pptx
algorithmanalysis and effciency.pptx
 
DynamicProgramming.ppt
DynamicProgramming.pptDynamicProgramming.ppt
DynamicProgramming.ppt
 
Recursive algorithms
Recursive algorithmsRecursive algorithms
Recursive algorithms
 
data structures and algorithms Unit 4
data structures and algorithms Unit 4data structures and algorithms Unit 4
data structures and algorithms Unit 4
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 

More from Shiang-Yun Yang (12)

User interface
User interfaceUser interface
User interface
 
Polarity analysis for sentiment classification
Polarity analysis for sentiment classificationPolarity analysis for sentiment classification
Polarity analysis for sentiment classification
 
文明的進程第十組
文明的進程第十組文明的進程第十組
文明的進程第十組
 
計算幾何論文報告 Minimum local disk cover sets
計算幾何論文報告 Minimum local disk cover sets計算幾何論文報告 Minimum local disk cover sets
計算幾何論文報告 Minimum local disk cover sets
 
N grams as linguistic features
N grams as linguistic featuresN grams as linguistic features
N grams as linguistic features
 
軍事報告 電磁砲
軍事報告 電磁砲軍事報告 電磁砲
軍事報告 電磁砲
 
第二十組福斯汽車
第二十組福斯汽車第二十組福斯汽車
第二十組福斯汽車
 
敏捷簡報
敏捷簡報敏捷簡報
敏捷簡報
 
計算型智慧論文報告 Building optimal regression tree ...
計算型智慧論文報告 Building optimal regression tree ...計算型智慧論文報告 Building optimal regression tree ...
計算型智慧論文報告 Building optimal regression tree ...
 
Rpg 角色扮演遊戲 – 初探
Rpg 角色扮演遊戲 – 初探Rpg 角色扮演遊戲 – 初探
Rpg 角色扮演遊戲 – 初探
 
Aaex6 group2(中英夾雜)
Aaex6 group2(中英夾雜)Aaex6 group2(中英夾雜)
Aaex6 group2(中英夾雜)
 
通識報告
通識報告通識報告
通識報告
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Aaex3 group2

  • 1. Advanced Algorithms Exercise 3 Group 2 陳右緯、楊翔雲、蔡宗衛、BINAYA KAR、林淑慧 2014/1/3 Q1 Q8 1
  • 2. Q1 • Given a 2-dimensional n × n matrix of 0/1 integers, design a linear time algorithm to find a subrectangle with the largest size such that all the elements in the sub-rectangle are equal to 1. 2014/1/3 Q1 Q8 2
  • 3. Q1 Keyword • Largest Empty Rectangle • Maximum rectangle area 2014/1/3 Q1 Q8 3
  • 4. Q1 – efficient algorithm(1) • 一個最大矩形必然存在壁(邊界上) • 窮舉一點面對這個壁 • 利用 DP 性質維護對壁距離 以及到壁能拓展的最大寬 • Picture from http://www.csie.ntnu.edu.tw/~u91029/LargestEmptyRectangle.html#3 2014/1/3 Q1 Q8 4
  • 5. Q1 – efficient algorithm(1) • 依序考慮每一行 正解呢 ? 2014/1/3 Q1 Q8 5
  • 6. Q1 – efficient algorithm(1) • • • • • l[i][j] 表示 (x, y) 向左伸展的最大寬度 r[i][j] 表示 (x, y) 向右伸展的最大寬度 h[i][j] 表示 (x, y) 向下伸展的最大高度 wl[i][j] 表示 (x, y) 最大高度下的最左寬度 wr[i][j] 表示 (x, y) 最大高度下的最右寬度 2014/1/3 Q1 Q8 6
  • 7. Q1 – efficient algorithm(1) • l[i][j] express that the size of (x, y) expand maximum left columns • r[i][j] express that the size of (x, y) expand maximum right columns • h[i][j] express that the height of (x, y) expand maximum rows (backword) • wl[i][j] the maximum left width when it has max height • wr[i][j] the maximum right width when it has max height 2014/1/3 Q1 Q8 7
  • 8. Q1 – efficient algorithm(1) l [ i ][ j ] r [ i ][ j ] h [ i ][ j ] wl [ i ][ j ] wr [ i ][ j ] l [ i ][ j 1,  if   A[i][j] is empty. 1] 0 ,   otherwise r [ i ][ j 1,  if   A[i][j] is empty. 1] 0 ,   otherwise h [i 1][ j ] 1,  if   A[i][j] is empty. 0 ,   otherwise min( wl [ i 1][ j ] 1,   l [ i ][ j ]),   if   A[i][j] is empty. 0 ,   otherwise min( wr [ i area [ i ][ j ] 1][ j ] 1,   r [ i ][ j ]),   if   A[i][j] is empty. 0 ,   otherwise ( h [ i ][ j ])( wl [ i ][ j ] wr [ i ][ j ] 1)  if   A[i][j] is empty. 0 ,   otherwise Maximum empty area = max(area[i][j]), (0 ≦ i, j < n ) 2014/1/3 Q1 Q8 8
  • 9. Q1 – efficient algorithm(1) area [ i ][ j ] ( h [ i ][ j ])( wl [ i ][ j ] wr [ i ][ j ] 1)  if   A[i][j] is empty. 0 ,   otherwise • Final result = max(area[i][j]), (0 < i, j ≦ n) 2014/1/3 Q1 Q8 9
  • 10. Q1 – efficient algorithm(1) int wl[205] = {}, wr[205] = {}; int r[205] = {}, l[205] = {}, h[205] = {}; int sum; int ret = 0; for(i = 0; i < n; i++) { for(j = 0, sum = 0; j < m; j++) { if(g[i][j] == 0) sum = 0; sum = wl[j] = sum + g[i][j]; } for(j = m-1, sum = 0; j >= 0; j--) { if(g[i][j] == 0) sum = 0; sum = wr[j] = sum + g[i][j]; } for(j = 0; j < m; j++) { if(g[i][j] == 0) h[j] = 0; else h[j]++; } for(j = 0; j < m; j++) { if(l[j] == 0) l[j] = wl[j]; else l[j] = min(l[j], wl[j]); if(r[j] == 0) r[j] = wr[j]; else r[j] = min(r[j], wr[j]); } for(j = 0; j < m; j++) ret = max(ret, (l[j]+r[j]-1)*h[j]); 2014/1/3 Q1 Q8 } 10
  • 11. Q1 – efficient algorithm(2) • 轉換問題,記錄連續單側最大值 • Picture from http://www.drdobbs.com/database/the-maximal-rectangle-problem/184410529 2014/1/3 Q1 Q8 11
  • 12. Q1 – efficient algorithm(2) • New Problem : Largest Rectangle in a Histogram • Histogram : (@*#&U(@*U(!* • Picture from http://poj.org/problem?id=2559 2014/1/3 Q1 Q8 12
  • 13. Q1 – efficient algorithm(2) • 單調堆 ? 單調棧 ? Monotone stack ? 尚且還沒有這個詞 • 維護一個由底至頂元素由小至大 的 stack 2014/1/3 Q1 Q8 13
  • 14. Q1 – efficient algorithm(2) int solve(int n, int h[]) { int ret = 0; int i, height; stack< pair<int, int> > stk;// <height, position> pair<int, int> e; stk.push(make_pair(-1, 0)); h[n] = 0;// visual height. for(i = 0; i <= n; i++) { height = h[i]; e = make_pair(height, i); while(height < stk.top().first) { e = stk.top(), stk.pop(); ret = max(ret, (i - e.second)*e.first); } if(height > stk.top().first) stk.push(make_pair(height, e.second)); } return ret; } 2014/1/3 Q1 Q8 14
  • 15. Q1 – more … • Online Judge POJ 2559 - Largest Rectangle in a Histogram ZJ b123 最大矩形 (Area) • More extended problem … maximum rectangle with all same element. O(NM) maximum rectangle which |maximum element – minimum element| < L O(NML) 2014/1/3 Q1 Q8 15
  • 16. Q2 • Improve the space utilization in the algorithm of solving the 0/1 knapsack (sum-of-subsets) problem discussed in the class. • 優化 0/1 背包問題的記憶體空間 2014/1/3 Q1 Q8 16
  • 17. Q2 • 額外維護一個新增數值的 queue • 當 queue.top() 小於當前嘗試的值時,將前 繼.next 指向它,並且 pop() 2014/1/3 Q1 Q8 17
  • 18. Q2 – efficient algorithm Queue<int> Q; Node *head = new Node(0, NULL); for(i = 0; i < n; i++) { for(p = q = head; p != NULL; p = (q = p)->next) { while(Q.front() < p->val) q = q->next = new Node(Q.front, q->next); Q.pop(); while(Q.front() == p->val) Q.pop(); val = p->val + s[i]; Q.push(val); } } 2014/1/3 Q1 Q8 18
  • 19. Q3 – a • Solve each of the following variations of the 0/1 knapsack problem (sum-of-subsets): Pack items of given sizes in a given-sized knapsack fully, but there is an unlimited supply (無限量供應) of each item. • 固定大小,無限量供應 2014/1/3 Q1 Q8 19
  • 20. Q3 – efficient algorithm(a) f[] : f[0] = 1 For(i = 0; i < n; i++) For(j = s[i]; j <= K; j++) f[j] |= f[j-s[i]]; • • • • Time Complexity : O(nK) Space Complexity : O(n) f[i][j] = f[i][j] | f[i-1][j-s[i]] 可以利用 Q2 的答案進行優化 2014/1/3 Q1 Q8 20
  • 21. Q3 – b • The assumptions are the same as in v1 (n items, unlimited supply, fixed-sized knapsack), but now each item has an associated value. Design an algorithm to find how to pack the knapsack fully, such that the items in it have the maximal value among all possible ways to pack the knapsack. • 計算背包容量的方法數 2014/1/3 Q1 Q8 21
  • 22. Q3 – efficient algorithm(b) f[] : f[0] = 1 For(i = 0; i < n; i++) For(j = s[i]; j <= K; j++) f[j] += f[j-s[i]]; • Time Complexity : O(nK) • Space Complexity : O(n) • f[i][j] = f[i][j] + f[i-1][j-s[i]] • 可以利用 Q2 的答案進行優化 2014/1/3 Q1 Q8 22
  • 23. Q3 – c • The assumptions are the same as in v2 (n items with sizes and values, unlimited supply, fixed-sized knapsack, and the goal of maximizing the value), but now we are not restricted to filling the knapsack exactly to capacity. We are interested only in maximizing the total value, subject to the constraint that there is enough room for the chosen items in the knapsack. 2014/1/3 Q1 Q8 23
  • 24. Q3 – efficient algorithm(c) f[] : f[0] = 0 For(i = 0; i < n; i++) For(j = s[i]; j <= K; j++) f[j] = max(f[j], f[j-s[i]]+v[i]); • Time Complexity : O(nK) • Space Complexity : O(n) • f[i][j] = max(f[i-1][j], f[i][j], f[i-1][j-s[i]]+v[i]) • 可以利用 Q2 的答案進行優化 2014/1/3 Q1 Q8 24
  • 25. Q3 – more • limited supply, fixed-sized O(NK) POJ 1742 - Coins UVa 711 - Dividing up • group item choose one with weight and value O(NKG) ex. ZJ d682 TOI2010 第三題:職棒簽約問題 2014/1/3 Q1 Q8 25
  • 26. Q3 – tricky • 分給 n < 6 個人等值 UVa 1163 - The Right Tip with another core algorithm. 2014/1/3 Q1 Q8 26
  • 27. Q4 • Design an algoritm to solve Problem 10482 “The Candayman Can” in the web site: • http://acm.uva.es/problemset/ • 將物品分成三堆,最大堆與最小堆差最小 為何 ? 2014/1/3 Q1 Q8 27
  • 28. Q4 • 紀錄兩堆資訊,剩餘一堆不用計算個數 • dp[i][j][k] : 討論前 i 個物品,其中一堆為 j 另一堆為 k • dp[i][j][k] = dp[i-1][j-s[i]][k] | dp[i-1][j][ks[i]] | dp[i-1][j][k] 2014/1/3 Q1 Q8 28
  • 29. Q5 • Design an algoritm to solve Problem 10261 “Ferry Loading” in the web site: • http://acm.uva.es/problemset/ • 依序放入 n 台車於渡口左側或右側,如果 不能放時,則後面的所有車都不能放。 渡口長 L,每台車長度 x。 2014/1/3 Q1 Q8 29
  • 30. Q5 • 維護其中一側即可,與 Q4 相同。 • dp[i][j] : 表示前 i 台車,左側長 j。 sum = sigma(x[i]) • dp[i][j] = dp[i-1][j-x[i]] | (sum-j <= L && dp[i-1][j]) 2014/1/3 Q1 Q8 30
  • 31. Q6 • Solve the even partition problem: Given a list of n positive integers, partition the list into two sublists, each of size floor(n/2) or ceil(n/2), such that the difference between the sums of the integers in the two sublists is minimized. • 0/1 背包問題 2014/1/3 Q1 Q8 31
  • 32. Q7 • Given a set of n sticks of various lengths, design an algorithm to determine if it is possible to join them end-to-end to form a square. • Uva 10364 - Square 2014/1/3 Q1 Q8 32
  • 33. Q7 • Uva 10364 - Square ↑ 由於狀態過大,只能使用 brute force + cut • 否則使用 dp[i][1st][2nd][3rd] Let 1st <= 2nd <= 3rd 2014/1/3 Q1 Q8 33
  • 34. Q8 • Suppose you have one machine and a set of n jobs a1, a2, … , an to process on that machine. Each job aj has a processing time tj, a profit pj, and a deadline dj. The machine can process only one job at a time, and job aj must run uninterruptedly for tj consecutive time units. If job aj is completed by its deadline dj, you receive a profit pj, but if it is completed after its deadline, you receive a profit of 0. Give an algorithm to find the schedule that obtains the maximum amount of profit. For each of the following special case, is it possible to find a more efficient algorithm (comparing to the general case.) ? • a) Each job has the same processing time. • b) Each job has the same profit. • c) Each job has the same deadline. 2014/1/3 Q1 Q8 34
  • 35. Q8 • a) P 工作時間相同 最大利益一定先做,Greedy + disjoint set O(nlogn) 從最大利益開始挑,盡可能將它靠近到 deadline。 對於 processing time > 1,則將 deadline in [processing time, processing time*2] 之間的設定為 deadline = processing time • b) P 工作利益相同 烏龜塔,前一份作業討論過。 • c) NPC 截止日期相同 最大價值背包問題。 • 當三者都不同時,根據截止日期排序 dp[i][j] 表示討論前 i 個工作,截止日期為 j 的最大獲益。 2014/1/3 Q1 Q8 35
  • 36. Q9 • Given a weighted directed acyclic graph (DAG; a directed graph is acyclic if it contains no directed cycles), and a pair of vertices u and v, design an algorithm to find a longest and a shortest path from u to v. Here, the length of a path is defined as the sum of weights of edges in the path. 2014/1/3 Q1 Q8 36
  • 37. Q9 • 類似拓樸排序的 DP • dp[v] = max(dp[u] + wuv) • O(V+E) 2014/1/3 Q1 Q8 37
  • 38. Q10 • Given a weighted directed graph G=(V, E), design an algorithm to detect if G contains a negative cycle. Moreover, if G contains no negative cycles, design an algorithm to find a cycle in G of minimum weight. 2014/1/3 Q1 Q8 38
  • 39. Q10 • Floyd - Warshell algorithm • Let g[i][i] = infinity large Floyd - Warshell algorithm O(V3) find minimum weight cycle • Detect negative cycle by Bellman-ford algorithm or SPFA(Shortest Path Faster Algorithm with SLF and LLL strategy) 2014/1/3 Q1 Q8 39
  • 40. Q10 - more • Minimum Mean Cycle Problem 2014/1/3 Q1 Q8 40