Ad platform~30 min2s · 256 MBtarget O((n + m) log m) time, O(n + m) spacebfs
You work on an ads platform that runs experiments. There are n ad creatives, numbered 0 to n - 1, and each must be put in test cohort 0 or in test cohort 1.
Analysts send reports in order. A report says that two creatives must be in the same cohort, or that they must be in opposite cohorts. After a while the reports may contradict each other, and then no assignment of cohorts satisfies all of them.
Your team lead asks: "How many reports, from the start of the list, can still be satisfied together?" The platform can have 20,000 creatives and 20,000 reports.
Write accepted_reports(n, reports).
reports[i] = [a, b, kind] is the i-th report. When kind = 0, creatives a and b must be in the same cohort. When kind = 1, they must be in opposite cohorts.a can equal b. A report with a = b and kind = 1 can never be satisfied.k such that some assignment of every creative to a cohort satisfies the first k reports. Return len(reports) when all of them can be satisfied.Input: n = 4, reports = [[0, 1, 1], [1, 2, 1], [2, 3, 0], [0, 3, 1]]
Output: 3Check the first k reports for each k. The cohort lists give the cohort of creatives 0 to 3:
| k | Report added | Result |
|---|---|---|
| 1 | [0, 1, 1] | cohorts [0, 1, 0, 0] |
| 2 | [1, 2, 1] | cohorts [0, 1, 0, 0] |
| 3 | [2, 3, 0] | cohorts [0, 1, 0, 0] |
| 4 | [0, 3, 1] | contradiction |
The first three reports are satisfied together. The fourth says that creatives 0 and 3 must differ, but the first three put both in cohort 0.
Input: n = 3, reports = [[0, 1, 0], [1, 2, 0], [0, 2, 0]]
Output: 3All three creatives can share one cohort, so every report is satisfied.
Input: n = 2, reports = [[1, 1, 1]]
Output: 0Creative 1 cannot be in the opposite cohort to itself, so not even the first report can be satisfied.
1 ≤ n ≤ 20,0000 ≤ len(reports) ≤ 20,0000 ≤ reports[i][0], reports[i][1] < n, and reports[i][2] is 0 or 1Colouring the graph again after each report costs about 40,000 steps for each of 20,000 reports, which is 800 million steps. Because adding a report can only make the plan harder, there is a single point where the plan first breaks. A binary search finds it with about 15 colourings.