POJ 3041 Asteroids二分图匹配

A s t e r o i d s Asteroids

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 27731 Accepted: 14862

Description

Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N grid (1 <= N <= 500). The grid contains K asteroids (1 <= K <= 10,000), which are conveniently located at the lattice points of the grid.

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

  • Line 1: Two integers N and K, separated by a single space.
  • 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

  • Line 1: The integer representing the minimum number of times Bessie must shoot.
    Sample Input

3 4
1 1
1 3
2 2
3 2
Sample Output

2

Hint

INPUT DETAILS:
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

USACO 2005 November Gold

题目大意:

给一张n*n的图,然后给出图上各个障碍物的坐标,每次操作可以消除一行或者一列的障碍物,问消除全部的障碍物最少需要多少次操作。

浅析

基本上算是二分图匹配的模板题了。
仔细思考一下,可以发现消除一行就是把横坐标为x的全部都删掉,而删除一列就是把纵坐标为y的全部删掉。我们把坐标图上的横坐标各表示成一个点,纵坐标做同样的处理,
然后对每个障碍物的坐标( x , y ),把横坐标x对应的点和纵坐标y对应的点连起来。
问题就转化成了:给出一个二分图和连边,求最少的点覆盖所有的连边,也就是二分图的最小点覆盖的问题了。
二分图的 最小点覆盖=最大匹配 所以跑一边匈牙利就可以了。

#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int maxn = 1111;
int used[maxn],match[maxn];//访问标记,匹配对象
int n,m;
vector<int> G[maxn];
void add_edge(int u,int v){
    G[u].push_back(v+n);
    G[v+n].push_back(u);
}
void input(){               //输入
    scanf("%d %d",&n,&m);
    for(int i=1;i<=m;i++){
        int u,v;
        scanf("%d %d",&u,&v);
        add_edge(u,v);
    }
}
bool dfs(int cur){
    used[cur] = 1;
    for(int i=0;i<G[cur].size();i++){
        int u = G[cur][i];
        if(!used[match[u]]&&(match[u]==0||dfs(match[u]))){     
            match[cur] = u;
            match[u] = cur;
            return true;
        }
    }
    return false;
}
int Max_comp(){
    int ans = 0;
    for(int i=1;i<=n;i++){
        if(!match[i]){
            memset(used,0,sizeof(used));
            if(dfs(i)) ans++;
        }
    }
    return ans;
}
int main(){
    input();
    printf("%d\n",Max_comp());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43710979/article/details/89489248