贪心二进制搜索c++

Greedy Binary Search C++

本文关键字:c++ 搜索 二进制 贪心      更新时间:2023-10-16

我正在努力解决这个问题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)将不包含在提供的范围中。