CF278B 题解
==>题目传送门<==
题意
给你 $n$ 个字符串,让你构造一个字典序最小的字符串,使得这个字符串不是这 $n$ 个字符串中任意一个的字串。
分析
这道题看到大家都是用的 DFS 解决的,我来交一个 BFS 解决的方法。
我们可以从空串开始,每一次都在队列中加入本来的字符串加上任意一个字符的字符串。如果我们看到这个字符串没有是任何一个的字串,我们就可以认定这个字符串为答案。
鉴于题目 $n \le 30$ 且 $\lvert s_i \rvert \le 20$,摆明了想让我们暴力解决了这个题
代码片段
首先,我们需要一个函数来判断一个字符串是否是这些字符串的子串
1 2 3 4 5 6 7 8 9 10 11 12
| bool check(string str){ for(auto v:s){ for(int i=0;i+str.size()-1<v.size();i++){ string tmp=v.substr(i,str.size()); if(str==tmp){ return true; } } } return false; }
|
然后就是 BFS 的核心代码
我们只需要从空串开始,每次将队列头增加 a 到 z 的每一个字符。
如果队列头的字符串不是任意一个字符串的子串,我们就可以认定它为一个答案,并且由于 BFS 的性质,第一个找到的字符串肯定是最优的答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| void bfs(){ queue<string> q; q.push(""); while(s.size()){ string top=q.front(); q.pop(); if(!check(top)&&top!=""){ cout<<top; return; } for(char x='a';x<='z';x++){ q.push(top+x); } } }
|
AC 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include<bits/stdc++.h> using namespace std; vector<string> s; bool check(string str){ for(auto v:s){ for(int i=0;i+str.size()-1<v.size();i++){ string tmp=v.substr(i,str.size()); if(str==tmp){ return true; } } } return false; } void bfs(){ queue<string> q; q.push(""); while(s.size()){ string top=q.front(); q.pop(); if(!check(top)&&top!=""){ cout<<top; return; } for(char x='a';x<='z';x++){ q.push(top+x); } } } int n; string x; int main(){ cin>>n; for(int i=1;i<=n;i++){ cin>>x; s.push_back(x); } bfs(); return 0; }
|
AC记录:https://codeforces.com/contest/278/submission/290355703