Students arrangement

See the original problem on HackerRank.

Solutions

First of all, we sort both the series in non-decreasing order, then we simply check if alternating boys and girls is feasible according to the rules:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int T, N;
cin >> T;
while (T--)
{
    cin >> N;
    array<vector<int>, 2> v = {vector<int>(N), vector<int>(N)};
    copy_n(istream_iterator<int>(cin), N, begin(v[0]));
    copy_n(istream_iterator<int>(cin), N, begin(v[1]));
    
    sort(begin(v[0]), end(v[0]));
    sort(begin(v[1]), end(v[1]));
    
    auto m = mismatch(begin(v[0]), end(v[0]), begin(v[1]), end(v[1]));
    
    if (m.first == end(v[0]))
    {
        cout << "YES" << "\n";
        continue;
    }
    bool idx = *m.first > *m.second;

    auto last = -1;
    auto checked = true;
    for (auto i=0; i<N && checked; ++i)
    {
        checked = v[idx][i] >= last;
        checked &= v[idx][i] <= v[!idx][i];
        last = v[!idx][i];
    }
    
    cout << (checked ? "YES" : "NO") << "\n";
}
sort  ad-hoc 
We've worked on this challenge in these gyms: modena 
comments powered by Disqus