贪心算法—宝藏最优选择问题
原理参考趣学算法
代码:
#include"quickSort1.h"
快速排序代码
int quickSort1(int a[], int l, int h) {//快速排序int i = l, j = h, p = a[l];while (i < j) {while (i<j&&a[j]>p) {//从右往左遍历查找比p更小的元素j--;}if (i < j) {a[i++] = a[j];}while (i < j&&a[i] <= p) {//从左往右遍历查找比p更大的元素i++;}if (i < j) {a[j--] = a[i];}}a[i] = p;//分界的值,左边小于等于p,右边大于preturn i;
}
void fenZhi1(int a[], int l, int h) {//分治if (l < h) {int mid = quickSort1(a, l, h);//以mid为分界线,进行分治,然后递归下去排序fenZhi1(a, l, mid - 1);fenZhi1(a, mid + 1, h);}
}
贪心代码
#include <stdio.h>
#include <stdlib.h>
#include"quickSort1.h"
void getBestValue(int * a,int bestWeight,int n) {//等值物品的最优选择问题int tempSum = 0;//临时总和量int pointCount = 0;//前个数for (int i = 0; i < n; i++) {tempSum += *(a + i);if (tempSum > bestWeight) {pointCount = i;break;}printf("%d ", *(a + i));}printf("\n总共%d个!\n",pointCount);
}
int main() {int b[7] = { 1,6,4,3,9,7,5 };int length = sizeof(b) / sizeof(b[0]);fenZhi1(b, 0, length - 1);getBestValue(b, 17, length);system("pause");return 0;
}