Vivek and party

What will the output for the test case:
8
b
f
e
t
d
a
s
c
6
a e
a b
c d
e f
s t
a t


the output for the above input shall be
a b e f s t c d

What am I doing wrong in the above code?

You haven’t considered the fact that when there is no order b/w the two drinks you need to drink first the one which came first in the input. For the above testcase -

8
b
f
e
t
d
a
s
c
6
a e
a b
c d
e f
s t
a t

Lets see the order b f e t d a s c
You can’t drink b f e t d as you can see in the graph above. (They have more alcohol content)
So you drink a.
but after this you can see you can drink e b s c but you need to drink b as it came first in the input.
So you drink b.
and you need to continue doing this.
I hope you get my point.
(Please refer to the graph above while reading this.)

My code is giving correct answer for this TC. But I am getting TLE.

You can have a look at this code for an idea

I am not able to explain your code.Can you please explain it to me.

In topologicalSort() function why did you started dfs from last vertex.

And why did you make graphmap as this “map<int, set, greater> graphMap”

There are different ways of making a graph. You can use adj. matrix or adj. list or use sets /maps anything.
You implement it in your way…

There are two ways of doing topological sort. Please go through topological sort videos.
When you do a dfs, there is no difference in iterating from first node or last node.

Algo you have to use:
1.Do a topological sort.
2. if 2 nodes are independent, print them in lexicographical order.

I hope its easy to understand now and you can implement code now :slight_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.