algorithm
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: algorithm VII description: 第七次作業 --- # Group 2 組員:王承隆、賴文宏、施宗佑、王昱翔、王柏喬、莊淳方、傅文宗 # Problem 1 ## Topic Determine the cost and structure of an optimal binary search tree for a set of $n = 7$ keys with the following probabilities ## Solution ![](https://i.imgur.com/qiQqkZP.jpg) ![](https://i.imgur.com/zaSGQz3.jpg) ```graphviz digraph Tree{ k5->k2 k5->k7 k2->k1 k2->k3 k7->k6 k3->k4 k7->d7 k1->d0 k1->d1 k3->d2 k6->d5 k6->d6 k4->d3 k4->d4 } ``` # Problem 2 [CLRS 3 rd ] Exercise 15.5-4 ## Topic Knuth [212] has shown that there are always roots of optimal subtrees such that $root[i, j−1]≤root[i,j]≤root[i+1,j] root[i, j - 1]$ for all $1≤i<j≤n$ Use this fact to modify the OPTIMAL-BST$\Theta(n^2)$ time. ## Solution ``` OPTIMAL-BST let e[1...n+1, 0...n], w[1..n+1, 0..n], and root[1..n, 1..n] be new tables for i = 1 to n +1 e[i, i-1] = q_(i-1) w[i, i-1] = q_(i-1) for l = 1 to n for i = 1 to n - l + 1 location 6 j = i + l -1 e[i, j] = INFINITE w[i, j] = w[i, j-1] + p_j + q_j line 10 for r = i to j t = e[i, r-1] + e[r+1, j] + w[i, j] if t < e[i, j] e[i, j] = t root[i, j] = r return e and root ``` The loop at line 10 is meant to find the best root of the subtree. We can us the prorperty the problem give to change the loop at line 10 to for $r = r[i, j - 1]$ to $r[i + 1, j]$ First, suppose i = 1, j = 3 then we have the loop for $r = r[1, 2]$ to $r[2, 3]$ Second, on the next iteration of the loop at location 6 we have i = 2, j = 4 and for $r = r[2, 3]$ to $r[3, 4]$ Comparing the range of r in the two iteration, we find ==their ranges have nothing to do with n.== Thus, the time complexity, $O(n^3)$, is redeuced to $O(n^2)$ # Problem 3 [CLRS 3 rd ] Exercise 16.1-3 ## Topic ## Solution 1. {(0,10),(8,12),(11,16),(15,18),(17,25)} always peek the shortest {(8,12),(15,18)} but there is a better solution {(0,10),(11,16),(17,25)} 2. {(0,3),(2,4),(2,4),(3,6),(5,7),(6,8),(7,10),(7,10),(7,10),(9,11),(9,11)} always peek the one overlaps the fewest Get: {(0,3),(5,7),(9,11)} Best: {(0,3),(3,6),(6,8),(9,11)} 3. {(0,10),(6,7),(8,13)} always peek the earliest Get: {(0,10)} Best: {(6,7),(8,13)} # Problem 4 [CLRS 3 rd ] Exercise 16.1-4 ## Topic ## Solution ```Pseudo= Scheduling(activities[1..n]){ calculating the maximal overlap of the activities, which is the minimum of halls we need suppose the maximal overlap is m for i = 1 to n for j = 1 to m if(the end of the last activity in jth hall is later than the start of ith activity) check (j+1)th hall else put ith activity in jth hall return scheduling of 1..nth hall } ``` ```c++= #include <iostream> #include <vector> #include <tuple> #include <algorithm> using namespace std; bool comp1(tuple<int, int> t1, tuple<int, int> t2){ return (get<1>(t1) <= get<1>(t2)); } bool comp2(tuple<int, int> t1, tuple<int, int> t2){ if(get<0>(t1) < get<0>(t2)) return 1; else if(get<0>(t1) > get<0>(t2)) return 0; else return (get<1>(t1) <= get<1>(t2)); } vector<vector<tuple<int, int>>> scheduling(vector<tuple<int, int>> activities){ int hall, activity; sort(activities.begin(), activities.end(), comp2); //calculating the maximal overlap int overlap = 0; for(int i = 1, counter = 1, currentEnd = get<1>(activities[0]), endIndex = 0;i < activities.size();i++){ if(get<0>(activities[i]) < currentEnd){ if(overlap < ++counter) overlap = counter; } else{ while(get<0>(activities[i]) >= get<1>(activities[endIndex])){ counter--; endIndex++; } currentEnd = get<1>(activities[endIndex]); } } vector<vector<tuple<int, int>>> halls(overlap, vector<tuple<int, int>>(0)); sort(activities.begin(), activities.end(), comp1); for(int i = 0, j, start, end;i < activities.size();i++){ start = get<0>(activities[i]); for(j = 0;j < halls.size();j++){ if(halls[j].empty()){ halls[j].push_back(activities[i]); break; } end = get<1>(halls[j][halls[j].size() - 1]); if(start < end) continue; else{ halls[j].push_back(activities[i]); break; } } } return halls; } int main(){ vector<tuple<int, int>> activities; int start, end, i, j; while(cin >> start >> end) activities.push_back(make_tuple(start, end)); vector<vector<tuple<int, int>>> halls = scheduling(activities); for(i = 0;i < halls.size();i++){ cout << "hall" << i + 1 << ": "; for(j = 0;j < halls[i].size();j++) cout << '(' << get<0>(halls[i][j]) << ", " << get<1>(halls[i][j]) << ")\t"; cout << endl; } } ``` # Problem 5 [CLRS 3 rd ] Exercise 16.1-5 (Hint: refer to Exercise 16.1-1) ## Topic ## Solution ```Pseudo Solution(intervals[1..n]){ //intervals[i] = (start::int, end::int, value::int) sort intervals by end int max[intervals[n].end + 1] // record the maximum in ith moment for(i = 0, j = 0;i < n;i++, j++){ if(i > 0 and intervals[i].end == intervals[i - 1].end) j--; for(;j < intervals[i].end;j++) max[j] = max[j - 1]; if(intervals[i].value + max[intervals[i].end] > max[j - 1]) max = intervals[i].value + max[intervals[i].start]; else max = max[j - 1]; return max[intervals[n - 1].end] } ``` ```c++= #include <iostream> #include <vector> #include <tuple> #include <algorithm> using namespace std; bool comp(tuple<int, int, int> t1, tuple<int, int, int> t2){ if(get<1>(t1) < get<1>(t2)) return 1; else if(get<1>(t1) > get<1>(t2)) return 0; else{ if(get<2>(t1) < get<2>(t2)) return 1; else return 0; } } int maximum(vector<tuple<int, int, int>> intervals){ int i, j; sort(intervals.begin(), intervals.end(), comp); int max[get<1>(intervals[intervals.size() - 1]) + 1] = {}; for(i = 0, j = 1;i < intervals.size();i++, j++){ if(i > 0 && get<1>(intervals[i]) == get<1>(intervals[i - 1])) j--; for(;j < get<1>(intervals[i]);j++) max[j] = max[j - 1]; max[j] = get<2>(intervals[i]) + max[get<0>(intervals[i])] > max[j - 1] ? get<2>(intervals[i]) + max[get<0>(intervals[i])] : max[j - 1]; } for(i = 0;i < get<1>(intervals[intervals.size() - 1]) + 1;i++) cout << max[i] << ' '; cout << endl; return max[get<1>(intervals[intervals.size() - 1])]; } int main(){ int start, end, value; vector<tuple<int, int, int>> intervals; cout << "input start, end and value, respectively" << endl; while(cin >> start >> end >> value) intervals.push_back(make_tuple(start, end, value)); cout << maximum(intervals) << endl; } ``` # Problem 6 A variation from [CLRS 3 rd ] Exercise 16.2-2 Given a 0-1 knapsack problem with the knapsack size K and n items, where each item has its weight in integer and its value in real. (a) Design an algorithm to find the most valuable load of the items that fit into the knapsack. (b) Design a pseudo-polynomial time algorithm to determine the optimal solution that the total weight exactly equals to K. ## Topic ## Solution ### (a) ```Pseudo= KNAPSACK(W, set) Initialize an (n + 1) by (W + 1) table for i = 0 to n //0 to ith items for j = 0 to W // current weight limit if i==0 || w=0 table[i][w] = 0; else if set[i-1].weight <= w table[i][w] = max(set[i-1].value + table[i-1][w-set[i-1].weight], table[i-1][w]) else table[i][w] = table[i-1][w] ``` ```=C++ #include<iostream> #include<vector> using namespace std; int max(int a, int b) { return (a > b)? a : b; } struct item{ int value; int weight; }; void knapSack(int W, vector<item>set) { int i, w, n=set.size(); int table[n+1][W+1]; for (i = 0; i <= n; i++) //0 to ith items { for (w = 0; w <= W; w++) // current weight limit { if (i==0 || w==0) table[i][w] = 0; else if (set[i-1].weight <= w) //compare the profits of putting it in or not table[i][w] = max(set[i-1].value + table[i-1][w-set[i-1].weight], table[i-1][w]); else//item weight beyond limit table[i][w] = table[i-1][w]; } } cout<< table[n][W]<<endl; for (int i = n-1, j = W; i >= 0; --i) //solution if (j - set[i].weight >= 0 && table[i+1][j] == table[i][j - set[i].weight] + set[i].value) { cout <<i<<endl; j -= set[i].weight; } } int main() { int maximum_weight, weight, value; vector<item>collection; cin>>maximum_weight; while(cin>>value>>weight) collection.push_back(item{value, weight}); knapSack(maximum_weight,collection); return 0; } ``` ### (b) ```Pseudo= KNAPSACK(W, set) Initialize an (n + 1) by (W + 1) table for i = 0 to n //0 to ith items for j = 0 to W // current weight limit if (set[i-1].weight <= w) //compare the profits of putting it in or not if(w == 0 || i == 0){} else if(set[i - 1].value + table[i - 1][w - set[i - 1].weight].value > table[i - 1][w].value) table[i][w].value = set[i - 1].value + table[i - 1][w - set[i - 1].weight].value table[i][w].last.value = i - 1 table[i][w].last.weight = w - set[i - 1].weight else table[i][w].value = table[i - 1][w].value table[i][w].last.value = table[i - 1][w].last.value table[i][w].last.weight = table[i - 1][w].last.weight else if(set[i - 1].weight > w) //item weight beyond limit table[i][w].value = table[i-1][w].value table[i][w].last.value = table[i - 1][w].last.value table[i][w].last.weight = table[i - 1][w].last.weight ``` ```=C++ #include<iostream> #include<vector> #include <stack> using namespace std; int max(int a, int b) { return (a > b)? a : b; } struct item{ int value = 0; int weight = 0; }; struct item2{ int value = 0; item last; }; void knapSack(int W, vector<item>set) { int i, w, n=set.size(); item2 table[n+1][W+1]; for (i = 0; i <= n; i++) //0 to ith items { for (w = 0; w <= W; w++) // current weight limit { if (set[i-1].weight <= w) //compare the profits of putting it in or not if(w == 0 || i == 0){} else if(set[i - 1].value + table[i - 1][w - set[i - 1].weight].value > table[i - 1][w].value){ table[i][w].value = set[i - 1].value + table[i - 1][w - set[i - 1].weight].value; table[i][w].last.value = i - 1; table[i][w].last.weight = w - set[i - 1].weight; } else{ table[i][w].value = table[i - 1][w].value; table[i][w].last.value = table[i - 1][w].last.value; table[i][w].last.weight = table[i - 1][w].last.weight; } else if(set[i - 1].weight > w){//item weight beyond limit table[i][w].value = table[i-1][w].value; table[i][w].last.value = table[i - 1][w].last.value; table[i][w].last.weight = table[i - 1][w].last.weight; } } } stack<int> index; for(i = 0;i <= n;i++){ for(w = 0;w <= W;w++) cout << '(' << table[i][w].value << ", " << table[i][w].last.value << ", " << table[i][w].last.weight << ')'; cout << endl; } for(int k = n;k > 0;k--){ for(i = table[k][W].last.value, w = table[k][W].last.weight;i > 0 && w > 0;i = table[i][w].last.value, w = table[i][w].last.weight){ index.push(i); } if(w == 0){ index.push(i); cout << table[k][W].value << endl; while(!index.empty()){ cout << index.top() << ' '; index.pop(); } cout << endl; return; } else if(i == 0){ while(!index.empty()) index.pop(); break; } } cout << "No answer" << endl; } int main() { int maximum_weight, weight, value; vector<item>collection; cin>>maximum_weight; while(cin>>value>>weight) collection.push_back(item{value, weight}); knapSack(maximum_weight,collection); return 0; } ``` # Problem 7 [CLRS 3 rd ] Exercise 16.2-6 ## Topic Give a dynamic-programming solution to the 0-1 knapsack problem that runs in **$O(nW)$** time, where n is the number of items and W is the maximum weight of items that the thief can put in his knapsack. ## Solution Same as Problem 6(a) # Problem 8 ## Topic Given a set S of n integers and another integer M, determines whether or not there exist k elements in S whose sum is exactly M. k is an input parameter. 這題要寫Pseudo Code Hint: DP定義: dp[i][j][k]代表從前i個數字取j個數字湊出k, 若可以湊填1, 否則填0 遞迴式: dp[i][j][k] = dp[i-1][j][k] || dp[i-1][j-1][k-S[i]], if k-S[i] >=0 = dp[i-1][j][k], if k-S[i] < 0 ## Soluation ```pseudocode= #define notFound null function(Set S, int M, string key = "", int index = 0){ define static dynamic table DP<string, int>; // storage the other result DP[""] = 0; forEach((el, i) in S start with index) DP[key+str(el)] = DP[key] + el; if(DP[key+str(el)]==M) return key+str(el); if(index<S.length) function(S, M, key+str(el)+" ", i+1); }); return notFound; } str(any var){ return stringType(var); } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully