MAKETREE  Hierarchy
A group of graduated students decided to establish a company; however, they don't agree on who is going to be who's boss.
Generally, one of the students will be the main boss, and each of the other students will have exactly one boss (and that boss, if he is not the main boss, will have a boss of his own too). Every boss will have a strictly greater salary than all of his subordinates  therefore, there are no cycles. Therefore, the hierarchy of the company can be represented as a rooted tree.
In order to agree on who is going to be who's boss, they've chosen K most successful students, and each of them has given a statement: I want to be the superior of him, him, and him (they could be successful or unsuccessful). And what does it mean to be a superior? It means to be the boss, or to be one of the boss' superiors (therefore, a superior of a student is not necessary his direct boss).
Help this immature company and create a hierarchy that will satisfy all of the successful students' wishes. A solution, not necessary unique, will exist in all of the test data.
Input
In the first line of input, read positive integers N (N ≤ 100 000), total number of students, and K (K < N), the number of successful students. All students are numbered 1..N, while the successful ones are numbered 1..K.
Then follow K lines. In A^{th} of these lines, first read an integer W (the number of wishes of the student A, 1 ≤ W ≤ 10), and then W integers from the range [1, N] which denote students which student A wants to be superior to.
Output
Output N integers. The A^{th} of these integers should be 0 if student A is the main boss, and else it should represent the boss of the student A.
Example
Input:
4 2Output:
1 3
2 3 42
0
1
2
Input:7 4Output:
2 2 3
1 6
1 7
2 1 24
1
1
0
4
2
3
hide comments
Gaurav Dahima:
20161007 10:16:49
Surprisingly AC in 2nd go (First one was TLE due to cin).


hodobox:
20160903 07:59:32
O(nlogn) requires constant optimization :/ 

kartikay singh:
20160701 10:09:20
Topological sorting :) 

Projjal Kundu:
20151215 12:55:36
Is it a binary tree? or we can assume any general tree 

sahni:
20150117 12:25:47
100th one :):P 

Aditya Joshi:
20141124 15:49:27
Increase the time limit. Not a single solution in Java. I am getting TLE even though my approach complexity is what is expected. 

DP:
20140722 03:54:36
Was getting TLE, changed cin to scanf and cout to printf. Got AC. 

parbays:
20140122 19:14:16
Phew...wasted my time, where mistakenly a cout n times was causing TLE. 

Bharat Jain:
20130720 18:36:47
any more test case ?? 

Pranay:
20121029 05:58:32
@Adrian : Could you please tell why WA (id: 7953672) ? Also Can't there be 2 main bosses ? E.g for case 1 , can't the answer be 0 0 2 2 ? Last edit: 20121029 07:01:37 
Added by:  Adrian Satja Kurdija 
Date:  20110415 
Time limit:  0.119s 
Source limit:  50000B 
Memory limit:  1536MB 
Cluster:  Cube (Intel G860) 
Languages:  All except: ASM64 
Resource:  own problem 