您的位置:首页 > 其它

poj 1469(二分图最大匹配)

2014-02-20 18:49 519 查看
题意:学生和课程构成二部图,然后需要找到一个集合每个学生代表一门课,每一门课有一个学生代表。

思路:二分图入门题。当最大匹配等于课程数的时候可以找到集合。

代码如下:

/**************************************************
* Author     : xiaohao Z
* Blog     : http://www.cnblogs.com/shu-xiaohao/ * Last modified : 2014-02-20 17:48
* Filename     : poj_1469.cpp
* Description     :
* ************************************************/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
#define MP(a, b) make_pair(a, b)
#define PB(a) push_back(a)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<unsigned int,unsigned int> puu;
typedef pair<int, double> pid;
typedef pair<ll, int> pli;
typedef pair<int, ll> pil;

const int INF = 0x3f3f3f3f;
const double eps = 1E-6;
const int LEN = 1010;
vector<int> Map[LEN];
int n, match[LEN], vis[LEN];

bool dfs(int u){
vis[u] = 1;
for(int i=0; i<Map[u].size(); i++){
int v = Map[u][i], w = match[v];
if((!vis[w] && dfs(w)) || w < 0){
match[u] = v;
match[v] = u;
return true;
}
}
return false;
}

int hungary()
{
int ret = 0;
memset(match, -1, sizeof match);
for(int i=0; i<n; i++){
if(match[i] >= 0) continue;
memset(vis, 0, sizeof vis);
if(dfs(i)) ret ++;
}
return ret;
}

int main()
{
//    freopen("in.txt", "r", stdin);

int T, stu, cr, b;
scanf("%d", &T);
while(T--){
for(int i=0; i<LEN; i++) Map[i].clear();
scanf("%d%d", &cr, &stu);
for(int i=0; i<cr; i++){
int tn;
scanf("%d", &tn);
for(int j=0; j<tn; j++){
scanf("%d", &b);
b--;
Map[i].PB(cr+b);
Map[cr+b].PB(i);
}
}
n = cr + stu;
int ans = hungary();
if(ans == cr) printf("YES\n");
else printf("NO\n");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: