字符串暴力枚举子序列求LCS

题意:

求n个串里的LCS,长度相同时按照字典序排序

solution:

断环为链,二进制枚举子序列,压入vector,按照字典序排序

把出现次数为n的,压入第二个vector

输出最长的第二个vector里最长的序列

 1 #include<bits/stdc++.h>
 2 #define endl '
'
 3 using namespace std;
 4 bool cmp(string a,string b)
 5 {
 6     return a.size()<b.size();
 7 }
 8 int main() {
 9 //    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
10     int n;
11     while(cin >> n) {
12         string s;
13         vector<string>a;
14         if(n == 1) {
15             cin >> s;
16             int sz= s.size();
17             vector<string>xx;
18             s+=s;
19            // cout << s << endl;
20             for(int i = 0; i < sz;i++) xx.push_back(s.substr(i,sz));//截取起点为i长度为sz的字串 
21             sort(xx.begin(),xx.end());
22             for(int i = 0; i < xx.size(); i++) cout <<xx[i]<<endl;
23             cout << xx[0] << endl;continue;
24         }
25         
26         for(int i = 0; i < n; i++) {
27             cin >> s;
28             int sz = s.size();
29             s += s;
30             vector<string>b;
31             for(int j = 0; j < sz; j++){//断环为链 
32                 for(int k = 1; k < (1 << sz); k++) {//用枚举子集来表示序列 
33                     string t;
34                     for(int p = 0; p < sz; p++) {
35                         if(k & (1 << p)) {
36                             t += s[j + p];
37                         }
38                     }
39                     //cout << t << endl;
40                     b.push_back(t);
41                 }
42                 //cout << endl;
43             }
44             sort(b.begin(),b.end());
45             b.erase(unique(b.begin(),b.end()),b.end());//每一个串的子序列按照字典序排序并去重 
46             for(int j = 0; j < b.size(); j++) {//把每一个串的子序列加入总的字符串里 
47                 a.push_back(b[j]);
48             }
49         }
50         sort(a.begin(),a.end());//按照所有串的子序列 
51 //        for(int i = 0; i < a.size(); i++) cout << a[i] <<endl;
52         int ct = 1, maxx = 0;
53         vector<string>c,d;
54         for(int i = 1; i < a.size(); i++) {
55             if(a[i] == a[i- 1]) ct++;
56             else ct = 1;
57             if(ct == n) c.push_back(a[i]),maxx=max(maxx,(int)a[i].size());//n个串里的公共子序列 
58         }
59 //        for(int i = 0; i < c.size(); i++) cout << c[i] <<endl;
60         if(c.size() == 0) {
61             cout << 0 << endl; continue;
62         }
63         for(int i = 0 ; i < c.size(); i++) {
64             if(c[i].size() == maxx){
65                 cout<<c[i]<<endl;break;
66             }
67         }
68     }
69     return 0;
70 }
View Code
原文地址:https://www.cnblogs.com/klaycf/p/9692037.html