C++贪心算法实现活动安排问题
2019-11-04 09:31:55来源:博客园 阅读 ()
C++贪心算法实现活动安排问题
_(:з」∠)_
1 #include <cstdio> 2 #include <iostream> 3 #include <ctime> 4 #include <windows.h> 5 #include <algorithm> 6 #include <fstream> 7 using namespace std; 8 struct activity 9 { 10 int no; 11 int start; 12 int finish; 13 }; 14 bool cmp(const activity &x, const activity &y) 15 { 16 return x.finish<y.finish;//从小到大排<,若要从大到小排则> 17 } 18 int greedySelector(int m,int solution[],struct activity activity[]){ 19 int number = 1; 20 solution[0] = 1; 21 int i,j = 0,counter = 1; 22 for(i = 1;i < m ;i++) 23 { 24 if(activity[i].start >=activity[j].finish) 25 { 26 solution[i] = 1; 27 j = i; 28 counter++; 29 } 30 else 31 solution[i] = 0; 32 } 33 cout << "The amount of activities is:"<<counter<<endl; 34 cout << "The solution is:"; 35 for(i = 0 ;i < m ;i++) 36 { 37 if (solution[i] == 1) 38 { 39 cout << activity[i].no <<" "; 40 } 41 } 42 return counter; 43 } 44 int main(void) 45 { 46 LARGE_INTEGER nFreq; 47 LARGE_INTEGER nBeginTime; 48 LARGE_INTEGER nEndTime; 49 ofstream fout; 50 srand((unsigned int)time(NULL)); 51 int m,i,j,t; 52 double cost; 53 cout << "Please enter the number of times you want to run the program:"; 54 cin >> t; 55 fout.open("activity.txt",ios::app); 56 if(!fout){ 57 cerr<<"Can not open file 'activity.txt' "<<endl; 58 return -1; 59 } 60 fout.setf(ios_base::fixed,ios_base::floatfield); //防止输出的数字使用科学计数法 61 for (j = 0;j < t;j++) 62 { 63 cout << "——————————————————The "<< j + 1 << "th test —————————————————"<<endl; 64 m = 1 + rand()%100000; 65 fout<<m<<","; 66 int solution[m]; 67 activity activity[m]; 68 for( i = 0;i < m;i++) 69 { 70 activity[i].no = i+1; 71 activity[i].start = 1 + rand()%1000; 72 while(1) 73 { 74 activity[i].finish = 1 + rand()%10000; 75 if(activity[i].finish > activity[i].start) break; 76 } 77 } 78 QueryPerformanceFrequency(&nFreq); 79 QueryPerformanceCounter(&nBeginTime); 80 sort(activity,activity+m,cmp); 81 greedySelector(m,solution,activity); 82 QueryPerformanceCounter(&nEndTime); 83 cost=(double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart; 84 fout << cost << endl; 85 cout << "\nThe running time is:" << cost << " s" << endl; 86 } 87 fout.close(); 88 cout << endl << endl; 89 cout << "Success!" << endl; 90 return 0; 91 }
原文链接:https://www.cnblogs.com/Jesse-Cavendish/p/11791036.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:set容器与map容器的简单应用
下一篇:清北学堂day3
- C++ 转换函数搭配友元函数 2020-06-10
- C++ 自动转换和强制类型转换(用户自定义类类型) 2020-06-10
- C++ rand函数 2020-06-10
- C++ 友元函数 2020-06-10
- C++ 运算符重载 2020-06-10
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash