1. 程式人生 > 程式設計 >C++貪心演算法實現活動安排問題(例項程式碼)

C++貪心演算法實現活動安排問題(例項程式碼)

貪心演算法

貪心演算法(又稱貪婪演算法)是指,在對問題求解時,總是做出在當前看來是最好的選擇。也就是說,不從整體最優上加以考慮,他所做出的是在某種意義上的區域性最優解。

貪心演算法不是對所有問題都能得到整體最優解,關鍵是貪心策略的選擇,選擇的貪心策略必須具備無後效性,即某個狀態以前的過程不會影響以後的狀態,只與當前狀態有關。

具體程式碼如下所示:

#include <cstdio>
#include <iostream>
#include <ctime>
#include <windows.h>
#include <algorithm>
#include <fstream>
using namespace std;
struct activity
{
  int no;
  int start;
  int finish;
};
bool cmp(const activity &x,const activity &y)
{
  return x.finish<y.finish;//從小到大排<,若要從大到小排則>
}
int greedySelector(int m,int solution[],struct activity activity[]){
  int number = 1;
  solution[0] = 1;
  int i,j = 0,counter = 1;
  for(i = 1;i < m ;i++)
  {
    if(activity[i].start >=activity[j].finish)
    {
      solution[i] = 1;
      j = i;
      counter++;
    }
    else
      solution[i] = 0;
  }
  cout << "The amount of activities is:"<<counter<<endl;
  cout << "The solution is:";
  for(i = 0 ;i < m ;i++)
  {
    if (solution[i] == 1)
    {
      cout << activity[i].no <<" ";
    }
  }
  return counter;
}
int main(void)
{
  LARGE_INTEGER nFreq;
  LARGE_INTEGER nBeginTime;
  LARGE_INTEGER nEndTime;
  ofstream fout;
  srand((unsigned int)time(NULL));
  int m,i,j,t;
  double cost;
  cout << "Please enter the number of times you want to run the program:";
  cin >> t;
  fout.open("activity.txt",ios::app);
  if(!fout){
    cerr<<"Can not open file 'activity.txt' "<<endl;
    return -1;
  }
  fout.setf(ios_base::fixed,ios_base::floatfield);    //防止輸出的數字使用科學計數法
  for (j = 0;j < t;j++)
  {
    cout << "——————————————————The "<< j + 1 << "th test —————————————————"<<endl;
    m = 1 + rand()%100000;
    fout<<m<<",";
    int solution[m];
    activity activity[m];
    for( i = 0;i < m;i++)
    {
      activity[i].no = i+1;
      activity[i].start = 1 + rand()%1000;
      while(1)
      {
        activity[i].finish = 1 + rand()%10000;
        if(activity[i].finish > activity[i].start) break;
      }
    }
    QueryPerformanceFrequency(&nFreq);
    QueryPerformanceCounter(&nBeginTime);
    sort(activity,activity+m,cmp);
    greedySelector(m,solution,activity);
    QueryPerformanceCounter(&nEndTime);
    cost=(double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart;
    fout << cost << endl;
    cout << "\nThe running time is:" << cost << " s" << endl;
  }
  fout.close();
  cout << endl << endl;
  cout << "Success!" << endl;
  return 0;
}

總結

以上所述是小編給大家介紹的C++貪心演算法實現活動安排問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!