Time limit
2s
Memory limit
128 MB
King Dohyun of Tteokguk wants to hire more guards to protect the cities in his country. There are K guard companies, and each company has offices only in some cities.
To newly place a guard from company B in city A, company B must have an office in city A. Guards that are already placed cannot be moved or dismissed, but any number of new guards may be hired as long as this rule is followed.
When two cities cooperate, a conflict occurs for one company if that company's guard is present in exactly one of the two cities. Since one city may have guards from several companies, a single pair of cooperating cities may create several conflicts.
You are given the cooperation relationships, the companies of the guards already placed in each city, and the companies that have offices in each city. Add guards so that the total number of conflicts is as small as possible.
The first line contains the number of cities N. (1 <= N <= 50)
The next N lines give the cooperation relationships as an adjacency matrix. 0 means the two cities do not cooperate, and 1 means they do. If the matrix is A, then A[i][i] = 0 and A[i][j] = A[j][i].
The next line contains the number of guard companies K. (1 <= K <= 50)
The following N lines describe cities 0 through N - 1 in order. Each line gives the number of guards already placed in that city, followed by the company numbers of those guards. Company numbers start at 0.
The final N lines describe cities 0 through N - 1 in order. Each line gives the number of guard-company offices in that city, followed by the company numbers that have offices there.
Print the minimum possible total number of conflicts after adding guards.
Each company can be considered independently. For one company, cities that already have its guard must be selected, while cities with neither an existing guard nor an office cannot be selected. Minimize the number of cooperation edges whose endpoints are on different sides.
In the first public test, adding company 0 guards to cities 1 and 3 leaves a conflict only between cities 0 and 2. The minimum for the fourth public test is 7.