My answer, but the complexity is not very satisfied, is an exponential level of complexity. But the test data is weak, or AC. Found on the Internet, are brute force solution, do not know whether there is a better solution.
Two errors were made in the solution, the first, map<int, and vector<int>> definitions were not accepted. But this must be a legitimate C + + definition. The second one, forgetting to consider the constraints of mapping the inverse of the characters. That is, "AB" may be translated into "CC", which is wrong. Word putting from source to target, from Target to source, there should be no one-to-many mappings.
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>
using namespace std;
vector<string> words;
vector<string> m_dic[81];
vector<int> finalMatchRelation;
bool findMatchString(int index, vector<int> matchedCharacter, vector<int> getMatched) {
if (index >= words.size()) {
finalMatchRelation = matchedCharacter;
return true;
}
vector<int> matchedCharacterBackup = matchedCharacter;
vector<int> getMatchedBackup = getMatched;
int l = words[index].size();
for (int i = 0; i < m_dic[l].size(); i++) {
bool ok = true;
for (int j = 0; j < words[index].size() && ok; j++) {
int srcCharIndex = words[index][j] - 'a';
int objCharIndex = m_dic[l][i][j] - 'a';
if (matchedCharacter[srcCharIndex] == -1 && getMatched[objCharIndex] == -1) {
matchedCharacter[srcCharIndex] = objCharIndex;
getMatched[objCharIndex] = srcCharIndex;
}
else if (matchedCharacter[srcCharIndex] == (m_dic[l][i][j] - 'a')) {
continue;
}
else {
ok = false;
}
}
if (ok) {
bool goodResult = findMatchString(index + 1, matchedCharacter, getMatched);
if (goodResult) {
return true;
}
}
matchedCharacter = matchedCharacterBackup;
getMatched = getMatchedBackup;
}
return false;
}
int main() {
string placeHolder;
int n;
cin >> n;
getline(cin, placeHolder);
for (int i = 0; i < n; i++) {
string ts;
getline(cin, ts);
m_dic[ts.size()].push_back(ts);
}
string s;
while (getline(cin, s)) {
vector<int> matchRelation(26, -1), getMatched(26, -1);
stringstream ss(s);
string ts;
words.clear();
while (ss >> ts) {
words.push_back(ts);
}
string result = "";
if (findMatchString(0, matchRelation, getMatched)) {
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ')
result.push_back(' ');
else
result.push_back('a' + finalMatchRelation[s[i] - 'a']);
}
}
else {
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ')
result.push_back(' ');
else
result.push_back('*');
}
}
cout << result << endl;
}
return 0;
}
Programming-challenges Crypt Kicker (110204)