A map contains n towns and directed edges connecting the two towns, which cannot form a loop. Now we have selected some town airborne soldiers (one town can have up to one soldier). The soldiers can come to the end along the road and ask at least a few soldiers who can traverse all the towns.
Idea: The Hungary algorithm calculates the minimum path overwrite: In a directed graph, path overwrite is to find some paths in the graph to overwrite all vertices in the graph, and any vertex has only one path associated with it. (If each path in these paths is taken from its start point to its end point, it can pass through each vertex in the graph once and only once). To solve this problem, you can create a bipartite graph model. Split all vertex I into two: I in the X node set and I in the Y node set. If edge I-> j exists, edge I-> j is introduced in the bipartite graph ', if the maximum matching value of a bipartite graph is m, the result is n-m.
Code:
[Cpp]
<Span style = "font-family: KaiTi_GB2312; font-size: 18px;" >#include <iostream>
Using namespace std;
Const int maxn = 125;
Int map [maxn] [maxn], visit [maxn], match [maxn];
Int n;
Bool dfs (int v)
{
Int I;
For (I = 1; I <= n; I ++)
{
If (map [v] [I] &! Visit [I])
{
Visit [I] = 1;
If (match [I] =-1 | dfs (match [I])
{
Match [I] = v;
Return true;
}
}
}
Return false;
}
Int hungry ()
{
Int I, ans = 0;
Memset (match,-1, sizeof (match ));
For (I = 1; I <= n; I ++)
{
Memset (visit, 0, sizeof (visit ));
If (dfs (I) ans ++;
}
Return ans;
}
Int main ()
{
Int I, t, j, a, B, ans, m;
Scanf ("% d", & t );
While (t --) www.2cto.com
{
Scanf ("% d", & n, & m );
Memset (map, 0, sizeof (map ));
For (I = 0; I <m; I ++)
{
Scanf ("% d", & a, & B );
Map [a] [B] = 1;
}
Ans = n-hungry ();
Printf ("% d % \ n", ans );
}
Return 0;
}
</Span>