Two-coach trip
MediumOnline Assessment
Split the students of a school trip between two coaches so that neither coach is more crowded than it has to be.
There are n students numbered 0 to n - 1, and each must ride exactly one of two coaches. Coaches have no seat limit and may even be empty.
- Every pair in
rivalsis a pair of students who must not ride the same coach. - Every pair in
friendsis a pair of students who must ride the same coach.
Rules apply even indirectly: if 0 and 1 are friends and 1 and 2 are friends, then 0 and 2 ride together as well. A pair may be listed more than once, and a student can never be a rival of themself.
Input: n, the number of students, rivals, a list of [a, b] pairs, and friends, a list of [a, b] pairs.
Output: the smallest possible number of students on the fuller coach over all valid ways to assign the students, or -1 if no valid assignment exists. Both coaches have to be counted, so with n = 5 and no rules at all the answer is 3.
Many students can be completely unconstrained, and there can be a great many independent groups, so trying every assignment of groups to coaches will be too slow.
Example 1
- Input:
- [5,[[0,1],[2,3]],[]]
- Output:
- 3
- Explanation
- Students 0 and 1 are rivals and 2 and 3 are rivals, so each pair is split across the coaches. Student 4 is free. One coach takes one student from each pair plus student 4 (3 students), the other takes 2, so the fuller coach carries 3.
Example 2
- Input:
- [6,[[1,2]],[[0,1],[2,3]]]
- Output:
- 3
- Explanation
- Friends 0 and 1 travel together, and friends 2 and 3 travel together. Rivals 1 and 2 are separated, so the groups {0, 1} and {2, 3} go on different coaches, and 4 and 5 can go anywhere. Splitting them 3 and 3 is possible ({0, 1, 4} and {2, 3, 5}), so the fuller coach carries 3.
Example 3
- Input:
- [4,[[0,2]],[[0,1],[1,2]]]
- Output:
- -1
- Explanation
- 0 and 1 are friends and 1 and 2 are friends, so all three must share a coach, but 0 and 2 are rivals and must not. No plan works: -1.
Constraints
1 <= n <= 1,5000 <= rivals.length, friends.length <= 1,500- every pair holds two student numbers in
[0, n - 1]