Magic Trees
Time limit2sMemory limit512 MB
Given a directed graph, repeatedly pick a vertex to mark magic and let magic or protected vertices protect their out-neighbors; maximize magic and unprotected vertices.
Problem
Dohyun has one incubator, and it turns a tree into a magic tree.
There are trees in Dohyun's flower bed, numbered 1 to . Some trees like other trees. Liking is not symmetric, and a tree can like itself. If tree likes tree then , and otherwise .
Every tree has two attributes. isMagical is True when the tree is a magic tree and False otherwise. isProtected is True when some other tree protects it and False otherwise. At the start, isMagical and isProtected are False for every tree.
Dohyun can pick one tree and change its isMagical from False to True. Turning one tree into a magic tree sets off the following changes in a chain.
- A tree whose isMagical is True protects every tree it likes. That is, if , the isProtected of tree becomes True.
- A tree whose isProtected is True protects every tree it likes. That is, if , the isProtected of tree becomes True.
The changes keep going until no tree changes any more. Once they are finished, Dohyun turns one more tree into a magic tree. He repeats this as many times as he wants.
Dohyun wants the largest possible number of trees that are magic and unprotected, meaning trees whose isMagical is True and whose isProtected is False. Write a program that finds that maximum.
Input
The first line contains the number of trees ().
Each of the next lines contains a string of length made of 0 and 1. The -th character of the -th line is .
Output
Print the largest possible number of trees that are magic and unprotected.
Hint
With two trees where only tree 1 likes tree 2, turn tree 1 into a magic tree. Tree 1 is then magic and unprotected.
With three trees where tree 1 likes tree 2 and tree 2 likes tree 3, turn tree 3 into a magic tree first, then turn tree 1 into a magic tree. Tree 1 protects tree 2 and tree 2 protects tree 3. Tree 1 is magic and unprotected, tree 2 is an ordinary tree and protected, and tree 3 is magic and protected.