// https://pydefis.callicode.fr/defis/JeuYoda/txt #include #include #include #include using namespace std; bool backtrack(const vector &mots, unordered_map &choisi, vector &liste) { int n = mots.size(); if((int)liste.size() == n) { return true; } string dernierMot = liste.back(); string dern = dernierMot.substr(dernierMot.size() - 3); for(string mot : mots) { if(choisi[mot] == false) { string prem = mot.substr(0, 3); if(prem == dern) { liste.push_back(mot); choisi[mot] = true; if(backtrack(mots, choisi, liste) == true) { return true; } // backtrack liste.pop_back(); choisi[mot] = false; } } } return false; } int main() { vector mots; string m; while(cin >> m) mots.push_back(m); for(string mot : mots) cout << mot << ' '; cout << '\n'; unordered_map choisi; for(auto mot : mots) { for(auto m : mots) choisi[m] = false; vector liste; liste.push_back(mot); choisi[mot] = true; cout << "Mot de début : " << mot << '\n'; if(backtrack(mots, choisi, liste)) // c'est gagné ! { cout << "C'est gagné !\n"; for(auto mot : liste) cout << mot << ' '; cout << '\n'; } else { cout << "On ne peut pas commencer par " << mot << '\n'; } } return 0; } // main()