SRM 658 div1 850 DancingForever [二分图匹配]

Description:
n n 个男孩和n个女孩,每个男孩喜欢至少一个女孩。你需要给出一种配对方案,满足至少有一对,且每个配对的男孩和他喜欢的女孩配对且他喜欢的其他女孩都被配了对,输出任意一组解。


Solution:
如果直接跑匈牙利,那么不能符合。于是


#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
const int N = 205;
int match[N], vis[N];
vector<int> G[N];
bool dfs(int u) {
    if(vis[u]) {
        return false;
    }
    vis[u] = 1;
    for(int i = 0; i < G[u].size(); ++i) {
        int v = G[u][i];
        if(match[v] == -1 || dfs(match[v])) {
            match[v] = u;
            match[u] = v;
            return true;
        }
    }
    return false;
}
class DancingForever {
public:
vector <int> getStablePairs(string s) {
    int n = round(sqrt(s.size()));
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < n; ++j) {
            if(s[i * n + j] == 'Y') {
                G[i].push_back(j + n);
                G[j + n].push_back(i);
            }
        }
    }
    vector<int> ret;
    memset(match, -1, sizeof(match));
    for(int f = 1; f;) {
        f = 0;
        memset(vis, 0, sizeof(vis));
        for(int i = 0; i < n; ++i) {
            if(match[i] == -1 && dfs(i)) {
                f = 1;
            }
        }
    }
    int S = -1;
    for(int i = 0; i < n; ++i) {
        if(match[i] == -1) {
            S = i;
        }
    }
    if(S == -1) {
        for(int i = 0; i < n; ++i) {
            ret.push_back(i);
            ret.push_back(match[i] - n);
        }
    } else {
        memset(vis, 0, sizeof(vis));
        dfs(S);
        for(int i = 0; i < n; ++i) {
            if(match[i] != -1 && vis[i]) {
                ret.push_back(i);
                ret.push_back(match[i] - n);
            }
        }
    }
    return ret;
}

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值