Description:
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;
}
};