Description
Children are used to playing with special cubes with letters written on thecubes‘ faces. The goal of the game is to compose words using such cubes. If youwant to compose the word "DOG", you must find 3 cubes, one containingthe letter ‘D‘, one containing the
letter ‘O‘, and one containing the letter‘G‘, and orient them so the proper letters are facing upward.
You are also given a some words, each element of which contains a word that youwould like to spell out using the cubes.
Input
There are several test cases,each test case begins with two numbersN(1<=N<=50) and M(1<=M<=50).the second line contains N string,thei-th string shows the uppercase letters(between 2 and 50,inclusive) on the i-thcube.The third line contains the M words.Each
element of words will containbetween 2 and 50 uppercase letters, inclusive.
Output
Output the words‘ number that can be composed using the given cubes inascending order. If no words‘ number that can be composed output -1.
Sample Input
5 3
ABCDEF DEFGHI OPQRST ZZZZZZ YYYYYY
CAT DOG PIZZA
6 7
ABCDEF DEFGHI OPQRST MNZLSA QEIOGH IARJGS
DOG CAT MOUSE BIRD CHICKEN PIG ANIMAL
Sample Output
1
0 1 3 5
Hint
Case 1:
We can form the word "DOG" using ‘D‘ from the first cube, ‘O‘ fromthe third and ‘G‘ from the second. Note that if we had used the second cube toget ‘D‘ instead, we would be missing a ‘G‘.
题目分析:
题意:给你若干个每个面刻着大写字母的多面体,让你判断给出的字符串能用以上给出的多面体拼出来吗?可构建二分图模型如下:对于每个字符串,其中的每个字母是集合A中的一个点,每个多面体是集合B中的一个点,若A中每个字符能在B中的立方体上找到,则该立方体与这个A中的这个点有一条边。最后检查最大匹配数是否为字符串长度。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
const int MAXN=52;
bool vis[MAXN];
int link[MAXN];
string s[MAXN],t[MAXN];
vector<int> g[MAXN]; //邻接阵存储图
int m,n;
vector<int> ans;
bool dfs(int s){
for(int i=0;i<g[s].size();++i){
int u=g[s][i];
if(vis[u]) continue;
vis[u]=true;
if(link[u]==-1 || dfs(link[u])){
link[u]=s;
return true;
}
}
return false;
}
int hungry(int t){
int ans=0;
memset(link,-1,sizeof(link));
for(int i=1;i<=t;++i){
memset(vis,false,sizeof(vis));
if(dfs(i)) ++ans;
}
return ans;
}
int main()
{
int i,j,k;
while(~scanf("%d%d",&n,&m)){
ans.clear();
for(i=1;i<=n;++i)
cin>>s[i];
for(i=1;i<=m;++i)
cin>>t[i];
for(i=1;i<=m;++i){
for(j=0;j<=MAXN;++j)
g[j].clear();
int len=t[i].size();
for(j=0;j<len;++j){
for(k=1;k<=n;++k){
string::size_typepos=s[k].find(t[i][j]);
if(pos==string::npos) continue;
g[k].push_back(j+1);
}
}
if(hungry(n)==len)
ans.push_back(i-1);
}
if(ans.size()==0) printf("-1\n");
else
for(i=0;i<ans.size();++i){
if(i) printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}
return 0;
eoj1854 Playing With Cubes 二分图最大匹配
原文地址:http://blog.csdn.net/fangpinlei/article/details/42193087