すべてのチャレンジ
中級 1件解決済み 正答率100.0%

Can We Split Into Two Teams?

Decide whether people can be assigned to two teams so that each listed pair is on opposite teams.

このチャレンジで学べること

  • Model people and conflicts as a graph
  • Check bipartiteness with two colors
  • Handle disconnected parts of a graph

問題

翻訳を表示

Decide whether people can be assigned to two teams so that each listed pair is on opposite teams. Every person receives exactly one team; either team may be empty. People without a listed pair can go on either team. Check every connected group of constraints.

Implement split_into_two_teams(people, pairs).

Input

people: The number of people, numbered from 1.

pairs: Rows [first_person, second_person] that must be separated.

Output

Return true if any valid assignment exists, otherwise false. Do not return the assignment.

制約

1 ≤ people ≤ 100,000. 0…200,000 pairs of distinct person IDs in 1…people. Duplicate pairs are allowed and repeat the same constraint.

例

例 1
入力:
people = 3
pairs = [
    [1, 2],
    [2, 3],
    [3, 1]
]

期待される出力:
expected = False
入力:
long long people = 3;
std::vector<std::vector<long long>> pairs = {
    {1, 2},
    {2, 3},
    {3, 1}
};

期待される出力:
bool expected = false;
入力:
long people = 3;
long[][] pairs = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3},
    new long[] {3, 1}
};

期待される出力:
bool expected = false;

解説

If 1 is on team A, 2 must be on B, and 3 must be on A. The last pair then violates the rule.

例 2
入力:
people = 4
pairs = [
    [1, 2],
    [2, 3]
]

期待される出力:
expected = True
入力:
long long people = 4;
std::vector<std::vector<long long>> pairs = {
    {1, 2},
    {2, 3}
};

期待される出力:
bool expected = true;
入力:
long people = 4;
long[][] pairs = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3}
};

期待される出力:
bool expected = true;

解説

Put 1 and 3 on team A and 2 on team B. Person 4 can join either team.

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

This is possible exactly when every constraint component can be colored with two different colors.

ヒント 2

Traverse each connected component and alternate team assignments across each pair constraint.

ヒント 3

If you ever need to give the same person both teams through an odd cycle, the answer becomes false.

目安の計算量

O(people + pairs) time, O(people + pairs) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 797 ms - 5/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。