POJ 3041 Asteroids (二分图匹配)

【题目链接】 http://poj.org/problem?id=3041

【题目大意】

  一个棋盘上放着一些棋子
  每次操作可以拿走一行上所有的棋子或者一列上所有的棋子
  问几次操作可以拿完所有的棋子

【题解】

  每个棋子相当于是连接行列二分图的边,我们做一遍二分图匹配就是答案。

【代码】

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector> 
using namespace std;
const int MAX_V=1000;
int V,match[MAX_V];
vector<int> G[MAX_V];
bool used[MAX_V];
void add_edge(int u,int v){
    G[u].push_back(v);
    G[v].push_back(u);
}
bool dfs(int v){
    used[v]=1;
    for(int i=0;i<G[v].size();i++){
        int u=G[v][i],w=match[u];
        if(w<0||!used[w]&&dfs(w)){
            match[v]=u;
            match[u]=v;
            return 1;
        }
    }return 0;
}
int bipartite_matching(){
    int res=0;
    memset(match,-1,sizeof(match));
    for(int v=0;v<V;v++){
        if(match[v]<0){
            memset(used,0,sizeof(used));
            if(dfs(v))res++;
        }
    }return res;
}
const int MAX_K=10000;
int N,K;
int R[MAX_K],C[MAX_K];
void solve(){
    V=N*2;
    for(int i=0;i<K;i++)add_edge(R[i]-1,N+C[i]-1);
    printf("%d
",bipartite_matching());
}
void init(){
    scanf("%d",&K);
    for(int i=0;i<K;i++)scanf("%d %d",&R[i],&C[i]);
}
int main(){
    while(~scanf("%d",&N)){
        init();
        solve();
    }return 0;
}
原文地址:https://www.cnblogs.com/forever97/p/poj3041.html