贪心二进制搜索c++
Greedy Binary Search C++
我正在努力解决这个问题https://www.codechef.com/ZCOPRAC/problems/ZCO12002
给定整数数组V, W和一对数组C (start, end)。你必须找到i, j使得W[j] - V[i]是最小的并且至少有一个对位于V[i]和W[j]
- 根据开始时间对W和竞赛进行排序。
- 对于V中的每一个V[i],二分查找开始时间>= V[i]的比赛,令找到的比赛位于索引c(小c)
- 在W中找到W[i],使它是第一个元素>= Contest[c]。end_time,设为j。
- t2 = W[j], t1 = W[i],则ans = min(ans, t2 - t1 + 1)
然而,尽管逻辑对我和3/4的测试用例来说听起来不错,但这似乎并没有通过其他测试用例。
这是我的代码
int i;
// Input
cin >> n >> x >> y;
V = new int[x];
W = new int[y];
C = new pair<int, int>[n];
for (i = 0;i < n;i++)
cin >> C[i].first >> C[i].second;
for (i = 0;i < x;i++)
cin >> V[i];
for (i = 0;i < y;i++)
cin >> W[i];
// End Input
sort(W, W + y);
sort(C, C + n);
int ans = INT_MAX, c, t1, t2, j;
for (i = 0;i < x;i++)
{
t1 = V[i];
// gr_eq is equivalent to std::lower_bound for pair<int, int>
// Def: gr_eq(pair<int,int>,low,high,target)
c = gr_eq(C, 0, n - 1, t1);
// he will attend the cth contest
if (c >= 0)
{
j = gr_eq(W, 0, y - 1, C[c].second); // lower_bound for integer array
if (j >= 0)
{
t2 = W[j];
ans = min(ans, t2 - t1 + 1);
}
}
}
/* output */
cout << ans << endl;
// Free memory
delete [] V;
delete [] W;
delete [] C;
我做错了什么?是否存在实现或逻辑错误?
编辑下面是我对gr_eq
的实现//
// Find number >= targer
//
int gr_eq(pair<int, int> * a, int low, int high, int target)
{
int mid;
while (low < high)
{
mid = (low+high)/2;
if (a[mid].first >= target)
high = mid;
else
low = mid + 1;
}
if ( a[low].first >= target)
return low;
else
return -1;
}
int gr_eq(int * a, int low, int high, int target)
{
int mid;
while (low < high)
{
mid = (low+high)/2;
if (a[mid] >= target)
high = mid;
else
low = mid + 1;
}
if ( a[low] >= target)
return low;
else
return -1;
}
您没有详细说明代码在哪些情况下会失败,也没有详细说明gr_eq的确切定义。但是,如果它确实使用(或完全模仿)lower_bound(),那么它的搜索范围是[first, last]而不是[first, last],或者换句话说,从第一个,包含到最后一个,不包含。在您的示例中,最后的元素(n-1和y-1)将不包含在提供的范围中。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- 如何在动态数组上使用搜索函数
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- cmake:添加要搜索头文件的目录
- 使用C++创建特殊的二叉搜索树
- 在C++的字符串中搜索和删除某些字符
- std::unordered_map 搜索算法是如何实现的?
- 使用不变量来确定二分搜索中的边界条件
- 二叉搜索如何比线性搜索更快?
- 按边长度递归搜索图中所有可行路径
- QStackWidget - 按名称搜索
- 在递归二叉搜索树中搜索
- 我的二进制搜索程序只是关闭了