ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 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.

สิ่งที่คุณจะได้เรียนรู้

  • จำลองคนและความขัดแย้งเป็นกราฟ
  • ตรวจกราฟสองส่วนด้วยสองสี
  • จัดการส่วนของกราฟที่ไม่เชื่อมกัน

โจทย์

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
อินพุต:
pairs = [
    [1, 2],
    [2, 3],
    [3, 1]
]
people = 3

ผลลัพธ์ที่คาดหวัง:
expected = False
อินพุต:
std::vector<std::vector<long long>> pairs = {
    {1, 2},
    {2, 3},
    {3, 1}
};
long long people = 3;

ผลลัพธ์ที่คาดหวัง:
bool expected = false;
อินพุต:
long[][] pairs = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3},
    new long[] {3, 1}
};
long people = 3;

ผลลัพธ์ที่คาดหวัง:
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
อินพุต:
pairs = [
    [1, 2],
    [2, 3]
]
people = 4

ผลลัพธ์ที่คาดหวัง:
expected = True
อินพุต:
std::vector<std::vector<long long>> pairs = {
    {1, 2},
    {2, 3}
};
long long people = 4;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;
อินพุต:
long[][] pairs = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3}
};
long people = 4;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;

คำอธิบาย

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

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

ทำได้ก็ต่อเมื่อแต่ละ component ของข้อจำกัดสามารถลงสีด้วย 2 สีต่างกันได้

คำใบ้ 2

เดินแต่ละ connected component แล้วสลับการจัดทีมตามข้อจำกัดแบบเป็นคู่

คำใบ้ 3

ถ้าระหว่างทางต้องให้คนเดียวอยู่สองทีมจาก odd cycle คำตอบจะเป็น false

ความซับซ้อนที่คาดหวัง

เวลา O(people + pairs), หน่วยความจำเพิ่ม O(people + pairs)

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก