PAT T1004 To Buy or Not to Buy - Hard Version
暴力搜索加剪枝~
#include<bits/stdc++.h> using namespace std; const int maxn=1014; string t; string s[maxn]; int pos[maxn],pos1[maxn]; int N; int nowLength; int minLength=1e9; int tle; void dfs (int v,int cnt) { if (tle==101) return; tle++; if (nowLength>minLength) return; if (cnt>=t.length()) { minLength=min(minLength,nowLength); return; } v++; while (v<=N) { int a=cnt; int pos2[maxn]; for (int i=0;i<s[v].length();i++) pos2[s[v][i]]=pos1[s[v][i]]; for (int i=0;i<s[v].length();i++) if (pos[s[v][i]]>pos1[s[v][i]]) cnt++,pos1[s[v][i]]++; nowLength+=s[v].length(); dfs (v,cnt); cnt=a; for (int i=0;i<s[v].length();i++) pos1[s[v][i]]=pos2[s[v][i]]; nowLength-=s[v].length(); v++; } } int main () { cin>>t>>N; for (int i=1;i<=N;i++) cin>>s[i]; for (int i=0;i<t.length();i++) pos[t[i]]++; dfs (0,0); int ans=0; for (int i=1;i<=N;i++) for (int j=0;j<s[i].length();j++) if (pos[s[i][j]]) pos[s[i][j]]--; for (int i=0;i<t.length();i++) ans+=pos[t[i]],pos[t[i]]=0; if (minLength<1e9) printf ("Yes %d",minLength-t.length()); else printf ("No %d",ans); return 0; }