码迷,mamicode.com
首页 > 编程语言 > 详细

算法专题——贪心算法

时间:2015-03-14 16:46:02      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

贪心算法正确性证明:

1.证明贪心选择性质:经过贪心选择,可以获得最优解

2.最优子结构:证明子问题最优解与贪心选择组合,结果依然是最优解

 

•All we really need to do is argue that an optimal solution to the subproblem, combined with the greedy choice already made, yields an optimal solution to the original problem.
例:
技术分享
•每次选择与当前已选Interval重叠,且X_R最大的Interval即可
 
贪心算法相关OJ题目:
1.POJ 1042 Gone Fishing
2.NYOJ 248 BUYING FEED II
3.HDU 1052 The Horse Racing
技术分享
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
 5 
 6 int a[1001],b[1001];
 7 
 8 int main()
 9 {
10     int n;
11     while ((cin>>n)&&(n!=0))
12     {
13         memset(a,0,sizeof(a));
14         memset(b,0,sizeof(b));
15         for (int i=0;i<n;i++)
16             cin>>a[i];
17         for (int i=0;i<n;i++)
18             cin>>b[i];
19         sort(a,a+n);
20         sort(b,b+n);        //a,b均已排好序,下面依次从后往前遍历即可
21                             //显然不可能次次排序,在比完后如何去掉用过的元素?
22         int money = 0;
23         for (int i=n-1;i>=0;i--)
24         {
25             if (b[i]>a[i])
26             {
27                 money-=200;
28                 int temp=a[0];
29                 for (int j=0;j<i;j++)
30                     a[j]=a[j+1];
31                 a[i]=temp;
32             }
33             else if (b[i]<a[i])
34             {
35                 money+=200;
36                 int j=i;
37                 while ((b[i]<a[j])&&(j>=0)) j--;
38                 int temp=a[j+1];
39                 for (int k=j+1;k<i;k++)
40                     a[k]=a[k+1];
41                 a[i]=temp;
42             }
43             //若出现相等情况,则比较复杂
44             else if (b[i]==a[i])
45             {
46                 if (a[0]>b[0])
47                 {
48                     money+=200;
49                     int temp1=a[0],temp2=b[0];
50                     for (int j=0;j<i;j++)
51                     {
52                         a[j]=a[j+1];
53                         b[j]=b[j+1];
54                     }
55                     a[i]=temp1;    
56                     b[i]=temp2;
57                 }
58                 else
59                 {
60                     if (a[0]<a[i]) money-=200;
61                     int temp=a[0];
62                     for (int j=0;j<i;j++)
63                         a[j]=a[j+1];
64                     a[i]=temp;
65                 }
66             }
67         }
68         cout<<money<<endl;
69     }
70     return 0;
71 }
View Code
4.HDU 1051 Wooden Sticks
5.POJ 1328 Radar Installation
6.POJ 1323 Game Prediction
 
 

算法专题——贪心算法

标签:

原文地址:http://www.cnblogs.com/giddens/p/4336181.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!