二分圖匹配——POJ3041

題目描述:

n*n的地圖上有k個小行星。每次攻擊可以消滅一行或者一列行星,問最少需要多少次攻擊能全部消滅行星。

大致思路:

對於每個行星可以選擇橫向攻擊,或者縱向攻擊,這樣建邊之後整張圖就變成了二分圖,而最後的答案求解就變成了二分圖最大匹配。

代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

#define CLR(a,b) memset(a,b,sizeof(a))
#define RD(x) scanf("%d",&x)

const int maxn = 1010;
int V;
vector<int> G[maxn*2];
int match[maxn*2];
bool used[maxn*2];

void add_edge(int u,int v) {
    G[u].push_back(v);
    G[v].push_back(u);
}

bool dfs(int v) {
    used[v] = true;
    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 true;
        }
    }
    return false;
}

int bipartite_matching() {
    int res = 0;
    CLR(match,-1);
    for (int v = 0; v < V; v++) {
        if (match[v] < 0) {
            CLR(used,0);
            if (dfs(v)) {
                res++;
            }
        }
    }
    return res;
}

int N,K;
int R[maxn*10],C[maxn*10];

void solve() {
    V =N * 2;
    for (int i = 0; i < K; i++) {
        add_edge(R[i] - 1,N + C[i] - 1);
    }
    cout<<bipartite_matching()<<endl;
}

int main() {
    while (cin>>N>>K) {
        for (int i = 0; i < K; i++) {
            RD(R[i]);RD(C[i]);
        }
        solve();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章