贪心算法正确性证明:
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
较好的解题参考:http://www.cnblogs.com/anderson0/archive/2011/05/07/2039971.html
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 }
4.HDU 1051 Wooden Sticks
5.POJ 1328 Radar Installation
6.POJ 1323 Game Prediction
时间: 2024-11-07 09:30:27