Question http://poj.org/problem here? Id = 3041
I have been learning algorithms because I am looking for a job recently. But I think the most difficult thing for a beginner is not to understand an algorithm. The second is how to model the question programming algorithm, compile the program. I personally think that this process should rely on more questions, more analysis, and cultivate their own sources of inspiration.
The general meaning of this question is that in an N * n matrix, there are several meteorite, and the ship's cannon can destroy a row or column at a time, ask how to minimize the number of gun launches, but eliminate all the meteorite.
Question Analysis:
You can convert rows and columns as follows:
In the preceding figure, the left graph indicates the row number, and the right graph indicates the column number. If there is a meteorite on (I, j), we connect row I to column J.
In this way, each edge represents a meteorite. If I launch a gun on line 1, all the edges connected to line 1 will be eliminated. Therefore, this problem is converted to the minimum coverage problem.
Introduce the point theory. In the bipartite graph:
Matching:
Given a bipartite graph, in a subgraph G' of G, if any two edges in the edge set of G are not attached to the same vertex, then, the edge set called G' is a matching of G.
Maximum match:
Among all the matches, the matching with the largest number of edges is the maximum matching of the Bipartite Graph.
Vertex coverage:
In the vertex set, select a part of the vertex, which can overwrite all the edges. These vertices are vertex overwrites.
Minimum vertex coverage:
In all vertex overwrites, the smallest vertex set is called the smallest vertex set.
König theorem for maximum matching of bipartite graphs
Maximum match = minimum vertex overwrite. This does not prove its correctness.
Then we write the program as follows:
#include <stdio.h>#include <memory.h>#define GRID_NUM 505int Grid[GRID_NUM][GRID_NUM];int matched[GRID_NUM];bool visited[GRID_NUM];int nGrid;bool dfs(int from){int i;for( i = 0;i < nGrid; i++){if(!visited[i] && Grid[from][i]){visited[i] = true;if(matched[i] == -1 || dfs(matched[i])){matched[i] = from;return true;}}}return false;}int main(){int nAstroid, j;int f, t;while(scanf("%d%d", &nGrid, &nAstroid) != EOF){memset(Grid, 0, sizeof(Grid));memset(matched, -1, sizeof(matched));for(j = 0; j < nAstroid; j++){scanf("%d%d", &f, &t);Grid[f-1][t-1] = 1;}int nIncrement = 0;for( j = 0; j < nGrid; j++){memset(visited, 0, sizeof(visited));if(dfs(j)){nIncrement++;}}printf("%d\n", nIncrement);}return 0;}