hdu 1845 Jimmy’s Assignment

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1845

解题思路:

最大二分匹配,模板题,其实题目说 This graph is undirected, has N vertices and each vertex has degree 3. Furthermore, the graph is 2-edge-connected。就能得到答案为n/2。但是为了熟悉模板,还是把模板敲了一遍。。。

注意:用G++交,看人品,有时能过,C++能过。。。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <map>
using namespace std;

const int MAX_V = 5005;
int n;//顶点数
vector<int> G[MAX_V];//图的邻接表表示
int match[MAX_V];//所匹配的顶点
bool used[MAX_V];//DFS中甬道的访问标记


//通过DFS寻找增广路
bool dfs(int u){
    used[u] = true;
    for(int i = 0; i < G[u].size(); i++){
        int v = G[u][i],w = match[v];
        if(w < 0 || !used[w] && dfs(w)){
            match[v] = u;
            return true;
        }
    }
    return false;
}

//求解二分图的最大匹配
int bipartite_matching(){
    int res = 0;
    memset(match,-1,sizeof(match));
    for(int v = 1; v <= n; v++){
        memset(used,0,sizeof(used));
        if(dfs(v))
            res++;
    }
    return res;
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        int m,u,v;
        scanf("%d",&n);
        for(int i = 1; i <= n; i++)
            G[i].clear();
        m = 3*n/2;
        for(int i = 0; i < m; i++){
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
            G[v].push_back(u);
        }
        printf("%d\n",bipartite_matching()/2);
    }
    return 0;
}


你可能感兴趣的:(最大二分匹配)