aaex4 group2(中英夾雜)

49
Advanced Algorithms Exercise 4 Group 2 陳陳陳 陳陳陳陳 陳陳陳陳 、、、 BINAYA KAR 陳陳陳 06/08/2022 1 Q1 Q8

Upload: shiang-yun-yang

Post on 11-May-2015

268 views

Category:

Documents


1 download

DESCRIPTION

除了第十三題外。

TRANSCRIPT

Page 1: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 1

Advanced AlgorithmsExercise 4

Group 2

陳右緯、楊翔雲、蔡宗衛、 BINAYA KAR 、林淑慧

Page 2: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 2

Q1

• For two points p and q in the plane, we say that p dominates q if both x and y coordinates of p are greater than that of q respectively. Given a set S of n points, the rank of a point p in S is the number of points in S dominated by p. We want to find the rank of every point in S. A naïve algorithm needs O(n^2) time. Design a faster algorithm for this problem.

Page 3: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 3

Q1 – efficient algorithm(1)

• Keyword : 2D rank finding problem• Solution 1 :

D&C strategy (implements by merge sort.)T(n) = 2*T(n/2) + O(n) = O(n logn)

• 實作細節:需要預處理排序 (presort)接著對 x 軸大小做切割,每次對切一半,合併時將 y 軸由小排到大,因此右側元素可以在 O(n) 增加新的 rank 值。因為已經保證左側 x 全小於右側元素,接著由於 y 已經單調排序,可以在 O(n) 時間內完成。

Page 4: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 4

Q1 – efficient algorithm(1)

• Keyword : 2D rank finding problem• Solution 1 :

D&C strategy (implements by merge sort.)

Page 5: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 5

Q1 – efficient algorithm(1)struct Pt {    int x, y, idx, r;    Pt(int a=0, int b=0, int c=0):        x(a), y(b), idx(c), r(0) {}    bool operator<(const Pt &a) const {        if(x != a.x)            return x < a.x;        return y > a.y;    }}; void DCmerge(int l, int m, int r) {    int idx1 = l, idx2 = m+1, top = 0;    int d = 0, i;    while(idx1 <= m && idx2 <= r) {        if(D[idx1].y < D[idx2].y)            X[top++] = D[idx1++], d++;        else            X[top++] = D[idx2++], X[top-1].r += d;    }    while(idx1 <= m)    X[top++] = D[idx1++];    while(idx2 <= r)    X[top++] = D[idx2++], X[top-1].r += d;    for(i = 0; i < top; i++)        D[l++] = X[i];}void DC(int l, int r) {    if(l >= r)    return ;    int m = (l+r)/2;    DC(l, m);    DC(m+1, r);    DCmerge(l, m, r);}

Page 6: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 6

Q1 – efficient algorithm(2)

• Keyword : 2D rank finding problem• Solution 2 :

Sweep line algorithm (implements by RMQ problem[binary indexed tree or segment tree]) - O(n logn)

• 對 x 大小排序,根據掃描線的精神,依序加點查找。

Y 0 1 2 3 4 5 6 7 8

C 1 12 1 1

Query prefix sum

Page 7: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 7

Q1 – efficient algorithm(2)

Func(Point[] p, int n) {sort(p, p+n); // sort by x value BinaryIndexedTree bit;for(i = 0; i < n; i++)

rank = bit.query(p[i].y-1); // O(log n)bit.add_singleVal(p[i].y, 1); // O(log n)show p[i] rank;

}

Page 8: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 8

Q2

• For two points p and q in the plane, we say that p dominates q if both x and y coordinates of p are greater than that of q respectively. Given a set S of n points, the rank of a point p in S is the number of points in S dominated by p. We want to find the rank of every point in S. A naïve algorithm needs O(n^2) time. Design a faster algorithm for this problem.

Page 9: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 9

Q2 – efficient algorithm

• Greedy strategy, knapsack capacity m.The problem lack the value of item.Item attribute (weight, value). How to get maximum value with limited capacity.

• solved by selection algorithm.• T(n) = T(n/2) + O(n) => T(n) = O(n).• 每個物品有價值和重量,背包有限重,而物品可以分數切

割 ( 只拿幾分之幾 ) ,問最多能帶走多少價值的物品。

Page 10: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 10

Q2 – efficient algorithm

• Step 1. find the median number by selection algorithm - O(n)

• Step 1.1 if n == 1 using greedy.• Step 2. calcuate the sum of the numbers(weight) which less

than median number. - O(n)• Step 3-1.

if sum > m, then get the numbers which less than median number. back step 1. else then select the numbers which less than median number.// get those item.valueget the number which larger then median nubmer. m -= n/2, back step 1.

Page 11: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 11

Q2 – efficient algorithm

• Step 1 : 利用 selection algorithm 找到所有物品價值的中位數 如果 n = 1 ,直接使用 greedy 。

• Step 2 : 把所有大於中位數的物品重量相加 = sumW• Step 3 :

如果 sumW < 背包限重,則把這些挑入背包中,更新新的限重,將剩餘物品繼續遞迴。反之,捨棄小於中位數的物品,將大於中位數的物品繼續遞迴。

Page 12: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 12

Q2 – efficient algorithmf(cap, items[]) {

if(items.size == 1)return items[0].value * (min(cap/items[0].w, 1));

midVal = median value of items[].valuesumW = 0, sumVal = 0for each e : items[]

if(e.value > midVal)sumW += e.w, sumVal += e.value;

if(sumW <= cap)return sumVal + f(cap-sumW,

items.sub(items.size/2));return f(cap, items.sub(0, items.size/2));

}

Page 13: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 13

Q2 – efficient algorithm

• Selection Algorithm C codeint selectionAlgorithm(int[], int, int, int);int medianOfMedians(int[], int, int);int selectionAlgorithm(int a[], int l, int r, int k) {/** * k = 0, 1, 2, ... * return k-th smallest value. */ if(r-l+1 <= 5) {// insert sort. int i, j, v; for(i = l+1; i <= r; i++) { v = a[i], j = i; while(j-1 >= l && a[j-1] > v) a[j] = a[j-1], j--; a[j] = v; } return l+k; } //printf("%d %d\n", l, r); int pivot = medianOfMedians(a, l, r); // partition begin. swap(a[l], a[pivot]); int i, j, t = a[l]; for(i = l, j = l+1; j <= r; j++) { if(a[j] <= t) i++, swap(a[i], a[j]); } swap(a[l], a[i]); // partition end. int position = I; if(position-l == k) return position; if(position-l < k) return selectionAlgorithm(a, position+1, r, k-(position-l+1)); else return selectionAlgorithm(a, l, position, k);}int medianOfMedians(int a[], int l, int r) { int numMedians = (r-l)/5; int i, subl, subr; int medianIdx; for(i = 0; i < numMedians; i++) { subl = l + i*5; subr = subl + 4; if(subr > r) subr = r; medianIdx = selectionAlgorithm(a, subl, subr, (subr-subl)/2); swap(a[l+i], a[medianIdx]); } //printf("median %d %d\n", l, r); return selectionAlgorithm(a, l, l+numMedians, numMedians/2);}

Page 14: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 14

Q3

• Assume there are n supposedly identical VLSI chips that are capable of testing each other. There is a test jig that can accommodate two chips at a time. When the jig is loaded, each chip tests the other and reports whether it is good or bad. A good chip always reports accurately whether the other chip is good or bad, but the answer of a bad chip cannot be trusted. Show that the good chips can be identified with O(n) pairwise tests, assuming that more than n/2 of the chips are good.

Page 15: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 15

Q3 – efficient algorithm

• tag : pigeonhole principle, math, D&C

| A says | B says | result-----------------------------------------| good | good | both good or both bad.------------------------------------------| X | X | least one is bad.------------------------------------------

Page 16: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 16

Q3 – efficient algorithm

• 1) n is even, • we make pair with random way.• by pigeonhole principle, at least one pair which are both good. only choose (good, good) pair, random leave one in this pair.

if there are k pairs which are both bad, there are >= k pairs which are both good.Then, we will get smaller scale problem.

• T(n) = T(n/2) + O(n)

Page 17: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 17

Q3 – efficient algorithm

• 2) n is odd.• when making pair, let 多餘挑出• 假使用 m 對呈現 (good, good) 其中會隨機挑出 p

個好的和 q 個壞的 , p + q = m• 2.1) if m is odd, 保證 p > q, 捨棄多餘的 , 繼續遞迴

• 2.2) if m is even, 保證加入多餘的 p > q, 繼續遞迴

Page 18: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 18

Q4

• Design an algorithm to find a longest (simple) path of a given digraph.

Page 19: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 19

Q4 – efficient algorithm

• Dynamic programming O(V+E)

Page 20: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 20

Q4 – efficient algorithmFunc(V, E) {

E’ = E inverse all edge.ret = 0for(i = 0; i < |V|; i++)

ret = max(ret, f(i, G(V, E’)));return ret;

}f(node, G) {

if(mem[node] != -1) return dp[node]dp[node] = 0mem[node] = 1;// donefor i = 0 to G[node].size()-1

dp[node] = max(dp[node], f(G[node].to, E)+G[node].weight);

return dp[node]}

Page 21: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 21

Q5

• Given a sequence S of n nonnegative numbers x1, x2, … ,xn, and an integer k, partition S into k or fewer consecutive subsequences such that the largest sum of these subsequences is minimized over all possible partitions.

• UVa 714 - Copying Books最大值最小化问题

Page 22: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 22

Q5 – efficient algorithm

• greedy with binary search – O(k log(maximum_guess))binary search result in [0, maximum_guess],use O(k) check yes or no.

• -----• Dynamic programming O(K^2 * S)

dp[k][s] = min(max(dp[i][s-1], sum[i+1][k])) // i < k

狀態定義:計算前 k 個已經劃分出 s 段的最小值。

Page 23: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 23

Q5 – efficient algorithm

int f(x[], n, k) {return Binary_search(0, 0xfffffff, cmp);function cmp(int limit) {

int sum = 0, seg = 0;for(i = 0; i < n; i++) {

if(sum + x[i] <= limit)sum += x[i];

elsesum = x[i], seg++;

}return seg <= k;

}}

Page 24: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 24

Q5 – efficient algorithm

// n = S, m = K.    DP[0][0] = 0;    for(i = 1; i <= m; i++) {        for(j = i; j <= n-(m-i); j++) {            DP[i][j] = 0xffffffffffffffLL;            for(k = i; k <= j; k++) {                if(DP[i][j] > max(sum[j]-sum[k-1], DP[i-1][k-1])) {                    best[i][j] = k-1;                    DP[i][j] = max(sum[j]-sum[k-1], DP[i-1][k-1]);                }            }        }    }

Page 25: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 25

Q6

• Solve Problem 10069 “Distinct Subsequences” in the ACM web site.

Page 26: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 26

Q6

• Dynamic programming - O(nm)if a[i] == b[j] dp[i][j] = dp[i-1][j] + dp[i-1][j-1]else //a[i] != b[j] dp[i][j] = dp[i-1][j]

• 定義 dp[i][j] : a 字串前 i 個字元討論中,已經匹配 b 字串的前 j 個的方法數為何。

Page 27: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 27

Q6 – make more concrete

• if a[i] == b[j] dp[i][j] = dp[i-1][j] + dp[i-1][j-1]

else //a[i] != b[j] dp[i][j] = dp[i-1][j]

babg … a[i] = g bag … b[j] = g{ba, ba, …} + g

… babg … bag …{bag, bag, …} + ε

… bab may have ‘bag’

Page 28: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 28

Q7

• Solve Problem 10271 “Chopsticks” in the ACM web site.

• 每個人分配三隻筷子,筷子有可能都不一樣長,問每個人拿到的最短兩隻筷子差平方的和最小為何。

Page 29: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 29

Q7

• sort length. 筷子長度由大到小排序

• dp[i][j] 表示前 i 支筷子分配給 j 個人• 遞迴時,要保證剩餘筷子有足夠的當做第 3 支筷

子可以分配給已經分配的 j 個人

• 基礎性質 : 保證 i-th 一定和 (i-1)-th 支筷子配。

xi, xi+1, xi+2, xi+3, ... // xi <= xi+1 <= xi+2 <= xi+3

• xi, xi+1, xi+2, xi+3 better than xi, xi+1, xi+2, xi+3

Page 30: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 30

Q8

• Solve problem “Printing neatly” in chapter 15 of the book [CLRS].

Page 31: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 31

Q8

• 有 n 個單詞,一行最多可放入 M 個字元的稿紙內,將單字印到稿紙後,稿紙的每一行結尾都會留下空白 O(n2)

• sum[i][j] = sigma(word_length[k]), i <= k <= j

• dp[i] 表示前 i 個單詞的最少留白個數• dp[i] = min(dp[j]+M-sum[j+1][i]-i+(j+1)),j < i & sum[j+1][i]+i–(j+1) <= M

Page 32: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 32

Q9

• Consider the activity-selection problem appears in p.41 of unit-5. Now, assume that each given activity is associated with a positive weight. Design an algorithm to find an independent subset of activities (activities that can be allowed to use the same resource) whose sum of weights is maximized.

Page 33: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 33

Q9

• activities each marked by a start time (si), finish time (fi), weight (wi)The problem is to select the maximum number of activities that can be performed by a single person or machine.if without weight, sort by finish time (fi) use greedy algorithm get the maximum activities can be allowed. with weight, use sweep line algorithmsort by start time (si)

• prev_max[fi] = max(prev_max[fi], prev_max[si] + wi, prev_max[fi-1])

Page 34: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 34

Q9

0 1 2 3 4 5 6 7 8 9 10

11

12

13

14

5

53

23

6

3 7

8

Maximum profit Before = 0

Maximum profit Before = 5

Page 35: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 35

Q10

• Given a list of n positive integers d1, d2, …, dn, we want to efficiently determine whether there exists a simple undirected graph whose nodes have degrees precisely d1, d2, …, dn. Design an algorithm to solve this problem.

• Tag : UVa 10720 - Graph Construction, greedy algorithm, Erdős–Gallai theorem

Page 36: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 36

Q10

• (1) greedy algorithm• step 1 : choose the maximum degrees node x• step 2 : let x links 前幾個大的點• step 3 : n--, back step 2• - O(n^2 logn)

Page 37: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 37

Q10

• (2) Erdős–Gallai theorem•

O(n logn)

Page 38: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 38

Q10int n, i, k;long long sum[1000005], d[1000005];int main() { while(scanf("%d", &n) == 1 && n) { sum[0] = 0; for(i = 0; i < n; i++) scanf("%lld", &d[i]); sort(d, d+n, greater<int>()); for(i = 0; i < n; i++) sum[i+1] = sum[i] + d[i]; long long left = 0, right; int ans = 0; if(sum[n]&1) ans = -1; else for(k = 0; k < n; k++) { left += d[k]; right = (long long)k * (k+1); int l = 0, r = n-1, m; while(l < r) { m = (l+r)>>1; if(d[m] <= k+1) r = m; else l = m+1; } if(l < k+1) right += sum[n] - sum[k+1]; else right += sum[n] - sum[l] + (long long)(k+1)*(l - k - 1); if(left > right) { ans = -1;break; } } if(ans) puts("Not possible"); else puts("Possible"); } return 0;}

Page 39: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 39

Q11

• Let G be a connected undirected graph. Given two spanning trees T and R of G, find the shortest sequence of trees T0, T1, …, Tk, such that T0 = T, Tk = R, and each tree differs from the previous one by an addition of one edge and a deletion of one edge.

Page 40: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 40

Q11

• Edge set ET ={et1, et2, … , etn-1}

• Edge set ER ={er1, er2, … , ern-1}

• The minimum step will …

(ET ∪ ER) \ ET \ER ={ed1, ed2, … , edk}

alternative choose different edge to transfer.

Minimum step = k/2

Page 41: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 41

Q12

• Given a weighted graph, find a spanning tree such that the maximal edge weight of the tree is minimized over all spanning trees.

Page 42: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 42

Q12

• 任何一個最小生成樹的算法都會符合。• Prim algorithm & Kruskal algorithm• 如果存在有更小的最大邊可以替換,不符

合當初最小生成樹的規則,劃分兩個集合 s – t ,最小權重的邊一定在最小生成樹上。

Page 43: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 43

Q13

• Let G be an undirected graph. Each edge e in G is assigned a probability pe, 0 < pe < 1, and a positive weight we. The length of a path is the sum of the weights of edges of the path, and the reliability of a path is the product of the probabilities of edges of the path. Given a value t, a path is said to be reliable if its reliability is not less than t. Design an efficient algorithm to find a reliable path from a given vertex u to another given vertex v with shortest length.

Page 44: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 44

Q13

• 找一條可靠度大於等於 t 的最短路徑。• 最短路徑下找最大可靠度 - 不難

可靠度為路徑上機率最小 - 不難

• Orz, help me.

Page 45: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 45

Q14

• Solve Problem 11264 “Coin Collector” in the ACM web site.

• withdraw(X){if( X == 0) return;Let Y be the highest valued coin that does not

exceed X.Give the customer Y valued coin.withdraw(X-Y);

}

• maximize the number of different coins that he can collect in a single withdrawal

Page 46: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 46

Q14

• 輸入 C1<C2<C3< … <Cn<1000000000

• 定義 : f[i] = 使用前 i 個硬幣且其中最大面額為 Ci 的最多種類個數。

• 意即 f[i] = k 的最佳解 Si = {Cx1, Cx2, … Cxk} and Cxk = Ci

• 對於其前綴 (prefix) 也都是最佳解。• Si 最佳解符合 1

iSc

Cci

Page 47: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 47

Q14

• Si = {Cx1, Cx2, … Cxk-1 ,Cxk} satisfy

Sxk-1 = {Cx1, Cx2, … Cxk-1} satisfy

• Si = {Sxk-1, Cxk} satisfy

• 遞迴式f[i] = max(f[j]) +1, Cj+1 + Ci < Ci+1

• O(n2)• 再仔細觀察一子,優化到 O(n)

1

iSc

Cci

11

1

k

k

xSxc

Cc

111 iix CCCk

Page 48: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 48

Q14

• 遞迴式f[i] = max(f[j]) +1, Cj+1 + Ci < Ci+1

• When i-value increasing, we know that j-value will increasing.

• Get it ! Maintain prefix maximum value !• O(n)

Page 49: Aaex4 group2(中英夾雜)

04/12/2023 Q1 Q8 49

Q14 - more

• f[i] = max(f[j]) +1, Cj+1 + Ci < Ci+1

f[p] f[q]

calculate f[i]

f[p] and f[q] are prefix maximum value.Because of Cp < Cq, p is better then q. We can only maintain the first maximum value.

j-value