活動選擇問題(貪婪演算法 1)用 C++ 編寫?


給定 n 項不同的活動及其開始時間和結束時間。選擇一個人解決的最大活動數。

我們將使用貪婪演算法來找到剩餘活動中完成時間最短的下一項活動,並且其開始時間大於或等於上次選定活動的完成時間。

  • 當列表未排序時,此問題的複雜度為 O(n log n)。如果提供了已排序的列表,則複雜度將為 O(n)。

輸入

一份具有開始和結束時間的不同活動的列表。

{(5,9), (1,2), (3,4), (0,6), (5,7), (8,9)}

輸出

選定的活動為 −

Activity: 0 , Start: 1 End: 2
Activity: 1 , Start: 3 End: 4
Activity: 3 , Start: 5 End: 7
Activity: 5 , Start: 8 End: 9

演算法

maxActivity(act, size)

輸入 - 活動列表以及列表中的元素數。
輸出 - 已選擇的活動順序。

Begin
   initially sort the given activity List
   set i := 1
   display the i-th activity //in this case it is the first activity
   for j := 1 to n-1 do
      if start time of act[j] >= end of act[i] then
         display the jth activity
         i := j
   done
End

示例

 即時演示

#include<iostream>
#include<algorithm>
using namespace std;
   struct Activitiy {
      int start, end;
   };
   bool comp(Activitiy act1, Activitiy act2) {
      return (act1.end < act2.end);
   }
   void maxActivity(Activitiy act[], int n) {
   sort(act, act+n, comp); //sort activities using compare function
   cout << "Selected Activities are: " << endl;
   int i = 0;// first activity as 0 is selected
   cout << "Activity: " << i << " , Start: " <<act[i].start << " End: " << act[i].end <<endl;
   for (int j = 1; j < n; j++) { //for all other activities
      if (act[j].start >= act[i].end) { //when start time is >=end time, print the activity
         cout << "Activity: " << j << " , Start: " <<act[j].start << " End: " << act[j].end <<endl;
         i = j;
      }
   }
}
int main() {
   Activitiy actArr[] = {{5,9},{1,2},{3,4},{0,6},{5,7},{8,9}};
   int n = 6;
   maxActivity(actArr,n);
   return 0;
}

輸出

Selected Activities are:
Activity: 0 , Start: 1 End: 2
Activity: 1 , Start: 3 End: 4
Activity: 3 , Start: 5 End: 7
Activity: 5 , Start: 8 End: 9

更新於: 30-7 月-2019

2K+ 閱讀

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告