Ensure that you are logged in and have the required permissions to access the test.

Handshakes in a party

3.3

6 votes
Graphs, Algorithms, Breadth-first search
Problem

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 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

wants to meet first, but will meet after meeting .
will be meeting after meeting and respectively while will meet after meeting and will meet only after meeting and . 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 guest.

Input format

  • The first line will contain an integer denoting the number of guests invited.
  • Next lines will container integers where the  line will denote the sequence in which 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

Sample Input
4
2 3 4
1 3 4
4 1 2
3 1 2
Sample Output
12
Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

In the first 3 second the guest (1,2) and (3,4) will meet each other.
In next 3 seconds, guest (1,3) will meet.
In next 3 seconds, guest (1,4) and (2,3) will meet.
In next 3 seconds, guest (2,4) will meet.
So, it will take 12 seconds for every guest to meet others.

Editor Image

?