poj 2239 Selecting Courses

本文介绍了一种解决课程调度问题的方法,通过构建二分图并利用网络流或匈牙利算法来寻找最大匹配,确保课程与时间不冲突。

poj.org/problem?id=2239

A集合代表课程 B集合代表 这就是一个二分图 由于课程和时间必须一一对应不能重叠 因此是二分图的最大匹配问题。做法有两种:

1.网络流的特殊化

建立一个S和T,S连课程,课程连时间,时间连T,每条边的流量都是1,则最大流就是最大匹配数。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAXV = 1010;
int S,T;
int n,G[MAXV][MAXV];
int pre[MAXV],Q[MAXV],h,t;

bool BFS(){
    memset(pre, -1, sizeof(pre));
    h = 0, t = 1, Q[1] = S;
    while(h < t){
        int u = Q[++h];
        for(int i=0; i<=T; i++){
            if(G[u][i] > 0 && pre[i] == -1){
                pre[i] = u;
                Q[++t] = i;
                if(i == T) return true;
            }
        }
    }
    return false;
}

int EK(){
    int maxflow = 0;
    while(BFS()){
        for(int i=T; i!=S; i=pre[i]){
            G[pre[i]][i]--;
            G[i][pre[i]]++;
        }
        maxflow++;
    }
    return maxflow;
}

int main(){
    while(scanf("%d",&n) == 1){
        memset(G, 0, sizeof(G));
        S = 0, T = 7*12+n+1;
        for(int i=1; i<=n; i++){
            int num;
            scanf("%d",&num);
            G[S][i] = 1;
            while(num--){
                int p,q;
                scanf("%d%d",&p,&q);
                G[i][n+(p-1)*12+q] = 1;
                G[n+(p-1)*12+q][T] = 1;
            }
        }
        int ans = EK();
        printf("%d\n",ans);
    }
    return 0;
}

2.匈牙利算法

如果某一轮点i无法成功增广的话 那么之后无论找到多少条增广路都不会有含有i的。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAXV = 1010;
const int B = 84;

int G[MAXV][MAXV];
int check[MAXV],ca[MAXV],cb[MAXV];
//check[]记录B集合中的点是否被扫描过,ca[],cb[]分别记录与A,B集合中的点匹配的点
int A;

int DFS(int u){//A集合中的点u
    for(int v=1; v<=B; v++){
        if(G[u][v] > 0 && !check[v]){
            check[v] = 1;
            if(cb[v] == -1 || DFS(cb[v])){//B集合中的点v还没有匹配或v点之前匹配的点可以找到新的匹配的点
                ca[u] = v;
                cb[v] = u;
                return 1;//代表此次匹配成功
            }
        }
    }
    return 0;
}

void Hungarian(){
    int res = 0;
    memset(ca, -1, sizeof(ca));
    memset(cb, -1, sizeof(cb));
    for(int i=1; i<=A; i++){
        if(ca[i] != -1) continue;//从A集合中还未匹配的点进行匹配  
        memset(check, 0, sizeof(check));
        res += DFS(i);
    }
    printf("%d\n",res);
}

int main(){
    while(scanf("%d",&A) == 1){
        memset(G, 0, sizeof(G));
        int num,p,q;
        for(int i=1; i<=A; i++){
            scanf("%d",&num);
            while(num--){
                scanf("%d%d",&p,&q);
                G[i][(p-1)*12+q] = 1;
            }
        }
        Hungarian();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值