poj1274 The Perfect Stall(二分图匹配)

题意

有n个奶牛和m个谷仓,现在每个奶牛有自己喜欢去的谷仓,并且它们只会去自己喜欢的谷仓吃东西,问最多有多少奶牛能够吃到东西。
输入第一行给出n与m
接着n行
每行第一个数代表这个奶牛喜欢的谷仓的个数s,后面接着s个数代表这个奶牛喜欢哪个谷仓

思路

典型的二分图匹配,n头牛和m个谷仓都抽象成点,如果某头牛喜欢某个谷仓的话就连一条边,然后求二分匹配。思维上没什么特殊的地方,这里实现上我用的是匈牙利算法,对于整个图,分别是矩阵表示和临接表(前向星)表示。

代码

矩阵

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

const int kMaxn = 200 + 5;

bool g[kMaxn][kMaxn];
int match[kMaxn];
bool vis[kMaxn];

int n,m;

bool Dfs(int u) {
  for(int v = 1; v <= m; v++) {
    if(!vis[v] && g[u][v]) {
      vis[v] = true;
      if(match[v] == -1 || Dfs(match[v])) {
        match[v] = u;
        return true;
      }
    } 
  }
  return false;
}

int MaxMatch() {
  memset(match, -1, sizeof(match));
  int ans = 0;
  for(int i = 1; i <= n; i++) {
    memset(vis, false, sizeof(vis));
    ans += Dfs(i);
  }
  return ans;
}

int main() {
  while(~scanf("%d %d", &n, &m)) {
    memset(g, false, sizeof(g));
    for(int i = 1; i <= n; i++) {
      int s;
      scanf("%d", &s);
      while(s--) {
        int x;
        scanf("%d", &x);
        g[i][x] = true;
      }
    }
    printf("%d\n", MaxMatch());
  }
  return 0;
}

前向星

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

const int kMaxn = 200 + 5;

struct Edge {
  int from,to;
  int next;
}g[kMaxn * kMaxn];

int head[kMaxn];
int match[kMaxn];
bool vis[kMaxn];

int n,m;
int top;

void Init() {
  memset(head, -1, sizeof(head));
  top = 0;
}

void AddEdge(int from, int to) {
  g[top] = (Edge){from, to, head[from]};
  head[from] = top++;
}

bool Dfs(int u) {
  for(int i = head[u]; i != -1; i = g[i].next) {
    int v = g[i].to;
    if(!vis[v]) {
      vis[v] = true;
      if(match[v] == -1 || Dfs(match[v])) {
        match[v] = u;
        return true;
      }
    }
  }
  return false;
}

int MaxMatch() {
  memset(match, -1, sizeof(match));
  int ans = 0;
  for(int i = 1; i <= n; i++) {
    memset(vis, false, sizeof(vis));
    ans += Dfs(i);
  }
  return ans;
}

int main() {
  while(~scanf("%d %d", &n , &m)) {
    Init();
    for(int i = 1; i <= n; i++) {
      int s;
      scanf("%d", &s);
      while(s--) {
        int x;
        scanf("%d", &x);
        AddEdge(i, x);
      }
    }
    printf("%d\n", MaxMatch());
  }
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值