Minimum path Overwrite for poj 1422

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.