Handshakes in a party
Practice
3.3 (6 votes)
Graphs
Algorithms
Breadth First search
Problem
67% Success 493 Attempts 30 Points 5s Time Limit 256MB Memory 1024 KB Max Code

You are organizing a new year's party and you have invited a lot of guests. Now, you want each of the guests to handshake with every other guest to make the party interactive. Your task is to know what will be the minimum time by which every guest meets others. One person can handshake with only one other person at once following the handshake should be of 3 seconds sharp.

You have prepared some data for each guest which is the order in which the $$Guest(i)$$ will meet others. If the data is inconsistent, then print -1. Otherwise, print the minimum time in seconds.

Hint: The data will be inconsistent if the handshake sequence of one person contradicts with another person, for instance:

4
2 3 4
3 1 4
4 1 2
1 3 2

$$G(1)$$ wants to meet $$G(2)$$ first, but $$G(2)$$ will meet $$G(1)$$ after meeting $$G(3)$$.
$$G(3)$$ will be meeting $$G(2)$$ after meeting $$G(4)$$ and $$G(1)$$ respectively while $$G(4)$$ will meet $$G(3)$$ after meeting $$G(1)$$ and $$G(1)$$ will meet $$G(4)$$ only after meeting $$G(2)$$ and $$G(3)$$. Hence, no one will be able to shake hands following this order as each handshake require some prior handshakes to happen. 

Note: G(i) denotes the \(i^{th}\) guest.

Input format

  • The first line will contain an integer \(N\) denoting the number of guests invited.
  • Next \(N\) lines will container \(N-1\) integers where the \(i^{th}\) line will denote the sequence in which$$ Guest(i)$$ met other guests.

Output format

If the input data is inconsistent, print -1. Otherwise, print the minimum time required for the handshakes (in seconds).

Constraints

\(1 \le G(i) \le N \le 1000\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
14 votes
Tags:
AlgorithmsBreadth First SearchGraphsMedium
Points:30
25 votes
Tags:
AlgorithmsApprovedBreadth First SearchGraphsMediumOpenRecursion
Points:30
21 votes
Tags:
AlgorithmsBreadth First SearchGraphs