Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 16211 | Accepted: 8819 |
Description
Fortunately, Bessie has a powerful weapon that can vaporize all the asteroids in any given row or column of the grid with a single shot.This weapon is quite expensive, so she wishes to use it sparingly.Given the location of all the asteroids in the field, find the minimum number of shots Bessie needs to fire to eliminate all of the asteroids.
Input
* Lines 2..K+1: Each line contains two space-separated integers R and C (1 <= R, C <= N) denoting the row and column coordinates of an asteroid, respectively.
Output
Sample Input
3 4
1 1
1 3
2 2
3 2
Sample Output
2
Hint
The following diagram represents the data, where "X" is an asteroid and "." is empty space:
X.X
.X.
.X.
OUTPUT DETAILS:
Bessie may fire across row 1 to destroy the asteroids at (1,1) and (1,3), and then she may fire down column 2 to destroy the asteroids at (2,2) and (3,2).
Source
#include<stdio.h>
#include<string.h>
const int M = ;
bool map[M][M] ;
int girl[M] ;
bool sta[M] ;
int n , m; bool hungary (int x)
{
for (int i = ; i <= n ; i++) {
if (map[x][i] && sta[i] == false) {
sta[i] = true ;
if (girl[i] == || hungary (girl[i])) {
girl[i] = x ;
return true ;
}
}
}
return false ;
} int main ()
{
// freopen ("a.txt" , "r" , stdin) ;
while (~ scanf ("%d%d" , &n , &m)) {
int x , y , k = ;
memset (map , , sizeof(map)) ;
memset (girl , , sizeof(girl)) ;
for (int i = ; i < m ; i++) {
scanf ("%d%d" , &x , &y) ;
map[x][y] = ;
}
int all = ;
for (int i = ; i <= n ; i++) {
memset (sta , , sizeof(sta)) ;
if (hungary (i))
all++ ;
}
printf ("%d\n" , all) ;
}
return ;
}
最小覆盖点 = 最大搭配数 。(匈牙利就是求最大搭配数)
#include<bits/stdc++.h>
using namespace std;
const int M = ;
int n ;
bool vis[M] ;
int from[M] ;
vector<int> g[M] ;
int tot ; bool match (int u) {
for (int i = ; i < g[u].size () ; i ++) {
int v = g[u][i] ;
if (!vis[v] ) {
vis[v] = ;
if (from[v] == - || match (from[v] ) ) {
from[v] = u ;
return true ;
}
}
}
return false ;
} int hungary () {
memset (from , - , sizeof(from )) ;
for (int i = ; i <= n ; i ++) {
memset (vis , , sizeof(vis)) ;
if (match (i) )
tot ++ ;
}
return tot ;
}
匈牙利模板
补充定义和定理:
最大匹配数:最大匹配的匹配边的数目
最小点覆盖数:选取最少的点,使任意一条边至少有一个端点被选择
最大独立数:选取最多的点,使任意所选两点均不相连
最小路径覆盖数:对于一个 DAG(有向无环图),选取最少条路径,使得每个顶点属于且仅属于一条路径。路径长可以为 0(即单个点)。
定理1:最大匹配数 = 最小点覆盖数(这是 Konig 定理)
定理2:最大匹配数 = 最大独立数
定理3:最小路径覆盖数 = 顶点数 - 最大匹配数