I learnt Tarjan’s algorithm in this video. Very good visualization.
First we find all the strongly conncted components in the given relationship graph. All the vetices in the same component can be treated as one point in the graph so we could get a DAG. The cows which is considered popular by all other cows are cows in the SCC with 0 out-degree. If there are more than one SCCs with 0 out-degree the answer is 0, otherwise the anser the number of cows in that SCC.
Some details in the implementation:
I used the low value as the id of each vetices so all the vertices in the same SCC can be seen as one point.
low values are now consecutive so when you encounter one low value with 0 out-degree, you have to change its out-degree to a none-zero value in case you count it again.