EOJ 1864 二分图匹配

来源:互联网 发布:数据库自然连接 编辑:程序博客网 时间:2024/05/22 03:47

典型的二分图匹配。x集合是组成给定的字符串的字符,y集合是立方体。x中的元素i和y中的元素j有边当且仅当,立方体j中包含有i这个字符。

我们求出最大匹配数,如果最大匹配数等于|x|,则此字符串可以被立方体表示,反之不行。

另外改了一些代码中不好的风格,该加空格的地方都加上了,大括号也改成换行的了,规范代码,从现在做起~~

#pragma warning(disable:4996);#include <algorithm>#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>#include <queue>#include <new>#include <set>#include <map>using namespace std;typedef long long int LL;const double pi = (acos (-1));const int maxn = 100;int link[maxn], g[maxn][maxn];int used[maxn];char cubes[maxn][maxn];int n, m, nx, ny;//nx是x集合元素个数,ny同理bool contain (int i, char ch) //判断第i个立方体是否包含字符ch{for (int j = 0; j < strlen (cubes[i]); j++){if (cubes[i][j] == ch) return true;}return false;}bool dfs (int u){for (int v = 1; v <= ny; v++){if (g[u][v] && !used[v]){used[v] = 1;if (link[v] == -1 || dfs (link[v])) {link[v] = u;return true;}}}return false;}int maxmatch (){int res = 0;memset (link, -1, sizeof (link));for (int i = 1; i <= nx; i++) {memset (used, 0, sizeof (used));if (dfs (i)) res++;}return res;}int main (){//freopen("D:\\Test_in.txt", "r", stdin);//freopen("D:\\Test_out.txt", "w", stdout);while (scanf ("%d%d\n", &n, &m) == 2) {for (int i = 1; i <= n; i++){scanf ("%s", cubes[i]);}vector<int> ans;char a[50];for (int i = 0; i < m; i++) {scanf ("%s", a);memset (g, 0, sizeof (g));for (int j = 0; j < strlen (a); j++){for (int k = 1; k <= n; k++) {if (contain (k, a[j]))g[j + 1][k] = 1;}}nx = strlen(a);ny = n;int res = maxmatch ();if (res == nx) ans.push_back (i);}int len = ans.size ();if (!len)printf ("-1\n");else {for (int i = 0; i < len; i++) printf ("%d%c", ans[i], i < len - 1 ? '  ' : '\n');}}return 0;}


0 0
原创粉丝点击