算法问题实战策略 DICTIONARY

时间:2021-08-02 06:20:52

地址 https://algospot.com/judge/problem/read/DICTIONARY

算法问题实战策略 DICTIONARY

算法问题实战策略 DICTIONARY

解法 构造一个26字母的有向图 判断无回路后 就可以输出判断出来的字符序了

比较各个字母的先后次序不必用一个单词分别同其他单词比较 只需要将临近的两个单词一一比较即可

证明如下

算法问题实战策略 DICTIONARY

算法问题实战策略 DICTIONARY

算法1 中判断有无回路 采取的是DFS方法

代码

 #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory.h> using namespace std; /*
3
3
ba
aa
ab
5
gg
kia
lotte
lg
hanhwa
6
dictionary
english
is
ordered
ordinary
this
======================================================
INVALID HYPOTHESIS
ogklhabcdefijmnpqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
*/ int n; vector<pair<int, int>> vvmap; void Compare(string s1, string s2)
{
int len = min(s1.size(),s2.size()); for (int i = ; i < len; i++) {
if (s1[i] == s2[i]) continue;
int a = s1[i] - 'a';
int b = s2[i] - 'a';
vvmap.push_back({a,b});
break;
}
} vector<int> seen, order; void dfs(int here) {
seen[here] = ;
for (int there = ; there < ; ++there) {
if ( find(vvmap.begin(),vvmap.end(),pair<int,int>(here,there)) != vvmap.end()
&& seen[there] == )
dfs(there);
}
order.push_back(here);
} vector<int> topologicalSort()
{
seen = vector<int>(, );
for (int i = ; i < vvmap.size(); i++) {
//记录需要dfs的索引
if (seen[vvmap[i].first] == )
seen[vvmap[i].first] =;
if (seen[vvmap[i].second] == )
seen[vvmap[i].second] = ;
}
order.clear();
for (int i = ; i < ; i++) {
if (seen[i] == )
dfs(i);
} reverse(order.begin(), order.end()); for (int i = ; i < order.size(); i++) {
for (int j = i+; j < order.size(); j++) {
if (find(vvmap.begin(), vvmap.end(), pair<int, int>(order[j], order[i])) != vvmap.end())
{
return vector<int>();
}
}
}
return order;
} int main()
{
cin >> n; while (n--) {
int m;
vvmap.clear();
cin >> m;
vector<string> vs;
for (int i = ; i < m; i++) {
string s;
cin >> s;
vs.push_back(s);
} for (int i = ; i < vs.size()-; i++) {
Compare(vs[i], vs[i + ]);
} vector<int> ans = topologicalSort();
if (ans.empty()) {
cout << "INVALID HYPOTHESIS" << endl;
}
else {
for (int i = ; i < ; i++) {
if (find(ans.begin(), ans.end(), i) == ans.end()) {
ans.push_back(i);
}
} for (int i = ; i < ans.size(); i++) {
cout << (char)(ans[i] + 'a');
}
cout << endl;
}
} }