Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- #include <map>
- #include <set>
- using namespace std;
- typedef long long ll;
- const int maxn = 205;
- int n, o;
- const int alphabet_size = 26;
- int trie[maxn][alphabet_size];
- ll dp[alphabet_size][1 << 9][maxn];
- map<int, int> at_trie_end_of_word;
- ll rek(int at, int visited, int at_trie) {
- if(at == o and __builtin_popcount(visited) == n) {
- return 1;
- }
- if(at >= o) {
- return 0;
- }
- if(dp[at][visited][at_trie] != -1) {
- return dp[at][visited][at_trie];
- }
- ll res = 0;
- for(int i = 0; i < 26; i++) {
- int c = trie[at_trie][i];
- res += rek(at + 1, visited | at_trie_end_of_word[c], c);
- }
- return dp[at][visited][at_trie] = res;
- }
- set<string> words;
- void gen_strings(int at, int visited, int at_trie, string s) {
- if(at == o and __builtin_popcount(visited) == n) {
- words.insert(s);
- return;
- }
- if(at >= o) {
- return;
- }
- for(int i = 0; i < 26; i++) {
- int c = trie[at_trie][i];
- if(rek(at + 1, visited | at_trie_end_of_word[c], c) > 0) {
- gen_strings(at + 1, visited | at_trie_end_of_word[c], c, s + (char) (i + 'a'));
- }
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- memset(dp, -1, sizeof dp);
- cin >> o >> n;
- vector<string> v(n);
- for(int i = 0; i < n; i++) {
- cin >> v[i];
- }
- map<string, int> m1;
- map<int, string> m2;
- int cnt = 1;
- for(int i = 0; i < n; i++) {
- string tmp = "";
- for(int j = 0; j < (int) v[i].size(); j++) {
- tmp += v[i][j];
- m1[tmp] = cnt;
- m2[cnt] = tmp;
- cnt++;
- }
- }
- m1[""] = 0;
- m2[0] = "";
- for(int i = 0; i <= 100; i++) {
- if(m2.find(i) != m2.end()) {
- for(int j = 0; j < n; j++) {
- if((int) m2[i].size() >= (int) v[j].size() and m2[i].find(v[j]) != string::npos) {
- at_trie_end_of_word[i] |= (1 << j);
- }
- }
- }
- string tmp = "";
- for(int j = 0; j < 26; j++) {
- tmp = m2[i] + (char) (j + 'a');
- while(m1.find(tmp) == m1.end()) {
- tmp.erase(tmp.begin());
- }
- trie[i][j] = m1[tmp];
- }
- }
- ll res = rek(0, 0, 0);
- if(res <= 30) {
- cout << res << endl;
- gen_strings(0, 0, 0, "");
- for(string s : words) {
- cout << s << "\n";
- }
- }
- else {
- cout << res << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement