Question:
A matrix of N * n. Each lattice has some planets. It has a special weapon that can destroy one row or one column at a time and ask the minimum number of such weapons used to destroy all the planets.
Diagram:
At the beginning, we thought that the Minimum side covers all vertices. This side is either a parallel X axis or a parallel Y axis.
Obviously, this side cannot be composed, and the start and end points are unknown.
Since the side of the Y axis cannot be constructed because of the parallel X axis, can the side of the parallel X axis or Y axis regard it as a point?
It is also divided into two sets, one set X (1-N), one set Y (1-N), one point (a, B) is from the point A in the X set
Link an edge to B in set Y. Such a definition diagram fully complies with the definition of a bipartite graph.
Bipartite Graph definition:
1. It can be divided into two sets, one X and one y.
2. The two endpoints of any edge belong to different sets.
3. No edge exists in any set.
After the diagram is complete, the problem to be solved is how to overwrite all edges with the least points.
The Hungarian algorithm is used to find the answer for the maximum matching of the Bipartite Graph,
That is, the minimum coverage point = the maximum match. Verify http://www.matrix67.com/blog/archives/116
View code
#include<stdio.h>#include<string.h>#include<stdlib.h>int N, M;int mp[510][510];int match[510];bool color[510];int find( int x ){ for( int i = 1; i <= N; i++) { if( !color[i] && mp[x][i] ) { color[i] = true; if( match[i] == -1 || find( match[i] )) { match[i] = x; return 1; } } } return 0;}void solve( ){ int ans = 0; memset(match,-1,sizeof(match)); for( int i = 1; i <= N; i++) { memset(color, 0, sizeof(color)); if( find(i) ) ans++; } printf("%d\n",ans);}int main( ){ int a, b; while( scanf("%d%d", &N, &M) != EOF) { for( int i = 1; i <= N; i++) for( int j = 1; j <= N; j++) mp[i][j] = 0; for( int i = 1; i <= M; i++) { scanf("%d%d",&a,&b); mp[a][b] = 1; } solve( ); } return 0;}