贪心算法的基本步骤:
1、从问题的某个初始解出发。
2、采用循环语句,当可以向求解目标前进一步时,就根据局部最优策略,得到一个部分解,缩小问题的范围或规模。
3、将所有部分解综合起来,得到问题的最终解。
HDU2037:
链接:http://acm.hdu.edu.cn/showproblem.php?pid=2037
题解:
贪心算法:在对问题求解时,总是作出在当前看来是最好的选择。也就是说,不从整体上加以考虑,它所作出的仅仅是在某种意义上的局部最优解(是否是全局最优,需要证明)。若要用贪心算法求解某问题的整体最优解,必须首先证明贪心思想在该问题的应用结果就是最优解!!
本题是贪心法的一个最简单的例子,将结束时间按从小到大排好序,然后寻找下一个开始时间大于等于上一个结束时间的,如此往复,即可解决问题
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<string> 5 #include<algorithm> 6 #include<vector> 7 #include<cmath> 8 using namespace std; 9 const int maxn=100+10; 10 typedef struct 11 { 12 int ts; 13 int te; 14 }t; 15 t p[maxn]; 16 const int cmp(const t s1,const t s2) 17 { 18 return s1.te<s2.te; 19 } 20 int main() 21 { 22 int n; 23 while(cin>>n) 24 { 25 if(n==0) 26 break; 27 for(int i=0;i<n;i++) 28 cin>>p[i].ts>>p[i].te; 29 sort(p,p+n,cmp); 30 int cnt=1; 31 for(int i=0;i<n;i++) 32 { 33 for(int j=i+1;j<n;j++) 34 if(p[i].te<=p[j].ts) 35 { 36 i=j; 37 cnt++; 38 continue; 39 } 40 } 41 cout<<cnt<<endl; 42 } 43 return 0; 44 }
HDU1050
区间覆盖问题:
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1050
题解:先创建一个函数judge(),输入的是任意房间号,输出的是走廊的位置。比如1号房间和2号房间都对应位置1的走廊,3号房间和4号房间对应位置2的走廊,一共有200个这样的位置。我用a[201]定义这些位置,其中某位置的值就是经历这个位置的次数。如果从某一号房到另一号房,所经历的每个位置的次数都+1,最后再全体扫描下哪个位置经历次数最多,输出值便是这个位置的值*10
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 #include<string> 7 #include<vector> 8 using namespace std; 9 const int maxn=200+10; 10 int s[maxn]; 11 int judge(int n) 12 { 13 if(n%2==0) return n/2; 14 else return (n+1)/2; 15 } 16 int main() 17 { 18 int t; 19 cin>>t; 20 while(t--) 21 { 22 int n,a,b; 23 cin>>n; 24 memset(s,0,sizeof(s)); 25 for(int i=0;i<n;i++) 26 { 27 cin>>a>>b; 28 if(a>b) 29 swap(a,b); 30 for(int j=judge(a);j<=judge(b);j++) 31 s[j]++; 32 } 33 int mx=0; 34 for(int i=0;i<201;i++) 35 if(mx<s[i]) 36 mx=s[i]; 37 cout<<mx*10<<endl; 38 } 39 return 0; 40 }