poj 1469 COURSES

题意:给出p个课程,n个学生,问能否满足每个学生选一门不同的课,且每个课程有一个学生。


分析:把这个问题看成二分图来做的话,简直就是裸题~。求出最大匹配看是否和p相等,相等输出YES,否则输出NO。

第一道二分图,用了匈牙利算法求出了最大匹配。


以下附上代码:


#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cctype>
#include <cmath>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <set>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;

const int maxn = 305;


int g[maxn][maxn];
int p,n;
int t;

int cx[maxn],cy[maxn];//cx->student cy->course
bool vis[maxn];// 

void input()
{
  int i,j;
  int k;
  int v;
  
  for(i = 0; i < maxn; i++){
    for(j = 0; j < maxn; j++){
      g[i][j] = 0;
    }
  }
  
  scanf("%d%d",&p,&n);
  for(i = 1; i <= p; i++){
    scanf("%d",&k);
    for(j = 0; j < k; j++){
      scanf("%d",&v);
      g[v][i] = 1;
    }
  }
  
}

//寻找可增广轨增广 
int path(int u)
{
  for(int v = 1; v <= p; v++){
    if(g[u][v] && !vis[v]){
      vis[v] = 1;
      if(cy[v] == -1 || path(cy[v])){
        cx[u] = v;
        cy[v] = u;
        return 1;//找到可增广轨 
      }
    }
  }
  return 0;//不存在可增广轨 
}

//匈牙利算法 
int maxMatch()
{
  int res = 0;
  fill(cx,cx+maxn,-1);
  fill(cy,cy+maxn,-1);
  
  for(int i = 1; i <= n; i++){
    if(cx[i] == -1){//当前没匹配 
      fill(vis,vis+maxn,0);
      res += path(i);
    }
  }
  return res;
}


bool solve()
{
  return maxMatch() == p;
}



int main()
{
  scanf("%d",&t);
  while(t--){
    input();
    puts(solve() ? "YES" : "NO");
  }
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值