题目:http://codeforces.com/gym/100735/problem/H
Informikas was cleaning his drawers while he found a toy of his childhood. Well, it's not just a toy, it's a bunch of cubes with letters and digits written on them.
Informikas remembers that he could have make any word he could think of using these cubes. He is not sure about that now, because some of the cubes have been lost.
Informikas has already come up with a word he would like to make. Could you help him by saying if the word can be built from the cubes in the drawer?
On the first line of input there is a string S, consisting of lowercase English letters, and an integer N (4 ≤ |S| ≤ 20, 1 ≤ N ≤ 100) – the word Informikas want to build and the number of cubes. On the every of the following N lines there are 6 characters. Every of those characters is either a lowercase English letter or a digit.
It is guaranteed that the string S consists only of lowercase English letters.
Output one word, either "YES", if the word can be built using given cubes, or "NO" otherwise.
dogs 4
d 1 w e 7 9
o 2 h a v e
g 3 c o o k
s 3 i e s 5
YES
banana 6
b a 7 8 9 1
n 1 7 7 7 6
a 9 6 3 7 8
n 8 2 4 7 9
a 7 8 9 1 3
s 7 1 1 2 7
NO
题意很简单就不多阐述了
自己的思路:
dfs暴搜+一点点的剪枝就过了,复杂度上按理算是不会过的
ac代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<queue> #include<set> #include<algorithm> #include<map> #define maxn 10005 using namespace std; typedef struct{ int x,y; }zuobiao; zuobiao zz[maxn]; int vis[maxn],ans,len,n,num; char str[25]; char mp[105][10]; void dfs() { if(ans==len)return ; else{ for(int i=0;i<n;i++){ if(vis[i])continue; for(int j=0;j<6;j++) { if(mp[i][j]==str[ans]) { ans++; vis[i]=1; if(ans==len)return; dfs(); if(ans==len)return; ans--; vis[i]=0; break; } } } } } int main() { scanf("%s",str); cin>>n; num=0; for(int i=0;i<n;i++) { for(int j=0;j<6;j++) { if(j!=n-1) scanf("%c ",&mp[i][j]); else scanf("%c",&mp[i][j]); if(mp[i][j]==str[0]) { zz[num].x=i; zz[num].y=j; num++; } } getchar(); } memset(vis,0,sizeof(vis)); len=strlen(str); for(int i=0;i<num;i++) { vis[zz[i].x]=1; ans=1; dfs(); if(len==ans) { cout<<"YES"<<endl; return 0; } vis[zz[i].x]=0; ans=0; } cout<<"NO"<<endl; return 0; }
反正就是不可思议的过了。
然后呢附上大佬们的思路吧!
二分匹配+匈牙利算法 http://www.renfei.org/blog/bipartite-matching.html
#include <bits/stdc++.h> using namespace std; const int maxn = 256; char str[maxn]; int n,Link[maxn]; bool w[maxn][maxn],used[maxn]; bool match(int u){ for(int i = 0; i < n; ++i){ if(used[i] || !w[u][i]) continue; used[i] = true; if(Link[i] == -1 || match(Link[i])){ Link[i] = u; return true; } } return false; } int main(){ while(~scanf("%s",str)){ scanf("%d",&n); memset(w,false,sizeof w); char tmp[20]; for(int i = 0; i < n; ++i){ for(int j = 0; j < 6; ++j){ scanf("%s",tmp); for(int k = 0; str[k]; ++k) if(str[k] == tmp[0]) w[k][i] = true; } } memset(Link,-1,sizeof Link); int ret = 0; for(int i = 0; i < 26; ++i){ memset(used,false,sizeof used); if(match(i)) ++ret; } printf("%s ",strlen(str) == ret?"YES":"NO"); } return 0; }