我采用了C ++中的这个例子 http://www.geeksforgeeks.org/weighted-job-scheduling-log-n-time/
这是C实现
#include <stdio.h>
#include <stdlib.h>
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
//#ifndef max
// #define max(a,b) ((a) > (b) ? (a) : (b))
//#endif
struct rent
{
int starttime, endtime, profit;
};
int sort_event(const void * st1, const void * st2)
{
struct rent s1, s2;
s1.endtime = *(int*)st1;
s2.endtime = *(int*)st2;
return (s1.endtime < s2.endtime);
}
int binarySearch(struct rent rents[], int index)
{
// Initialize 'lo' and 'hi' for Binary Search
int lo = 0, hi = index - 1;
// Perform binary Search iteratively
while (lo <= hi)
{
int mid = (lo + hi) / 2;
if (rents[mid].endtime <= rents[index].starttime)
{
if (rents[mid + 1].endtime <= rents[index].starttime)
lo = mid + 1;
else
return mid;
}
else
hi = mid - 1;
}
return -1;
}
int findMaxProfit(struct rent arr[], int n)
{
qsort(arr, sizeof(arr+n), sizeof(int), sort_event);
int *table = (int *) malloc(sizeof(n));
table[0] = arr[0].profit;
// Fill entries in table[] using recursive property
for (int i=1; i<n; i++)
{
// Find profit including the current job
int inclProf = arr[i].profit;
int l = binarySearch(arr, i);
if (l != -1)
inclProf += table[l];
// Store maximum of including and excluding
table[i] = max(inclProf, table[i-1]);
}
// Store result and free dynamic memory allocated for table[]
int result = table[n-1];
free(table);
return result;
}
int main()
{
struct rent arr1[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}};
int n = sizeof(arr1)/sizeof(arr1[0]);
printf("\nOptimal profit is %d\n", findMaxProfit(arr1, n));
return 0;
}
预期的结果是250.经过进一步调查,我发现C中的qsort()具有不同的实现wrt。 sort()是incsort。但是我不确定这是唯一的原因还是什么。任何人都可以建议哪里可能是失礼。
答案 0 :(得分:1)
对我而言,您似乎错误地致电func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
// Write a similar code to exchange/move view controllers using tabbarController instance.
}
。
请改为尝试:
qsort
答案 1 :(得分:1)
&#34;函子&#34;在C和C ++中工作方式不同。 qsort
和bsearch
期望一个函数返回小于,等于或大于0的值,如果s1小于,等于或大于s2。
在C ++中,仿函数只会执行其中一个,例如,如果较小则返回true。
将代码更改为return s1.endtime - s2.endtime;
此外,您对qsort
的来电是无稽之谈。正如另一个答案所指出的那样,你给出了错误的参数。 sizeof(arr+n)
应为n
。 qsort
想要项目数,而不是字节数。您错误地使用sizeof
- 您甚至无法在arr
等函数参数上使用它。