Roadside optimization
InterviewTime limit1sMemory limit256 MB
Given a graph as an adjacency matrix of reachability, find the minimum number of roads to keep so that all reachability relations stay the same.
- Level
Medium4 of 10
- Topics
- Graph, Union-find, Implementation, Math
- Solved
- No attempts yet
Problem
Some towns in the province are connected by roads, and roads always run both ways. The budget for maintaining the road network is scarce, so it was decided to keep only the minimum number of roads. However, if it is currently possible to reach town from town , this must remain possible even after the reduction.
Determine the minimum number of roads that must be kept.
Input
The first line of the input file contains a single integer , the number of tests (). The descriptions of tests follow.
The first line of test contains a single integer , the number of towns ().
The next lines contain integers each, and every integer is either or . If the th position of line is , then town cannot be reached from town (not even by passing through other towns); if it is , then there is a passage. A passage from a town to itself is assumed, so the th position of line is always ().
The sum of over all tests is guaranteed not to exceed .
Output
For each test, print the minimum number of roads to be kept on a separate line.