PAT (Top Level) Practice1004 To Buy or Not to Buy - Hard Version (35 分)
阿新 • • 發佈:2018-12-23
題目連結:https://pintia.cn/problem-sets/994805148990160896/problems/994805155206119424
暴力,基本上不會超時,dfs加上一些剪枝
演算法:dfs
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<set> #include<map> #include<vector> #define N 150 #define inf 0x3f3f3f using namespace std; int n; int op[N][N]; int po[N][N]; string str[N]; string q[N]; int num[N]; int ans = 0; int vis[N]; int re = inf; int flagss = 0; void dfs(int index,int u,string s) { if (flagss == 1) return; if (s.size() == 0) { re = min(re, index); if (re == 0) { flagss = 1; } return ; } for (int i = u; i <= ans; i++) { set<char>p; int ks[N]; int sd = 0; for (int j = 0; j < s.size();j++) { if (!p.count(s[j])) { if (op[i][s[j]] == 0) { sd = 1; break; } ks[s[j]] = 1; p.insert(s[j]); } else { if (ks[s[j]] + 1 > op[i][s[j]]) { sd = 1; break; } ks[s[j]]++; } } if (sd == 1) { break; } string s1 = s; int nu1 = str[num[i]].size(); int nu2 = s1.size(); for (string::iterator iter = q[i].begin(); iter != q[i].end();) { if (s1.find_first_of(*iter) != -1) { s1.erase(s1.find_first_of(*iter), 1); iter++; } else { iter++; } } int nu = nu1 - (nu2 - s1.size()); dfs(index + nu, u + 1, s1); if (flagss == 1) return; } } int main() { string s; string s2; cin >> s; s2 = s; memset(vis, 0, sizeof(vis)); scanf("%d", &n); int flag = 0; int flags = 0; for (int i = 0; i < n; i++) { cin >> str[i]; if (str[i] == s) { flags = 1; } if (flags == 1) continue; flag = 0; for (int j = 0; j < str[i].size(); j++) { if (s.find(str[i][j])!=string::npos) { if (flag == 0) { q[++ans] = ""; q[ans] += str[i][j]; po[ans][str[i][j]] = 1; num[ans] = i; flag = 1; } else { q[ans] += str[i][j]; po[ans][str[i][j]]++; } } } } if (flags == 1) { cout << "Yes " << flags-1 << endl; return 0; } memset(op, 0, sizeof(op)); for (int i = ans; i >= 1; i--) { for (int j = 0; j < s.size(); j++) { if (q[i].find(s[j]) != string::npos) { op[i][s[j]] = op[i + 1][s[j]] + po[i][s[j]]; } else { op[i][s[j]] = op[i + 1][s[j]]; } } } dfs(0, 1,s); if (re == inf) { for (int i = 1; i <= ans; i++) { for (string::iterator iter = q[i].begin(); iter != q[i].end();) { if (s2.find_first_of(*iter) != -1) { s2.erase(s2.find_first_of(*iter), 1); iter++; } else { iter++; } } } cout << "No " <<s2.size()<< endl; } else cout <<"Yes " <<re<< endl; return 0; }