即使在我的系统上可以运行,仍在编程网站上不断出现运行时错误(SIGSEGV)

时间:2019-05-16 07:36:28

标签: c++ algorithm runtime-error unordered-map greedy

我正在解决此问题https://www.codechef.com/problems/FGFS。 我找不到运行时错误(SIGSEGV)的原因。该代码可在我的系统上运行,但我找不到错误所在。

起初,我以为我遇到了错误,因为我没有考虑边缘情况(N = 0),并且正在通过迭代器访问未分配的内存,但是在修复它之后,我仍然遇到运行时错误。 / p>

我的代码:

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>

using namespace std;

struct Interval
{
    int s, f;
    Interval(int _s = 0, int _f = 0)
        : s(_s), f(_f) {}
    friend istream& operator>> (istream& in, Interval& I)
    {
        return in >> I.s >> I.f;
    }
};

class Comparator
{
public:
    bool operator() (const Interval& I1, const Interval& I2) const
    {
        return I1.f < I2.f;
    }
};

bool intersect(const Interval& I1, const Interval& I2)          // two intervals intersect if the departure time of the first is greater than the arrival time of the second (Note that they are already sorted according to Comparator())
{
    return I1.f > I2.s;
}

int main()
{
    int T;
    cin >> T;

    while (T--)
    {
        int N, K;
        cin >> N >> K;

        if (N == 0)
        {
            cout << 0 << endl;
            continue;
        }

        unordered_map<int, vector<Interval>> R;
        for (int i = 0; i < N; ++i)
        {
            Interval I;
            int p;
            cin >> I >> p;

            R[p].push_back(I);
        }

        for (auto itr = R.begin(); itr != R.end(); ++itr)
            sort(itr->second.begin(), itr->second.end(), Comparator());     // sort the vector at each compartment based on the departure time of the customers

        int count = 0;
        for (auto itr = R.cbegin(); itr != R.cend(); ++itr)
        {
            const vector<Interval>& C = itr->second;

            ++count;
            size_t k = 0;
            for (size_t i = 1; i < C.size(); ++i)                           // greedy algorithm to count the size of the maximal set of non-conflicting intervals at that respective compartment
                if (!intersect(C[k], C[i]))
                {
                    ++count;
                    k = i;
                }
        }

        cout << count << endl;
    }
}

约束:

1 ≤ T ≤ 30
0 ≤ N ≤ 105
1 ≤ K ≤ 109
0 ≤ si < fi ≤ 109
1 ≤ pi ≤ K

示例输入和输出:

输入:

2
3 3
1 3 1
4 6 2
7 10 3
4 2
10 100 1
100 200 2
150 500 2
200 300 2

输出:

3
3

在网站上出现运行时错误(SIGSEGV),但在我的系统上运行正常。

0 个答案:

没有答案